def main(): run = True clock = pygame.time.Clock() board = Board() turn = 1 winner = None while run: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if (turn == -1): choice = random.choice(board.get_legal_moves()) board.move(choice[0], choice[1], -1) turn = 1 winner = board.check_winner(WIN) if event.type == pygame.MOUSEBUTTONDOWN and winner == None: pos = pygame.mouse.get_pos() row, col = get_row_col_from_mouse(pos) if turn == 1 and board.move(row, col, 1): turn = -1 winner = board.check_winner(WIN) if winner == "Draw": print("It is a Draw!") elif winner != None: print(str(winner) + " wins!") board.draw(WIN) pygame.display.update() pygame.quit()
class UIWrapperTest(unittest.TestCase): def setUp(self): self.board = Board() self.printer = UIWrapper(MockCLIOutput()) def testPrintEmptyBoard(self): result = self.printer.print_board(self.board) expected_result = ''' 1 | 2 | 3 ===+===+=== 4 | 5 | 6 ===+===+=== 7 | 8 | 9 ''' self.assertEqual(result, expected_result, msg='\nRetrieved:\n{0} \nExpected:\n{1}'.format(result, expected_result)) def testPrintBoardWithSpaceTaken(self): self.board.make_move(1, "X") result = self.printer.print_board(self.board) expected_result = ''' X | 2 | 3 ===+===+=== 4 | 5 | 6 ===+===+=== 7 | 8 | 9 ''' self.assertEqual(result, expected_result, msg='\nRetrieved:\n{0} \nExpected:\n{1}'.format(result, expected_result))
def test_board_detects_all_winning_patterns(): for s1, s2, s3 in patterns.winning_patterns: xo_board = Board(tokens=["X", "O"]) xo_board[s1] = "X" xo_board[s2] = "X" xo_board[s3] = "X" assert xo_board.is_over()
def game(): current = Player.AI board = Board() winner = Player.UNKNOWN while winner == Player.UNKNOWN: if current == Player.HUMAN: board = human_turn(board) current = Player.AI else: board = ai_turn(board) current = Player.HUMAN print('-' * 20) print(board) winner = board.winner if not board.possible_moves(Player.AI) and winner == Player.UNKNOWN: winner = None if winner == Player.HUMAN: print('You won!') elif winner == Player.AI: print('Yoy lose!') else: print('It\'s a draw!')
def train(self, player='X', n=100000): self.reset() for episode in range(n): board = Board('X', 'O', ' ') state = board.state reward = 0 if player != 'X': board.make_random_move() while not board.game_over: if np.random.uniform() < self.eps: action = self.random_action(board) else: action = self.best_action(state, board) next_state, reward, terminated = \ board.step(player, action) q = self.Q[state, action] max_q = self.max_q(next_state) next_q = (1 - self.nu) * q + self.nu * (reward + self.gamma * max_q) self.Q[state, action] = next_q state = next_state
def test_board_horizontal_line(self): '''Test Board has_straight_line horizontal''' for size in self.board_size_list: for value in self.sample_values: for row in range(size): board = Board(size) self._fill_board_horizontally(board, value=value, row=row) self.assertTrue(board.has_straight_line())
def test_board_vertical_line(self): '''Test Board has_straight_line vertical''' for size in self.board_size_list: for value in self.sample_values: for col in range(size): board = Board(size) self._fill_board_vertically(board, value=value, col=col) self.assertTrue(board.has_straight_line())
def play_game(player1, player2): '''Play a game with two robots''' board = Board() for turn in range(9): player = player2 if (turn % 2) else player1 board.move(player.next_move(board)) if board.winner(): return board
def test_print_board_for_instructions(self): board = Board(self.print_function) board.print_board() expected_string = ' | | \n 1 | 2 | 3 \n | | \n' expected_string += '-----------------\n' expected_string += ' | | \n 4 | 5 | 6 \n | | \n' expected_string += '-----------------\n' expected_string += ' | | \n 7 | 8 | 9 \n | | \n' self.assertEqual(self.returned_string, expected_string)
def x_winning(self): x_winning = Board() x_winning.make_move(1, "X") x_winning.make_move(2, "O") x_winning.make_move(3, "X") x_winning.make_move(4, "O") x_winning.make_move(5, "X") x_winning.make_move(7, "O") x_winning.make_move(9, "X") return x_winning
def test_hard_computer_chooses_adjacent_corner_as_second_move(hard_computer): board = Board() board[0] = "X" board[1] = "O" move = hard_computer.move(board) assert move == 6 board = Board() board[0] = "X" board[3] = "O" move = hard_computer.move(board) assert move == 2
def test_row_winner(self): board = Board() for x in range(board._cols): board.accept_move(x, 0, board.player_o) board.accept_move(x, 1, board.player_o) board.accept_move(x, 2, board.player_o) self.assertEqual(board.check_winner(), board.player_o, f"Error: player O should have won.") board.reset()
def test_col_winner(self): board = Board() for y in range(board._rows): board.accept_move(0, y, board.player_x) board.accept_move(1, y, board.player_x) board.accept_move(2, y, board.player_x) self.assertEqual(board.check_winner(), board.player_x, f"Error: player X should have won.") board.reset()
def run_train(): game = Board(size=3) bot1 = Bot() bot2 = Bot() print("Start training..") bot1.train_mode(0.7) bot2.train_mode(0.7) for i in tqdm(range(10000)): game.run(bot1, bot2, verbose=False) if (i + 1) % 100 == 0: bot1.learning_rate *= 0.95 bot2.learning_rate *= 0.95 bot1.train_mode(0.5) bot2.train_mode(0.5) for _ in tqdm(range(10000)): game.run(bot1, bot2, verbose=False) print("End training..") print("Play dummy game..") bot1.fix_model() bot2.fix_model() bot1.serious_mode() bot2.serious_mode() game.run(bot1, bot2)
def test_print_board_for_marked_cell(self): board = Board(self.print_function) board.clean_marks() self.assertFalse(board.is_cell_marked(5)) board.mark_cell(5, 1) self.assertTrue(board.is_cell_marked(5)) board.print_board() expected_string = ' | | \n | | \n | | \n' expected_string += '-----------------\n' expected_string += ' | | \n | X | \n | | \n' expected_string += '-----------------\n' expected_string += ' | | \n | | \n | | \n' self.assertEqual(self.returned_string, expected_string) self.assertEqual(board.marked_cells, 1)
def o_winning_move(self): o_winning_move = Board() o_winning_move.make_move(1, "X") o_winning_move.make_move(5, "O") o_winning_move.make_move(2, "X") o_winning_move.make_move(3, "O") o_winning_move.make_move(8, "X") return o_winning_move
def testPlayerMove(self): result = self.player1.move(Board()) expected_result = 1 self.assertEqual(result, expected_result, msg='\nRetrieved:\n{0} \nExpected:\n{1}'.format( result, expected_result))
def playIncompleteGameAIPlaysSecond(self): ai_game = Game(Player("X", self.mock_cli_input, self.ui), AIMinimax("O", Rules()), self.ui, Validations(), Rules(), Board()) ai_game._board.make_move(1, self.game._player1._symbol) ai_game._board.make_move(3, self.game._player2._symbol) self.db.add_game_to_database(ai_game)
def testName(self): for x in range(1,10000): b=Board() randomAI=AI('x',AI.moveRandom) smartAI=AI('o',AI.moveAI) while not b.isFilled(): randomAI.turn(b) if b.isWinner('o'): print 'o is winner!\n' + str(b) break smartAI.turn(b) if b.isWinner('x'): print 'x is winner!\n' + str(b) self.fail('X won with moves ' + str(b.moves)) print 'Finished game ' + str(x) + '\n' pass
def test_diagonal_winner(self): board = Board() # Main diagonal for x in range(board._rows): board.accept_move(x, x, board.player_o) self.assertEqual(board.check_winner(), board.player_o) board.reset() # Alternate diagonal for x in range(board._rows): board.accept_move(board._cols - 1 - x, x, board.player_o) self.assertEqual(board.check_winner(), board.player_o)
def test_board_creation(self): board = Board(self.print_function) self.assertEqual(len(board.cells), 9) self.assertEqual(board.marked_cells, 0) for idx in range(0, 9): cell_number = str(idx + 1) self.assertEqual(board.cells[idx], cell_number)
def o_winning(self): o_winning = Board() o_winning.make_move(1, "X") o_winning.make_move(3, "O") o_winning.make_move(2, "X") o_winning.make_move(5, "O") o_winning.make_move(6, "X") o_winning.make_move(7, "O") return o_winning
def testPlayerSymbolDisplayedWhenPlayersTurnToMakeAMove(self): self.player1.move(Board()) result = self.mock_cli_output._last_output expected_result = "Player X, please make a move or type 'q' to save and quit game:" self.assertTrue(result in expected_result, msg='\nRetrieved:\n{0} \nExpected:\n{1}'.format( result, expected_result))
def game(): """Single game. """ board = Board() player_idx = 0 print(f"\nCurrent position:\n{board.render()}") while not board.is_full(): player_idx = (player_idx + 1) % len(SYMBOLS) symbol = SYMBOLS[player_idx] code = input_move(f"Enter move code 1 - 9 for '{symbol}': ") x, y = MOVE_CODES[code] try: board.move(symbol, x, y) print(f"\nCurrent position:\n{board.render()}") if board.is_win(): print(f"\nPlayer '{symbol}' wins!") break except BoardError as e: # Print error and let player re-enter move print(e, file=sys.stderr) player_idx = (player_idx + 1) % len(SYMBOLS) if board.is_draw(): print("\nThe game is a draw!")
def testPlayerMoveAgain(self): self.mock_cli_input.set_value(5) result = self.player1.move(Board()) expected_result = 5 self.assertEqual(result, expected_result, msg='\nRetrieved:\n{0} \nExpected:\n{1}'.format( result, expected_result))
def test_check_if_str_return_proper_repr4(self): test_board = Board(2, 2) test_board.set_element(0, 0, 'o') test_board.set_element(0, 1, 'o') test_board.set_element(1, 0, 'o') test_board.set_element(1, 1, 'o') expected_str = "o o \n\no o \n\n" self.assertEqual(test_board.__str__(), expected_str)
def test_hard_computer_wins_if_able(hard_computer): for args in patterns.winning_patterns: args = list(args) random.shuffle(args) a, b, c = args board = Board() board[a] = "X" board[b] = "X" move = hard_computer.move(board) assert move == c
def test_hard_computer_response_strategy_picks_mid_spot_turn_three(seed): hard_computer = players.HardComputer(seed=seed) hard_computer.token = "X" board = Board() board[2] = "O" board[4] = "X" board[6] = "O" move = hard_computer.move(board) assert move in patterns.middles
def ai_turn(board): weighted_moves = [] for move in board.possible_moves(Player.AI): w, t = tree_search(Board(board, move), Player.AI) weighted_moves.append((move, w / t)) if len(weighted_moves) == 0: return best_move, best_weight = weighted_moves[0] for move, weight in weighted_moves: if weight > best_weight: best_move = move best_weight = weight return Board(board=board, move=best_move)
def score(self, player='X', n=100): wins = draws = losses = 0 for i in range(n): board = Board('X', 'O', ' ') if player != 'X': board.make_random_move() while not board.game_over: state = board.state action = self.best_action(state, board) next_state, reward, terminated = board.step(player, action) if terminated: if reward == 0: draws = draws + 1 elif reward > 0: wins = wins + 1 else: losses = losses + 1 return round(wins / n, 2), round(draws / n, 2), round(losses / n, 2)
def testDisplaysBoardOnce(self): self.mock_cli_input.set_value('0') board = Board() board_string = self.setup_game._ui.print_board(board) self.setup_game.run() result = self.mock_cli_output._last_output self.assertTrue( board_string in result, msg='\nRetrieved:\n{0} \nExpected to contain:\n{1}'.format( result, board_string))
def setUp(self): self.mock_cli_input = MockCLIInput() self.output = MockCLIOutput() self.player1 = Player("X", MockCLIInput(), self.output) self.player2 = Player("O", MockCLIInput(), self.output) self.rules = Rules() self.board = Board() self.game = Game(Player("X", self.mock_cli_input, self.output), Player("O", MockCLIInput(), self.output), self.output, Validations(), self.rules, self.board) self.engine = create_engine(TEST_DB_ADDRESS) self.db = Database(self.engine)
def testWin(self): b=Board() [b.mark(l,m) for l,m in ((2,'x'),(4,'x'))] self.assertFalse(b.isWinner('x')) b.mark(6, 'x') print b self.assertTrue(b.isWinner('x'))
def score_moves(self, board): '''Score next moves for a board''' scores = {} depth = 9 - len(board.next_moves()) for pos in board.next_moves(): next_board = Board(board.state()) next_board.move(pos) if next_board.winner() == board.X_WINS: scores[pos] = 10 - depth elif next_board.winner() == board.O_WINS: scores[pos] = -10 + depth elif next_board.winner() == board.TIE: scores[pos] = 0 else: score, _ = self.best_moves(next_board) scores[pos] = score return scores
def play(): b=Board() ai=AI('o',AI.moveAI) while not b.isFilled(): print str(b) + '\nPlease input a number representing the space '\ 'you want to mark in the range 0-8, then press enter: ' msg = sys.stdin.readline() try: location=int(msg) if b.isMarked(location): print('Please choose a space that has not already been filled in') continue b.mark(location, 'x') if b.isWinner('x'): print('X wins!') return if not b.isFilled(): ai.turn(b) if b.isWinner('o'): print('O wins!') return except: print('Please input a valid number between 0-8') print('Stalemate, please play again!')
def game(): """Endpoint for the assignment.""" # KeyError type from the args dict results in HTTP 400. # For details, see # http://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.MultiDict try: # TODO: overly broad try / except board = Board(wire_format=request.args['board']) if Board.O not in board.next_players(): abort(400) # not O's turn, bad request # Simply attempt the first move returned by available moves. board.make_move(Board.O, board.available_moves(Board.O)[0]) resp = make_response(board.wire_format()) resp.mimetype = 'text/plain' return resp except ValueError: abort(400) # inavlid board, bad request
def test_check_free_on_not_free_cell(self): board = Board() board.o(0, 2) self.assertFalse(board.is_free(0, 2))
def test_check_free_on_free_cell(self): board = Board() board.o(0, 2) self.assertTrue(board.is_free(1, 2))
def test_first_line_x_winner(self): board = Board() board.x(0, 0) board.x(0, 1) board.x(0, 2) self.assertEqual(CROSS, board.winner)
def test_full_completed(self): board = Board() for i in range(3): for j in range(3): board.o(i, j) self.assertTrue(board.completed)
def test_clone_detaches_future_writes(self): board = Board() board2 = board.clone() board.o(0, 2) self.assertTrue(board2.is_free(0, 2))
def testDetectLine(self): b=Board() [b.mark(l,m) for l,m in ((0,'x'),(4,'o'),(8,'x'))] smartAI=AI('o',AI.moveAI) self.assertEqual(smartAI.moveAI(b), 1)
def test_first_column_mixed_no_winner(self): board = Board() board.x(0, 0) board.x(1, 0) board.o(2, 0) self.assertFalse(board.winner)
def test_first_column_completed_o_winner(self): board = Board() board.o(0, 0) board.o(1, 0) board.o(2, 0) self.assertEqual(CIRCLE, board.winner)
def test_first_line_mixed_no_winner(self): board = Board() board.x(0, 0) board.x(0, 1) board.o(0, 2) self.assertFalse(board.winner)
def testDetectWin(self): b=Board() [b.mark(l,m) for l,m in ((2,'x'),(4,'x'))] smartAI=AI('x',AI.moveAI) self.assertEqual(smartAI.detectWin(b, 'x'), 6)
def test_cannot_override_same_value(self): board = Board() board.o(0, 2) self.assertRaises(AlreadySet, board.o, 0, 2)
def test_diagonal2_completed_o_winner(self): board = Board() board.o(0, 2) board.o(1, 1) board.o(2, 0) self.assertEqual(CIRCLE, board.winner)
def test_clone_copies_already_set_cells(self): board = Board() board.o(0, 2) self.assertFalse(board.clone().is_free(0, 2))
def test_diagonal2_not_completed_no_winner(self): board = Board() board.o(0, 2) board.o(1, 1) board.x(2, 0) self.assertFalse(board.winner)
def test_column_not_completed(self): board = Board() board.o(0, 2) board.o(1, 1) board.x(2, 0) self.assertFalse(board.completed)
def test_first_line_not_completed_no_winner(self): board = Board() board.x(0, 0) board.x(0, 1) self.assertFalse(board.winner)
def testEmptyExcept(self): b=Board() [b.mark(l,m) for l,m in ((2,'x'),(4,'x'))] self.assertTrue(b.isEmptyExcept((2,4)))