from time import sleep as sl from player import HumanPlayer, RandomPcPlayer, GeniusPcPlayer class TicTacToe: def __init__(self): self.board = [' ' for _ in range(9)] # El tablero es representado por una lista self.current_winner = None 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(): # 0 | 1 | 3 etc number_board = [[str(i+1) 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): #moves = [] #for (i, spot) in enumerate(self.board): # ['x', 'x', 'o'] --> [(0, 'x'), (1, 'x'), (2, 'o')] # if spot == ' ': # moves.append(i) #return moves 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, bando): if self.board[square] == ' ': self.board[square] = bando if self.winner(square, bando): self.current_winner = bando return True return False def winner(self, square, bando): # 3 en fila row_ind = square // 3 row = self.board[row_ind*3 : (row_ind + 1) * 3] if all([spot == bando for spot in row]): return True # 3 en columna col_ind = square % 3 column = [self.board[col_ind + i*3] for i in range(3)] if all([spot == bando for spot in column]): return True # 3 en diagonal if square % 2 == 0: diagonal1 = [self.board[i] for i in [0, 4, 8]] if all([spot == bando for spot in diagonal1]): return True diagonal2 = [self.board[i] for i in [2, 4, 6]] if all([spot == bando for spot in diagonal2]): return True return False def play(game, x_player, o_player, print_game=True): " Retorna el ganador del juego o None si es empate" if print_game: game.print_board_nums() bando = 'X' while game.empty_squares(): if bando == 'O': square = o_player.get_move(game) else: square = x_player.get_move(game) if game.make_move(square, bando): if print_game: print(bando + f' --> jugada en el cuadarante {square}') game.print_board() print(' ') if game.current_winner: if print_game: print('Victoria para ' + bando) return bando bando = 'O' if bando == 'X' else 'X' if print_game: sl(0.8) if print_game: print('Empate') if __name__ == '__main__': x_wins = 0 o_wins = 0 ties = 0 for _ in range(1000): x_player = RandomPcPlayer('X') o_player = GeniusPcPlayer('O') t = TicTacToe() result = play(t, x_player, o_player, print_game=False) if result == 'X': x_wins += 1 elif result == 'O': o_wins += 1 else: ties += 1 print(f"Despues de 1000 Juegos:\n\'X\' Gano: {x_wins} veces\n\'O\' Gano: {o_wins} veces\n Empates: {ties}")