It gave me this error:
import math
import random
class TicTacToe:
def init(self):
self.board = [’ ’ for _ in range(9)] # 3x3 tic tac toe board
self.current_winner = None # keep track of winner!
def print_board(self):
for row in [self.board[i * 3:(i + 1) * 3] for i in range(3)]:
print(‘| ’ + ’ | ‘.join(row) + ’ |’)
@staticmethod
def print_board_nums():
number_board = [[str(i) for i in range(j * 3, (j + 1) * 3)] for j in range(3)]
for row in number_board:
print(’| ’ + ’ | ‘.join(row) + ’ |’)
def available_moves(self):
return [i for i, spot in enumerate(self.board) if spot == ’ ‘]
def empty_squares(self):
return ’ ’ in self.board
def num_empty_squares(self):
return self.board.count(’ ')
def make_move(self, square, letter):
if self.board[square] == ’ ‘:
self.board[square] = letter
if self.winner(square, letter):
self.current_winner = letter
return True
return False
def winner(self, square, letter):
# check row
row_ind = square // 3
row = self.board[row_ind*3 : (row_ind + 1)3]
if all([s == letter for s in row]):
return True
# check column
col_ind = square % 3
column = [self.board[col_ind+i3] for i in range(3)]
if all([s == letter for s in column]):
return True
# check diagonals
if square % 2 == 0:
diagonal1 = [self.board[i] for i in [0, 4, 8]]
if all([s == letter for s in diagonal1]):
return True
diagonal2 = [self.board[i] for i in [2, 4, 6]]
if all([s == letter for s in diagonal2]):
return True
return False
Player class
class Player:
def init(self, letter):
self.letter = letter
def get_move(self, game):
pass
class RandomComputerPlayer(Player):
def init(self, letter):
super().init(letter)
def get_move(self, game):
square = random.choice(game.available_moves())
return square
class HumanPlayer(Player):
def init(self, letter):
super().init(letter)
def get_move(self, game):
valid_square = False
val = None
while not valid_square:
square = input(self.letter + ‘‘s turn. Input move (0-8): ‘)
try:
val = int(square)
if val not in game.available_moves():
raise ValueError
valid_square = True # if successful, then yay!
except ValueError:
print(‘Invalid square. Try again.’)
return val
class GeniusComputerPlayer(Player):
def init(self, letter):
super().init(letter)
def get_move(self, game):
if len(game.available_moves()) == 9:
square = random.choice(game.available_moves()) # randomly choose one
else:
square = self.minimax(game, self.letter)[‘position’]
return square
def minimax(self, state, player):
max_player = self.letter # yourself
other_player = ‘O’ if player == ‘X’ else ‘X’
# first, we want to check if the previous move is a winner
if state.current_winner == other_player:
# we should return position AND score because we need to keep track
return {‘position’: None,
‘score’: 1 * (state.num_empty_squares() + 1) if other_player == max_player else -1 * (
state.num_empty_squares() + 1)}
elif not state.empty_squares():
return {‘position’: None, ‘score’: 0}
if player == max_player:
best = {‘position’: None, ‘score’: -math.inf} # each score should maximize (be larger)
else:
best = {‘position’: None, ‘score’: math.inf} # each score should minimize
for possible_move in state.available_moves():
# step 1: make a move, try that spot
state.make_move(possible_move, player)
# step 2: recurse using minimax to simulate a game after making that move
sim_score = self.minimax(state, other_player) # now, we alternate players
# step 3: undo the move
state.board[possible_move] = ’ ‘
state.current_winner = None
sim_score[‘position’] = possible_move # this is the new
# step 4: update the dictionaries if necessary
if player == max_player: # we are trying to maximize the max_player
if sim_score[‘score’] > best[‘score’]:
best = sim_score # replace best
else: # but minimize the other player
if sim_score[‘score’] < best[‘score’]:
best = sim_score # replace best
return best
def play(game, x_player, o_player, print_game=True):
if print_game:
game.print_board_nums()
letter = ‘X’ # starting letter
# iterate while the game still has empty squares
while game.empty_squares():
if letter == ‘O’:
square = o_player.get_move(game)
else:
square = x_player.get_move(game)
if game.make_move(square, letter):
if print_game:
print(letter + f’ makes a move to square {square}’)
game.print_board()
print(’’)
if game.current_winner:
if print_game:
print(letter + ’ wins!’)
return letter # ends the loop and exits the game
letter = ‘O’ if letter == ‘X’ else ‘X’ # switches player
if print_game:
print(‘It’s a tie!’)
if name == ‘main’:
x_player = GeniusComputerPlayer(‘X’)
o_player = HumanPlayer(‘O’)
t = TicTacToe()
play(t, x_player, o_player, print_game=True)