diff --git a/TicTacToe.py b/TicTacToe.py index 14f56e2..c733b69 100644 --- a/TicTacToe.py +++ b/TicTacToe.py @@ -21,7 +21,7 @@ class Matrix: self.marked_case = 0 - def winer(self): + def winer(self, show=False): ''' Check if there is a winner return 0 if there is no winner yet @@ -29,19 +29,41 @@ class Matrix: return 2 if player 2 win ''' + # Check vertical lines for column in range(GRID_COLS): if self.cases[0][column] == self.cases[1][column] == self.cases[2][column] != 0: + if show: + color = PLAYER1_COLOR if self.cases[0][column] == 1 else PLAYER2_COLOR + initial_pos = (column * CASE_SIZE + CASE_SIZE//2, 20) + final_pos = (column * CASE_SIZE + CASE_SIZE//2, LENGHT - 20) + pygame.draw.line(screen, color, initial_pos, final_pos, LINE_WIDTH) return self.cases[0][column] + # Check horizontal lines for row in range(GRID_ROWS): if self.cases[row][0] == self.cases[row][1] == self.cases[row][2] != 0: + if show: + color = PLAYER1_COLOR if self.cases[0][column] == 1 else PLAYER2_COLOR + initial_pos = (20, row * CASE_SIZE + CASE_SIZE//2) + final_pos = (WIDTH - 20, row * CASE_SIZE + CASE_SIZE//2) + pygame.draw.line(screen, color, initial_pos, final_pos, LINE_WIDTH) return self.cases[row][0] # Check diagonals if self.cases[0][0] == self.cases[1][1] == self.cases[2][2] != 0: + if show: + color = PLAYER1_COLOR if self.cases[0][column] == 1 else PLAYER2_COLOR + initial_pos = (20, 20) + final_pos = (WIDTH - 20, LENGHT - 20) + pygame.draw.line(screen, color, initial_pos, final_pos, LINE_WIDTH) return self.cases[0][0] if self.cases[0][2] == self.cases[1][1] == self.cases[2][0] != 0: + if show: + color = PLAYER1_COLOR if self.cases[0][column] == 1 else PLAYER2_COLOR + initial_pos = (20, LENGHT - 20) + final_pos = (WIDTH - 20, 20) + pygame.draw.line(screen, color, initial_pos, final_pos, LINE_WIDTH) return self.cases[0][2] # Check if there is no winner yet return 0 @@ -148,6 +170,7 @@ class Game: self.player = 1 #1 = X, 2 = O self.gamemode = 'ai' #1v1 or 1vAI self.running = True + self.ai_starts = False self.lines() def draw_figures(self, row, column): @@ -188,12 +211,20 @@ class Game: self.gamemode = 'ai' def isover(self): - return self.matrix.winer() != 0 or self.matrix.isfull() + return self.matrix.winer(show=True) != 0 or self.matrix.isfull() def reset(self): self.__init__() screen.fill(BACKGROUND_COLOR) self.lines() + if self.ai_starts: + self.ai_first_move() + + def ai_first_move(self): + if self.gamemode == 'ai' and self.player == self.ai.player and self.ai_starts: + row, column = self.ai.evaluate(self.matrix) + self.make_move(row, column) + self.ai_starts = False def main(): @@ -216,6 +247,11 @@ def main(): # g-gamemode if event.key == pygame.K_g: game.change_gamemode() + + # s-start + if event.key == pygame.K_s: + game.ai_starts = not game.ai_starts + game.ai_first_move() #r-restart if event.key == pygame.K_r: @@ -255,5 +291,4 @@ def main(): game.running = False pygame.display.update() -main() - +main() \ No newline at end of file