@@ -18,12 +18,10 @@ class TicTacToe():
1818 SYMBOLS = {0: '-', 1: 'O', 2: 'X', }
1919
2020 def __init__(self):
21- self.board = self.makeBoard()
22- # Simple heads or tails, under 5.0 goes the player
21+ self.board = [[0] * 3 for i in [0] * 3]
22+ # Simple heads or tails, over 5.0 goes the player
2323 self.who_next = self.PLAYER if random.random() >= 0.5 else self.AI
24-
25- def makeBoard(self):
26- return [[0] * 3 for i in [0] * 3]
24+ self.total_moves = 0
2725
2826 def printBoard(self):
2927 symbols_to_print = ''
@@ -80,6 +78,7 @@ class TicTacToe():
8078 raise self.NoPlayableRoom()
8179
8280 def makePlay(self):
81+ self.choose_next_move()
8382 if self.who_next == self.PLAYER:
8483 self.PlayerPlay()
8584 else:
@@ -88,12 +87,37 @@ class TicTacToe():
8887 def choose_next_move(self):
8988 self.who_next = self.PLAYER if self.who_next == self.AI else self.AI
9089
90+ def checkForWinner(self):
91+ board = self.board
92+ # game needs at least 5 moves to be a winner
93+ if self.total_moves >= 5:
94+ # Check horizontals, then verticals, then diag:
95+ if board[0][0] == board[0][1] == board[0][2] or\
96+ board[1][0] == board[1][1] == board[1][2] or\
97+ board[2][0] == board[2][1] == board[2][2] or\
98+ board[0][0] == board[1][0] == board[2][0] or\
99+ board[0][1] == board[1][1] == board[2][1] or\
100+ board[0][2] == board[1][2] == board[2][2] or\
101+ board[0][0] == board[1][1] == board[2][2] or\
102+ board[2][0] == board[1][1] == board[0][2]:
103+
104+ return True, self.who_next
105+ return False, None
106+
91107 def loop(self):
92108 game_running = True
93109
94110 while(game_running):
95111 self.printBoard()
96112
113+ game_won, winner_index = self.checkForWinner()
114+ winner = 'You' if self.PLAYER == winner_index else 'The AI'
115+ if game_won:
116+ print(
117+ f"\nGame Over. {winner} won in {self.total_moves} moves\n")
118+ game_running = False
119+ break
120+
97121 try:
98122 self.makePlay()
99123 except self.NoPlayableRoom:
@@ -103,7 +127,7 @@ class TicTacToe():
103127 print('\nInvalid coordenates, please choose a valid spot\n\n')
104128 self.loop()
105129
106- self.choose_next_move()
130+ self.total_moves = self.total_moves + 1
107131
108132
109133 if __name__ == '__main__':