def monte_carlo(self, board, t, depth=None): self.order_count += 1 if depth is None: depth = [] ttt = TicTacToe() ttt.copy(board) # ランダムに自分の一手を行う position = _pick_one(ttt) ttt.set(position, t) t_enemy = TicTacToe.O if t == TicTacToe.X else TicTacToe.X depth = depth + [(t, position)] # 結果を判定。決着がつかないなら再帰的に繰り返す status = ttt.eval() if status != TicTacToe.ON_PROGRESS: result = { "game_result": status, "moves": depth, TicTacToe.WIN_O: 0, TicTacToe.WIN_X: 0, TicTacToe.DRAW: 0, } result[status] += 1 return result result = { "position": position, TicTacToe.WIN_O: 0, TicTacToe.WIN_X: 0, TicTacToe.DRAW: 0, } mc_results = [ self.monte_carlo(ttt.board, t_enemy, depth) for _ in range(1) ] for mc_result in mc_results: result[TicTacToe.WIN_O] += mc_result[TicTacToe.WIN_O] result[TicTacToe.WIN_X] += mc_result[TicTacToe.WIN_X] result[TicTacToe.DRAW] += mc_result[TicTacToe.DRAW] return result
def play_tictactoe(): """ Executes TicTacToe between two players """ print "Size of Tic Tac Toe board: 3" size = 3 marker = raw_input("Choose the marker u want to use from %s: " % MARKER) if marker not in MARKER: print "wrong marker chossen" return t = TicTacToe(size) print "Tic Tac Toe board" t.display() turn = MARKER.index(marker) player = 0 inpt = '' while (inpt not in QUIT): try: if player != 0: make_move_cpu(t, MARKER[turn], inpt) else: inpt = raw_input("Player %s make your move: " % (player + 1)) t.make_move(inpt, MARKER[turn]) t.display() if t.is_winner(MARKER[turn]): print "Player %s wins" % ( (player + 1) if player == 0 else 'CPU') print "Game End" return turn = turn ^ 1 player = player ^ 1 except TieGameException as e: print(e) return except InvalidMoveException as e: print(e) except Exception as e: print "Error: Exiting game" return
def test_o_winner_game(self): board = TicTacToe() moves = [(0, 2), (2, 0), (1, 0), (2, 1), (0, 0), (2, 2)] for move in moves: board.play(move) self.assertEqual(board.state(), GameState.Win) self.assertEqual(board.legal_moves(), []) self.assertIs(board.winner(), Player.O) self.assertTrue((board.to_tensor()[:, :, 1] == np.array([[1, 0, 1], [1, 0, 0], [0, 0, 0]])).all()) self.assertTrue((board.to_tensor()[:, :, 2] == np.array([[0, 0, 0], [0, 0, 0], [1, 1, 1]])).all())
def test_some_game(self): board = TicTacToe() board.play((0, 0)) board.play((1, 1)) board.play((2, 0)) self.assertEqual(board.state(), GameState.Continue) self.assertEqual(board.turn(), Player.O) self.assertCountEqual(board.legal_moves(), [(0, 1), (0, 2), (1, 0), (1, 2), (2, 1), (2, 2)]) self.assertIs(board.winner(), None) self.assertTrue((board.to_tensor()[:, :, 0] == -np.ones((3, 3))).all()) self.assertTrue((board.to_tensor()[:, :, 1] == np.array([[1, 0, 0], [0, 0, 0], [1, 0, 0]])).all()) self.assertTrue((board.to_tensor()[:, :, 2] == np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]])).all())
def __init__(self): self.ttt = TicTacToe() CANVAS_SIZE = 300 self.TILE_SIZE = CANVAS_SIZE / 3 self.root = tkinter.Tk() self.root.title("틱 택 토") self.root.geometry(str(CANVAS_SIZE) + "x" + str(CANVAS_SIZE)) self.root.resizable(width=False, height=False) self.canvas = tkinter.Canvas(self.root, bg="white", width=CANVAS_SIZE, height=CANVAS_SIZE) self.canvas.pack() self.images = dict() self.images["O"] = tkinter.PhotoImage(file="img/O.gif") self.images["X"] = tkinter.PhotoImage(file="img/X.gif") self.canvas.bind("<Button-1>", self.click_handler)
def play(agent): game = TicTacToe() while True: action = agent.qlearner.get_best_action(game.get_state()) winner = game.play(*action) if winner: print("**** you lost ****") return if game.is_ended(): print("**** draw ****") return x, y = input("input x and y: ").split() winner = game.play(int(x), int(y)) if winner: print("**** you won ****") return if game.is_ended(): print("**** draw ****") return
def test_game_x_wins() -> None: game = TicTacToe() game.make_turn(Player.X, col=1, row=1) game.make_turn(Player.O, col=1, row=0) game.make_turn(Player.X, col=0, row=2) game.make_turn(Player.O, col=2, row=0) game.make_turn(Player.X, col=0, row=0) game.make_turn(Player.O, col=2, row=1) # XOO # .XO # X.. assert not game.is_finished() assert game.winner() is None game.make_turn(Player.X, col=0, row=1) assert game.is_finished() assert game.winner() is Player.X
def test(self): """Test.""" tictactoe = TicTacToe() self.assertEqual( best_move(tictactoe, ((' ', 'o', 'x'), (' ', 'x', 'o'), (' ', 'x', 'o'))), (1, ((' ', 'o', 'x'), (' ', 'x', 'o'), ('x', 'x', 'o')))) self.assertEqual( best_move(tictactoe, (('x', 'o', ' '), (' ', 'x', 'o'), (' ', 'x', 'o'))), (0, (('x', 'o', 'x'), (' ', 'x', 'o'), (' ', 'x', 'o')))) # już stan końcowy self.assertEqual( best_move(tictactoe, ((' ', 'o', 'x'), (' ', 'x', 'o'), ('x', 'x', 'o'))), (1, None))
def main(): game = TicTacToe() game.printBoard() player = 1 while not game.gameOver(): print('Player ' + str(player) + '\'s turn!') y = input("What row do you want to play? ") while not checkInt(y): y = input("Please enter a whole number value. ") y = int(y) x = input("What column? ") success = game.turn(x, y, player) if(success): player = changePlayer(player) result = game.gameOver() winner = result[1] print("Player", winner, "has won!")
def create_match(player1: Player, player2: Player) -> TwoPlayerMatch: dim_board = 3 initial_board = np.zeros((dim_board, dim_board)) initial_player = player1 game = TicTacToe( player1=player1, player2=player2, dim_board=dim_board, ) game_state = TwoPlayerGameState( game=game, board=initial_board, initial_player=initial_player, ) return TwoPlayerMatch(game_state, max_sec_per_move=1000, gui=False)
def init(): # Optionally clear the screen. Play.clear() # Show the welcome banner. Play.show_banner() # Initialize the game backend. game = TicTacToe() # Let the X character to turn first. last_move = TicTacToe.CHARACTER_X_SYMBOL # Game loop while True: # Clear the screen on every (hopefully, frame). Play.clear() # Render (or shows) the board. Play.render_board(game) # Getting the winner. # This method is used to prevent bad experience if we had to # call `player_moves` in the beginning. winner = game.get_winner() # Check for the winner existance. if len(winner) > 0: print("Game has been ended!") print("The winner is Player {}".format(winner)) break # A condition where nobody (everybody) won the game. In the other hand, tie is occured. elif len(game.get_player_moves_record(TicTacToe.CHARACTER_X_SYMBOL)) + len(game.get_player_moves_record(TicTacToe.CHARACTER_O_SYMBOL)) == 9: print("Game tied!") break # Check and validate all player's move. Play.player_moves(game, last_move) # Swap the turn. last_move = TicTacToe.CHARACTER_O_SYMBOL if last_move == TicTacToe.CHARACTER_X_SYMBOL else TicTacToe.CHARACTER_X_SYMBOL
def play_game(self): '''Main function to play the game. ''' self.game_status = 'In-Progress' game = TicTacToe() player1 = self.create_player(player_id=1) player2 = self.create_player(player_id=2) self.game_positions = game.generate_all_positions() self.available_choices = list(self.game_positions.keys()) round_count = 0 while len(self.available_choices) > 1: round_count += 1 print('\n') print(f'Round {round_count}:') print('---------') player1 = self.record_player_move(player1) player2 = self.record_player_move(player2) for player in [player1, player2]: if game.check_player_game_status(player): player_name = player['Name'] self.game_status = f'Player {player_name} has Won' break if self.game_status != 'In-Progress': game.display_current_positions(player1, player2) print('Game status:', self.game_status) return if self.game_status == 'In-Progress' and len( self.available_choices) >= 3: game.display_current_positions(player1, player2) print('Game status:', self.game_status) game.display_current_positions(player1, player2) self.game_status = 'Draw' print('Game status:', self.game_status) return
def test_agents(p1_type, p2_type): board = TicTacToe() player_1 = p1_type(code=1) player_2 = p2_type(code=-1) if isinstance(player_1, StudentAgent): player_1.load_agent(STUDENT_SOLUTION_PATH) if isinstance(player_2, StudentAgent): player_2.load_agent(STUDENT_SOLUTION_PATH) one_wins, two_wins, ties = 0, 0, 0 TESTS = 500 for _ in range(TESTS): board.reset() while not board.isDone(): state = board.get_state().copy() p1_action = player_1.act(state) new_state, reward, done, _ = board.step(p1_action, player_1.get_code()) if board.isDone(): break state = new_state.copy() p2_action = player_2.act(state) new_state, reward, done, _ = board.step(p2_action, player_2.get_code()) result = board.has_won() if result == 1: one_wins += 1 elif result == -1: two_wins += 1 else: ties += 1 return one_wins, two_wins, ties
def testTicTacToe(self): rand = random.Random(123456789) game = TicTacToe() minimax_agents = [MiniMaxAgent, AlphaBetaAgent] # Statistically MiniMax based agents should beat random agents even without a proper heuristic. for agent in minimax_agents: self.assertBetterThanRandom(agent(random=rand), game) # Statistically MiniMax based should improve with greater horizons. for agent in minimax_agents: self.assertBetterAgent(agent('Horizon1', horizon=1, random=rand), agent('Horizon5', horizon=5, random=rand), game, 20) # Statistically in MiniMax based agents having a simple heuristic should be better than none. for agent in minimax_agents: self.assertBetterAgent( agent('RandomHeuristic', random=rand), agent('SimpleHeuristic', heuristic=TicTacToe.simple_heuristic, random=rand), game)
def main(): while (True): option = 0 #MULTIPLAYER IS IN TESTS print( "\n\n**Welcome to the Tic Tac Toe Game**\n\n>Select one:\n 1- Player One vs Computer\n 2- One Player vs Player Two\n 3- 2 Players Online\n" ) while (option != 1 and option != 2 and option != 3): answer = input(">") if re.match('^\d+$', answer): option = int(answer) if (option == 1 or option == 2 or option == 3): print("\nGood game...\n") else: print( "\nThere aren't that option in the Menu\nOnly 1 or 2 or 3\n" ) else: option = -1 print( "\nHey, you can't put a caracter different from an integer number!\n" ) game = TicTacToe(option) status = game.execute_game() print(game) if (status == 0): print("*Nobody Won*\n") elif (status == 1): print("*Player One Won*\n") elif (status == 2): print("*Player Two Won*\n") else: print("*Computer Won*\n") if (game.start_new_game() == False): return None else: game.reset_game()
def TicTacToeGame(): from tictactoe import TicTacToe from AI import AnywhereCanSet, RandomUntilEnd, MonteCarloTree game = TicTacToe() # AIを選ぶ ai = RandomUntilEnd(game, TicTacToe.X) while True: print "\n----" print game.print_board(True) cmd = raw_input("move?:") if cmd == "q": break if cmd == "r": game.reset() print game.print_board() continue try: position = int(cmd) game.set(position, TicTacToe.O) except Exception as e: print e.message continue # print game.print_board() # print "status:", game.eval() print ai.play() print game.print_board() print "status:", game.eval() if game.eval() != TicTacToe.ON_PROGRESS: game.reset() print "\n\nnew game!" print game.print_board()
def get_message(self, channel, message, user): players = self.user_manager.get_users_mentioned(message) players.add(user) if len(players) > 2: self.msg_writer.send_message( "You may not have more than two players currently", channel) return tokens = message.split() size = 3 length = 3 match_type = False move = "" for token in tokens: if TicTacToeManager.size_command in token: numbers = re.search(r'\d+', token) if numbers: size = int(re.search(r'\d+', token).group()) elif TicTacToeManager.length_command in token: numbers = re.search(r'\d+', token) if numbers: length = int(re.search(r'\d+', token).group()) elif token == TicTacToeManager.bolton_command: match_type = TicTacToeManager.bolton_command elif token == TicTacToeManager.pvp_command: match_type = TicTacToeManager.pvp_command else: move = token if match_type: game = TicTacToe(size, length, match_type, players) self.game_manager.add_game(game, players, channel, TicTacToeManager.name) self.msg_writer.send_message(game.starting_message(), channel) else: self.game_manager.process_message(players, channel, TicTacToeManager.name, move, user)
# Main # This is the file to run from tictactoe import TicTacToe print('Welcome to Tic Tac Toe!') board = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] letter = '' move = '' bo = '' le = '' self = TicTacToe(board, letter, move, bo, le) # Prompting rules print('Would you like to know the rules of tic-tac-toe? (yes or no)') if input().lower().startswith('y'): print('''Tic-Tac-Toe is a two player game where both players alternate turns placing a mark of their choice (typically O or X) on a 3x3 grid, until either: # One of the players gets 3 of their marks in a row; whether its horizontal, vertical, or diagonal. The player who gets 3 of their marks in a row wins. # The grid is entirely filled with marks and neither of the players have 3 marks in a row. This ends in a stalemate. Good luck!''') while True: # Reset the board player1Letter, player2Letter = self.inputPlayerLetter() turn = self.whoGoesFirst() print(turn + ' will go first.')
if os.path.exists(args.file1): with open(args.file1, 'rb') as fp: state_dict1 = pickle.load(fp) else: state_dict1 = {} if args.file2: if os.path.exists(args.file2): with open(args.file2, 'rb') as fp: state_dict2 = pickle.load(fp) else: state_dict2 = {} for i in range(args.n): tictactoe = TicTacToe() Player1 = RLTicTacToeAgent(tictactoe, state_dict1) Player2 = RandomTicTacToeAgent(tictactoe) tictactoe.add_agent(Player1, 'x') tictactoe.add_agent(Player2, 'o') while not tictactoe.game_has_ended()[0]: next_move1 = Player1.emit_move() tictactoe.move(next_move1) if not tictactoe.game_has_ended()[0]: next_move2 = Player2.emit_move() tictactoe.move(next_move2) if args.verbose:
self.stats.process(agents, match_num, move_num, d, g) yield (match_num, move_num, d, g) yield (None, None, self.stats, self.game) class Pyramid_Contest(Contest): """ Agents play count matches againts other. The winner gets to the next round, and so on until the contest has one winner. """ def __init__(self, game, agents, count=1): Contest.__init__(self, game, agents) self.count = count def run(self): """ TODO winners = list(self.agents) iter_agents = itertools.cycle(winners) matches = [[iter_agents.next() for _ in range(len(players))] for _ in range(round(len(winners) / 2.0))] """ if __name__ == '__main__': from tictactoe import TicTacToe from _agents import RandomAgent, MiniMaxAgent rnd = random.Random() agentes = [RandomAgent(rnd, 'RandomAgent_%05d' % i) for i in range(1)] agentes.extend([MiniMaxAgent('MiniMaxAgent_%05d' % i, 3, rnd) for i in range(1)]) print(complete(AllAgainstAll_Contest(TicTacToe(), agentes, 5)))
return node.score @property def best_action(self): for child in self.root.children: if child.score == self.root.score: choice = child break state = self.root.value next_state = choice.value for i in range(9): if state[i] != next_state[i]: return i raise Exception('States are equal or different in size') def terminal(state): return winner(state, 1) or winner(state, 0) or state.count(None) == 0 def next_states(state, turn): indices = [i for i, x in enumerate(state) if x is None] if not terminal(state): return [state[:i] + [turn] + state[i + 1:] for i in indices] return [] if __name__ == '__main__': g = TicTacToe(MiniMaxTree) g.run()
import random from board import Board from randomai import RandomAI from pseudorandomai import PseudoRandomAI from humanai import HumanAI from tictactoe import TicTacToe if __name__ == "__main__": while True: board = Board() ttt = TicTacToe() print "Choose the match-up:" print "Type 1 for Random AI v/s Pseudo Random AI" print "Type 2 for Pseudo Random AI v/s Pseudo Random AI" print "Type 3 for Random AI v/s You" print "Type 4 for Pseudo Random AI v/s You" print "Type 5 for a 2 player game" choice = int(raw_input("Type in your choice: ")) if choice == 1: ttt.start(board, RandomAI(), PseudoRandomAI()) elif choice == 2: ttt.start(board, PseudoRandomAI(), PseudoRandomAI()) elif choice == 3: humanPlayer = HumanAI() ttt.start(board, RandomAI(), humanPlayer) elif choice == 4: humanPlayer = HumanAI() ttt.start(board, humanPlayer, PseudoRandomAI()) elif choice == 5: humanPlayer1 = HumanAI() humanPlayer2 = HumanAI()
# Set up the logger logger = logging.getLogger() logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="\n%(message)s") # Create the players from players import Human human = Human(logger=logger) # from agents.minimax import MiniMaxAgent # human = MiniMaxAgent() mcts_agent = MCTSAgentRandom(logger=logger) # Run the game game = TicTacToe([human, mcts_agent], shuffle=True, logger=logger) while True: game.run() generate_graph(mcts_agent.root_node) else: random.seed(7) mcts_agent = MCTSAgentRandom() mcts_agent.max_playouts = 100 mcts_agent.side = rules.CROSS # board = np.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) # board = np.asarray([[1, 0, 0], [0, -1, 0], [0, 1, 0]]) # board = np.asarray([[1, 0, -1], [0, 0, 0], [0, 0, 0]]) # board = np.asarray([[1, 0, -1], [0, 0, -1], [0, 0, 0]]) # board = np.asarray([[1, -1, 1], [0, -1, 0], [0, 1, 0]])
def state_alpha_beta(game, alpha, beta, state): """Wylicza wartość stanu.""" game_value = game.check_final_state(state) if game_value != None: return game_value if game.player_to_go(state) == 'max': for next_state in game.moves(state): alpha = max(alpha, state_alpha_beta(game, alpha, beta, next_state)) if beta <= alpha: break return alpha else: for next_state in game.moves(state): beta = min(beta, state_alpha_beta(game, alpha, beta, next_state)) if beta <= alpha: break return beta from tictactoe import TicTacToe if __name__ == '__main__': TICTACTOE = TicTacToe() print alpha_beta(TICTACTOE) print state_alpha_beta(TICTACTOE, -9999, +9999, ((' ', 'o', ' '), (' ', 'x', ' '), (' ', ' ', ' ')))
f'Enter the position {game.get_current_player_name()}: ')) print('\n') if not game.update_board(position_input): print('Wrong position entered') print('\n') continue winner = game.get_winner() show_board(game) if winner == None: print('Game Tie') print('\n') elif winner == 'X': print(game.get_player_names()[0], 'is the winner') print('\n') elif winner == 'O': print(game.get_player_names()[1], 'is the winner') print('\n') game = TicTacToe() choice = 'Y' while choice == 'Y' or choice == 'y': columns = shutil.get_terminal_size().columns print("TIC-TAC-TOE".center(columns)) play_game(game) choice = input('Do you want to play again? (Y/N)') print('\n')
import time from tictactoe import TicTacToe from player import Player from ai_player import AIPlayer p1 = Player() p2 = AIPlayer() # Train with 10000 games against itself. print('Learning...') t = time.time() for _ in range(10000): game = TicTacToe(p2, p2) game.start() print('Learned {} unique states from {:.0f} games in {:.2f} seconds'.format( len(p2.states['x']) + len(p2.states['o']), p2.games_played() / 2, time.time() - t)) # Only perform best moves. p2.epsilon = 0 # Play against human player. while True: game = TicTacToe(p1, p2) game.start()
def start_game(self) -> None: self.game = None self.game = TicTacToe() self.send_field()
def main(): game = TicTacToe() play_x(game)
playerA = Player(1, basic_h, 'Player A') playerB = Player(1, naive_h, 'Player B') stats = {'Player A wins': 0, 'Player B wins': 0, 'Tied': 0} # set the board size of the game board_size = 10 # set the ply search for the player k = 2 print('Players using K-ply =', k) playerA.set_k_ply(k) playerB.set_k_ply(k) # start the game with players A and B # use print_steps=False to remove printouts of moves game = TicTacToe(board_size, playerA, playerB, print_steps=True) for i in range(5): # Player A moves first game.reset() game.set_players(playerA, playerB) result, winner = game.start() print(result) if winner is None: stats['Tied'] += 1 else: stats['{} wins'.format(winner.name)] += 1 # Player B moves first game.reset() game.set_players(playerB, playerA)
def setUp(self): self.game = TicTacToe()