-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.py
More file actions
560 lines (525 loc) · 26.5 KB
/
game.py
File metadata and controls
560 lines (525 loc) · 26.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
import sqlite3
import pygame
import sys
from pygame_widgets.dropdown import Dropdown
import pygame_widgets
pygame.init()
from constants import *
from board import Board
from humanPlayer import HumanPlayer
from aiPlayer import AIPlayer
from button import Button
from toggle import Toggle
from counterButton import CounterButton
class Game:
"""
Handles and runs the game
Attributes:
- _db (DB): The database object used to manage the database
- _gameID (int): Stores the specific id of the game
- _window (Surface): The pygame surface which the GUI is drawn onto
- _showMoves (Bool): Stores the value of the show moves toggle on whether moves are shown to the user
- _cells (dict): Stores each cell on the board with the corresponding coordinates of the GUI window
- _player1Undos (int): Stores the number of undos player 1 has made
- _player2Undos (int): Stores the number of undos player 2 has made
- _board (Board): Stores the instance of the board object used in this game
- _searchDepth (int): Stores the search depth for this game
- _currentPlayer (int): The current player in the game - switched between 1 and 2
- _currentState (int): The id of the current state of the game
- _playerNames (dict): Stores each player number and their corresponding name
"""
def __init__(self, db, window, searchDepth, newGame, gameID, player1, player2):
self._db = db
self._gameID = gameID
self._window = window
self._showMoves = True
self._cells = self._generateCells()
# If the game is a new game (ie: not a loaded game)
if newGame:
# Number of undos set to 0
self._player1Undos = 0
self._player2Undos = 0
# Initialize the board and get the search depth for the minimax algorithm
self._board = Board(True, None, self._window)
self._searchDepth = searchDepth # Depth for AI's minimax algorithm
# Initialize the players as either humans or AIs based on the inputs and save the names for future use
self._initialisePlayers(player1, player2)
# Save this game to the database
connection = sqlite3.connect("othello.db")
cursor = connection.cursor()
cursor.execute("""
INSERT INTO GAME
VALUES (NULL, NULL, ?, ?, ?, ?, ?, ?, ?);
""", (0, player1, player2, searchDepth, 0, 0, 1))
cursor.close()
connection.commit()
# Get the GameID of this game
cursor = connection.cursor()
cursor.execute("""
SELECT GameID FROM GAME
WHERE USER1ID = ?
AND USER2ID = ?;
""", (player1, player2))
output = cursor.fetchall()
self._gameID = output[-1][0]
cursor.close()
connection.commit()
# Store the first game state in the database
cursor = connection.cursor()
cursor.execute(f"""
INSERT INTO GAME_STATE (GameID, BoardRepresentation)
VALUES ({self._gameID}, '{self._board.arrayToString()}');
""")
cursor.close()
connection.commit()
self._currentState = self._getCurrentState()
# Insert players starting scores into the database
cursor = connection.cursor()
cursor.execute(f"""
INSERT INTO SCORE
VALUES(?, ?, ?);
""", (self._player1.getID(), self._gameID, 2 * self._searchDepth))
cursor.execute(f"""
INSERT INTO SCORE
VALUES(?, ?, ?);
""", (self._player2.getID(), self._gameID, 2 * self._searchDepth))
cursor.close()
connection.commit()
# Set the current player to 1
self._currentPlayer = 1
self._play() # Start the game loop
else:
# Load an existing game from the database
connection = sqlite3.connect("othello.db")
cursor = connection.cursor()
cursor.execute(f"""
SELECT MAX(GAME_STATE.GameStateID) FROM GAME_STATE, GAME
WHERE GAME.GameID = {self._gameID}
AND GAME.GameID = GAME_STATE.GameID;
""")
output = cursor.fetchall()
currentStateID = output[0][0]
cursor.execute(f"""
SELECT BoardRepresentation FROM GAME_STATE
WHERE GameStateID = {currentStateID};
""")
output = cursor.fetchall()
currentBoard = output[0][0]
cursor.execute(f"""
SELECT User1ID, User2ID, SearchDepth, Player1Undos, Player2Undos FROM GAME
WHERE GameID = {gameID};
""")
output = cursor.fetchall()
player1 = output[0][0]
player2 = output[0][1]
self._searchDepth = output[0][2]
self._player1Undos = output[0][3]
self._player2Undos = output[0][4]
connection.close()
self._board = Board(False, self._stringToGameBoard(currentBoard), self._window)
self._initialisePlayers(player1, player2)
self._gameID = gameID
self._currentState = self._getCurrentState()
self._currentPlayer = self._getCurrentPlayer()
self._play() # Start the game loop
# Convert a string into a game board array
def _stringToGameBoard(self, string):
board = []
for i in range(0, 64, 8):
board.append([int(char) for char in string[i:i+8]])
return board
# Set up both the players for the game and store them for future use
def _initialisePlayers(self, player1, player2):
self._playerNames = {} # Dictionary to store player names
if player1 == 0:
self._player1 = AIPlayer(1, self._board, self._searchDepth) # Initialize player 1 as AI
else:
self._player1 = HumanPlayer(player1, 1, self._db.getUserDetails(player1)[0][1]) # Initialize player 1 as human
if player2 == 0:
self._player2 = AIPlayer(2, self._board, self._searchDepth) # Initialize player 2 as AI
else:
self._player2 = HumanPlayer(player2, 2, self._db.getUserDetails(player2)[0][1]) # Initialize player 2 as human
# Get the names of both players
self._playerNames[1] = self._player1.getName()
self._playerNames[2] = self._player2.getName()
return 0
# The main loop of the game
def _play(self):
previousMove = None
gameOver = False
# Main game loop that runs until the game ends
while not gameOver:
moveMade = False
self._displayBoard() # Display the current state of the board
pygame.display.flip()
# If there are legal moves each player can make (ie: the game is not over)
if not len(self._board.getValidMoves(self._currentPlayer)) == 0:
# The board is displayed
self._displayBoard()
endGame = False
closeGame = False
# If both players don't have any moves
else:
self._currentPlayer = self._switchPlayer(self._currentPlayer)
if len(self._board.getValidMoves(self._currentPlayer)) == 0:
endGame = True
closeGame = True
self._displayBoard()
pygame.display.flip()
# If the game hasn't been closed, make a move
if not closeGame:
# If the player is a computer, handle them making a move
if self._currentPlayer == 1:
if self._player1.getName() == "Computer":
move = self._player1.move(self._board)
moveMade = True
self._displayBoard()
else:
if self._player2.getName() == "Computer":
move = self._player2.move(self._board) # AI makes a move
moveMade = True
self._displayBoard()
# Handle user input
for event in pygame.event.get():
# If the user closes the window
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
endGame = True
# If the user clicks on the window, get the object which is clicked
if event.type == pygame.MOUSEBUTTONUP:
position = pygame.mouse.get_pos()
clickedObjects = [o for o in self._objects if o.rect.collidepoint(position)]
for clickedObject in clickedObjects:
self._clickedObject = clickedObject
if len(clickedObjects) == 0:
self._clickedObject = None
else:
objectType = self._clickedObject.getText()
value = self._clickedObject.isClicked()
# If the End Game button is clicked
if objectType == "End Game":
gameOver = True
closeGame = True
# If the Save Game button is clicked
elif objectType == "Save Game":
gameOver = False
playerToSave, saveSlot = self._saveGameMenu() # Get the inputs of the user from the menu
slots = ["SavedGame1", "SavedGame2", "SavedGame3"]
# Save the game
connection = sqlite3.connect("othello.db")
cursor = connection.cursor()
cursor.execute(f"""
UPDATE USER_DETAILS
SET {slots[saveSlot-1]} = {self._gameID}
WHERE UserID = {playerToSave};
""")
cursor.execute(f"""
UPDATE GAME
SET Player1Undos = {self._player1Undos},
Player2Undos = {self._player2Undos},
CurrentPlayer = {self._currentPlayer}
WHERE GameID = {self._gameID};
""")
cursor.close()
connection.commit()
gameOver = True
closeGame = True
# Handles the Show Moves toggle
elif objectType == "Show Moves":
if self._showMoves:
self._showMoves = False
else:
self._showMoves = True
# Handles the undo feature
elif objectType == "Undo":
currentBoard = self._board.getBoard()
# If the game is in the initial state, don't undo
if currentBoard != [[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 2, 1, 0, 0, 0],
[0, 0, 0, 1, 2, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0]]:
self._undo() # Undo the last move
if "Computer" in self._playerNames.values():
self._undo() # Undo again if playing against AI
else:
move = value
if self._currentPlayer == 1:
move = self._player1.move(self._board, move) # Human player makes a move
self._displayBoard()
moveMade = True
else:
move = self._player2.move(self._board, move) # Human player makes a move
self._displayBoard()
moveMade = True
pygame.display.flip()
if moveMade:
# Insert the new state to the database
self._currentState += 1
connection = sqlite3.connect("othello.db")
cursor = connection.cursor()
cursor.execute("""
INSERT INTO GAME_STATE VALUES (NULL, ?, ?, ?);
""", (self._gameID, self._currentState - 1, self._board.arrayToString()))
previousMove = move
# Update the scores of the 2 players, multiplying the score by the search depth if playing against an AI
score1, score2 = self._board.getScore()
if self._playerNames[1] != "Computer":
cursor.execute(f"""
UPDATE SCORE
SET Score = {(score1 - self._player1Undos) * self._searchDepth}
WHERE UserID = {self._player1.getID()}
AND GameID = {self._gameID};
""")
if self._playerNames[2] != "Computer":
cursor.execute(f"""
UPDATE SCORE
SET Score = {(score2 - self._player2Undos) * self._searchDepth}
WHERE UserID = {self._player2.getID()}
AND GameID = {self._gameID};
""")
self._currentPlayer = self._switchPlayer(self._currentPlayer)
gameOver = self._board.gameOver()
connection.commit()
# Get the winner
if not closeGame:
pygame.time.delay(3000) # Delay the display of the result to allow the user to see the final state
self._resultLoop() # Display the result of the game
# Update the database to say the game is finished
cursor = connection.cursor()
cursor.execute(f"""
UPDATE GAME
SET GameFinished = 1
WHERE GameID = {self._gameID};
""")
cursor.close()
connection.commit()
return 0
# Generate the cells dict
def _generateCells(self):
cells = {}
y = 132 + 32/2
for i in range(8):
x = 172 + 32/2
cells[f"{0}x{i}"] = ((x, y))
for j in range(7):
x += 32
cells[f"{j+1}x{i}"] = ((x, y))
y += 32
return cells
# Get the settings for the game to be saved using dropdowns
def _saveGameMenu(self):
self._objects = []
self._window.fill(GREY)
if "Computer" not in self._playerNames.values():
dropdownPlayerNo = Dropdown(self._window, 0, 10, 200, 75, name="Player To Save", choices=[f"{self._playerNames[1]}", f"{self._playerNames[2]}"], values=[1, 2], font=mediumFont, borderColour=BLACK, borderRadius=20, colour=RED)
dropdownSaveSlot = Dropdown(self._window, 400, 10, 200, 75, name="Slot to Save To", choices=["1", "2", "3"], values=[1, 2, 3], font=mediumFont, borderColour=BLACK, borderRadius=20, colour=RED)
button = Button(WIDTH / 2, 300, 100, 50, "Confirm", RED)
button.draw(self._window)
pygame.display.flip()
finished = False
while not finished:
self._window.fill(GREY)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
finished = True
if event.type == pygame.MOUSEBUTTONUP:
position = pygame.mouse.get_pos()
if button.rect.collidepoint(position):
_, confirmed = button.isClicked()
if confirmed:
if "Computer" not in self._playerNames.values():
playerToSaveNumber = dropdownPlayerNo.getSelected()
else:
for player in [1, 2]:
if self._playerNames[player] != "Computer":
playerToSaveNumber = player
saveSlot = dropdownSaveSlot.getSelected()
if playerToSaveNumber == 1:
playerToSave = self._player1.getID()
else:
playerToSave = self._player2.getID()
return playerToSave, saveSlot
pygame_widgets.update(events)
button.draw(self._window)
pygame.display.flip()
return 0
# Display the board on the GUI
def _displayBoard(self):
self._window.fill(GREY)
rectangle = pygame.Rect(0, 0, 256, 256)
rectangle.center = (WIDTH / 2, HEIGHT / 2 + 60)
pygame.draw.rect(self._window, DARK_GREY, rectangle)
pygame.draw.rect(self._window, BLACK, rectangle, 2)
# Render the names of both the players
self._renderText(largeFont, f"{self._playerNames[1]}", BLACK, 200, 70)
self._renderText(largeFont, f"{self._playerNames[2]}", WHITE, 400, 70)
# Render the scores of both the players
p1Score, p2Score = self._board.getScore()
self._renderText(massiveFont, f"{p1Score}", BLACK, 90, 70)
self._renderText(massiveFont, f"{p2Score}", WHITE, 510, 70)
# If the player is not a computer, display the number of undos they have made
if self._playerNames[1] != "Computer":
self._renderText(mediumFont, f"{self._playerNames[1]} Undos: {self._player1Undos}", BLACK, 90, 160)
if self._playerNames[2]!= "Computer":
self._renderText(mediumFont, f"{self._playerNames[2]} Undos: {self._player2Undos}", WHITE, 90, 200)
# Draw relevant buttons
endGameButton = Button(90, 275, 155, 60, "End Game", RED)
endGameButton.draw(self._window)
saveGameButton = Button(90, 350, 155, 60, "Save Game", RED)
saveGameButton.draw(self._window)
undoButton = Button(510, 200, 155, 60, "Undo", RED)
undoButton.draw(self._window)
showMovesToggle = Toggle(510, 350, 155, 60, "Show Moves", RED, GREEN, self._showMoves)
showMovesToggle.draw(self._window)
for coords in self._cells.values():
rectangle = pygame.Rect(0, 0, 32, 32)
rectangle.center = coords
pygame.draw.rect(self._window, BLACK, rectangle, 2)
self._objects = [saveGameButton, undoButton, showMovesToggle, endGameButton]
# Draw the counters onto the board
for row in range(8):
for column in range(8):
currentBoard = self._board.getBoard()
if currentBoard[row][column] != 0:
coords = self._cells[f"{column}x{row}"]
if currentBoard[row][column] == 1:
self._drawCounter(BLACK, coords)
else:
self._drawCounter(WHITE, coords)
# Display the legal moves
for move in self._board.getValidMoves(self._currentPlayer):
moveString = f"{move[1]}x{move[0]}"
coords = self._cells[moveString]
if self._showMoves: # Only display if the show moves toggle is True
if self._currentPlayer == 1:
colour = BLACK
else:
colour = WHITE
else:
colour = DARK_GREY
counterButton = CounterButton(self._window, coords[0], coords[1], 16, moveString, colour)
self._objects.append(counterButton)
pygame.display.flip()
return 0
# Draw an individual counter
def _drawCounter(self, colour, coords):
pygame.draw.circle(self._window, colour, coords, 16, 16)
return 0
# Render any text
def _renderText(self, font, text, colour, x, y):
textSurface = font.render(text, True, colour)
self._window.blit(textSurface, textSurface.get_rect(center=(x, y)))
return 0
# Reverts the game back to its previous state
def _undo(self):
# Update the number of undos
if self._switchPlayer(self._currentPlayer) == 1:
self._player1Undos += 1
else:
self._player2Undos += 1
# Get the previous game from the databse
connection = sqlite3.connect("othello.db")
cursor = connection.cursor()
cursor.execute(f"""
SELECT PreviousStateID
FROM GAME_STATE
WHERE GameStateID = {self._currentState}
AND GameID = {self._gameID};
""")
output = cursor.fetchall()
newStateID = output[0][0]
# Delete the last game state
cursor.execute(f"""
DELETE FROM GAME_STATE
WHERE GameStateID = {self._currentState}
AND GameID = {self._gameID};
""")
connection.commit()
# Get the representation of the board
cursor.execute(f"""
SELECT BoardRepresentation FROM GAME_STATE
WHERE GameStateID = {newStateID};
""")
output = cursor.fetchall()
connection.commit()
cursor.close()
currentBoard = output[0][0]
# Create a new board with the last game state
self._board = Board(False, self._stringToGameBoard(currentBoard), self._window)
self._currentState = newStateID
self._currentPlayer = self._switchPlayer(self._currentPlayer)
return 0
# Get the current StateID for the game
def _getCurrentState(self):
connection = sqlite3.connect("othello.db")
cursor = connection.cursor()
cursor.execute("SELECT GameStateID FROM GAME_STATE;")
output = cursor.fetchall()
currentState = output[-1][0]
cursor.close()
return currentState
# Work out which player's turn it is based on who made the last move
def _getCurrentPlayer(self):
connection = sqlite3.connect("othello.db")
cursor = connection.cursor()
cursor.execute("SELECT GameStateID FROM GAME_STATE;")
output = cursor.fetchall()
currentPlayer = output[0][0]
return currentPlayer
# Switches the current player to the other player
def _switchPlayer(self, player):
return 2 if player == 1 else 1
# Gets the winner of the game and prints the result
def _displayResult(self):
winner = self._board.getWinner()
self._window.fill(GREY)
if winner == 0:
textSurface = massiveFont.render("Draw!", True, BLACK)
else:
textSurface = largeFont.render(f"{self._playerNames[winner]} Wins!", True, BLACK)
p1Score, p2Score = self._board.getScore()
# If one of the players is a computer, only display the score of the human player
if "Computer" in self._playerNames.values():
p1Multiplier = p2Multiplier = self._searchDepth
if self._playerNames[1] == "Computer":
self._renderText(massiveFont, f"{(p2Score - self._player2Undos) * p2Multiplier}", WHITE, 520, 70)
else:
self._renderText(massiveFont, f"{(p1Score - self._player1Undos) * p1Multiplier}", BLACK, 80, 70)
else:
# Get the multiplier of each player to apply to the other player
p1Multiplier = self._db.getMultiplier(self._player2.getID)
p2Multiplier = self._db.getMultiplier(self._player1.getID)
self._renderText(massiveFont, f"{(p1Score - self._player1Undos) * p1Multiplier}", BLACK, 80, 70)
self._renderText(massiveFont, f"{(p2Score - self._player2Undos) * p2Multiplier}", WHITE, 520, 70)
self._window.blit(textSurface, textSurface.get_rect(center=(300, 160)))
endButton = Button(300, 275, 155, 60, "End", RED)
endButton.draw(self._window)
self._objects = [endButton]
pygame.display.flip()
return 0
# Display the results of the game until the user clicks the End Game button
def _resultLoop(self):
self._displayResult()
finished = False
while not finished:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
finished = True
if event.type == pygame.MOUSEBUTTONUP:
position = pygame.mouse.get_pos()
clickedObjects = [o for o in self._objects if o.rect.collidepoint(position)]
for clickedObject in clickedObjects:
self._clickedObject = clickedObject
if len(clickedObjects) == 0:
self._clickedObject = None
else:
buttonClicked, clicked = self._clickedObject.isClicked()
if buttonClicked == "End":
finished = True
pygame.display.flip()
return 0