def run_games(config):
    game = Othello()
    model = ""
    x = config.iterations
    while(x != 0):
        x -= 1
        models = sorted(glob.glob(config.data.model_location+"*.h5"))
        if model == "":
            model = models[-1]
            print("Loading new model: %s" % util.getPlayerName(model))
            ai = AIPlayer(config.buffer_size, config.game.simulation_num_per_move, model=model)
        elif models[-1] != model:
            model = models[-1]
            print("Loading new model: %s" % util.getPlayerName(model))
            ai.load(model)
		
        start=time()
        for j in range(config.nb_game_in_file):
            util.print_progress_bar(j, config.nb_game_in_file, start=start)
            side = -1
            turn = 1
            while not game.game_over():
                ai.tau = config.game.tau_1
                if config.game.tau_swap < turn:
                    ai.tau = config.game.tau_2
                t = ai.pick_move(game, side)
                game.play_move(t[0], t[1], side)
                side *= -1
                turn += 1
            ai.update_buffer(game.get_winner())
            game.reset_board()
        #print("Average Game Time: ", (time()-start)/(config.nb_game_in_file))
        util.print_progress_bar(config.nb_game_in_file, config.nb_game_in_file, start=start)
        save_games(config, ai.buffer)
    t.join()
示例#2
0
    def test_is_legal_move(self):
        game = Othello()
        game.initialize_board()

        # Test illegal moves before making any legal moves
        illegal_moves = [(), (3, 3), (3, 4), (4, 3), (4, 4), (-1, 0), 
                         (8, 2), (-5, 9), (0, 0), (3, 1), (2, 2), (5, 3)]

        for move in illegal_moves:
            self.assertFalse(game.is_legal_move(move))

        # Test legal moves for player 1 (black tile)
        legal_moves = [(2, 3), (3, 2), (5, 4), (4, 5)]
        for move in legal_moves:
            self.assertTrue(game.is_legal_move(move)) 
        
        # Let player 1 make a legal move
        game.move = (2, 3)
        game.make_move()
        
        # Test legal/illegal moves for player 2 (white tile)
        game.current_player = 1
        legal_moves = [(2, 4), (2, 2), (4, 2)]
        for move in legal_moves:
            self.assertTrue(game.is_legal_move(move))
        illegal_moves = [(3, 2), (5, 3), (5, 4), (4, 5), (3, 5), (6, 1)]
        for move in illegal_moves:
            self.assertFalse(game.is_legal_move(move))
示例#3
0
def test__init__():
    othello = Othello(400, 4, "Name", "black")

    board = Board(400, 4)
    gc = GameController(400, 400, "Name", "black")
    tiles = [Tile(100) for _ in range(16)]

    tile = tiles.pop()
    tile.set_white()
    board.grids[1][1] = tile

    tile = tiles.pop()
    tile.set_black()
    board.grids[1][2] = tile

    tile = tiles.pop()
    tile.set_black()
    board.grids[2][1] = tile

    tile = tiles.pop()
    tile.set_white()
    board.grids[2][2] = tile

    assert othello.board == board
    assert othello.gc == gc
    assert othello.tiles == tiles
    assert othello.valid_grids == set({})
    assert othello.is_black
    assert not othello.is_control
示例#4
0
def test_flip():
    othello = Othello(400, 4, "Name", "black")

    othello.flip(0, 0, "dr", 1)
    assert othello.board.grids[1][1].is_black
    othello.flip(0, 0, "dr", 1)

    othello.flip(0, 3, "dl", 1)
    assert not othello.board.grids[1][2].is_black
    othello.flip(0, 3, "dl", 1)

    othello.flip(3, 0, "ur", 1)
    assert not othello.board.grids[2][1].is_black
    othello.flip(3, 0, "ur", 1)

    othello.flip(3, 3, "ul", 1)
    assert othello.board.grids[2][2].is_black
    othello.flip(3, 3, "ul", 1)

    othello.flip(1, 0, "r", 1)
    assert othello.board.grids[1][1].is_black
    othello.flip(1, 0, "r", 1)

    othello.flip(1, 3, "l", 1)
    assert not othello.board.grids[1][2].is_black
    othello.flip(1, 3, "l", 1)

    othello.flip(0, 1, "d", 1)
    assert othello.board.grids[1][1].is_black
    othello.flip(0, 1, "d", 1)

    othello.flip(3, 1, "u", 1)
    assert not othello.board.grids[2][1].is_black
    othello.flip(3, 1, "u", 1)
示例#5
0
    def test_get_valid_flips(self):
        # Set up a testable game
        game = Othello(8)
        game.active_color = 'white'
        game.board.record_tile(Point(2, 2), 'white')
        game.board.record_tile(Point(5, 4), 'black')
        game.board.record_tile(Point(6, 5), 'black')
        game.board.record_tile(Point(7, 5), 'white')
        game.board.record_tile(Point(6, 6), 'white')
        game.board.record_tile(Point(5, 6), 'black')
        game.board.record_tile(Point(5, 7), 'black')
        game.board.record_tile(Point(4, 6), 'black')

        # Test good input (a move that results in a variety of flips or lack
        # thereof in each direction)
        test_move = game.get_valid_flips(Point(5, 5))
        expected_outcome = [Point(6, 5), Point(4, 4), Point(3, 3)]
        self.assertEqual(test_move, expected_outcome)

        # Test bad inputs:
        # 1. Move outside the board
        # 2. Move that targets an occupied square
        # 3. Argument is None instead of a point
        outside_board_test = game.get_valid_flips(Point(100, 100))
        occupied_board_test = game.get_valid_flips(Point(2, 2))
        none_point_test = game.get_valid_flips(None)
        self.assertEqual(outside_board_test, [])
        self.assertEqual(occupied_board_test, [])
        self.assertEqual(none_point_test, [])
示例#6
0
def test_update_info():
    othello = Othello(400, 4, "Name", "black")
    othello.gc.is_black = False
    othello.is_control = True
    othello.update_info()
    assert othello.gc.is_black
    assert not othello.is_control
示例#7
0
def minimax(board,
            depth,
            player,
            alpha=-np.inf,
            beta=np.inf,
            eval_func='pos_score',
            king_version=False):
    if depth == 0:
        if eval_func == 'pos_score':
            return pos_score_sum(board)
        elif eval_func == 'mobi':
            return mobility(board)
        elif eval_func == 'pos_mobi':
            return pos_plus_mobi(board)
        elif eval_func == 'king_pos_score':  # this is for King Othello
            return king_pos_score_sum(board)
    if not king_version:
        game = Othello()
    else:
        game = KingOthello()
    game.board = board
    game.current_player = player
    possible_moves = game.find_all_valid_moves()

    if possible_moves:
        if player == BLACK:  # maximizing player
            max_eval = -np.inf
            for move in possible_moves:
                game_copy = deepcopy(game)
                game_copy.take_move(move[0], move[1])
                eval = minimax(game_copy.board, depth - 1, opposite(player),
                               alpha, beta)
                max_eval = max(max_eval, eval)
                alpha = max(alpha, eval)
                if beta <= alpha:
                    break
            return max_eval

        else:  # WHITE, minimizing player
            min_eval = np.inf
            for move in possible_moves:
                game_copy = deepcopy(game)
                game_copy.take_move(move[0], move[1])
                eval = minimax(game_copy.board, depth - 1, opposite(player),
                               alpha, beta)
                min_eval = min(min_eval, eval)
                beta = min(beta, eval)
                if beta <= alpha:
                    break
            return min_eval

    else:  # no possible move for current player
        game.switch_turn()
        possible_moves = game.find_all_valid_moves(
        )  # check whether opponent has moves
        if possible_moves:
            return minimax(game.board, depth - 1, opposite(player), alpha,
                           beta)  # hand over to opponent, nothing changed
        else:  # the opponent has no moves either, game over
            return pos_score_sum(game.board)
示例#8
0
    def test_has_tile_to_flip(self):
        game = Othello()
        game.initialize_board()

        # Test when the board is in the initial state
        # Test two moves for player 1 (black tile) in all flipping directions
        self.assertTrue(game.has_tile_to_flip((2, 3), (+1, 0)))
        no_flip_dirs = [(-1, -1), (-1, +1), (0, -1), (0, +1),
                        (+1, -1), (-1, 0), (+1, +1)]
        for direction in no_flip_dirs:
            self.assertFalse(game.has_tile_to_flip((2, 3), direction))
        
        self.assertTrue(game.has_tile_to_flip((3, 2), (0, +1)))
        no_flip_dirs = [(-1, -1), (-1, +1), (0, -1), (+1, 0), 
                        (+1, -1), (-1, 0), (+1, +1)]
        for direction in no_flip_dirs:
            self.assertFalse(game.has_tile_to_flip((3, 2), direction))
        
        # Let player 1 make a legal move
        game.move = (2, 3)
        game.make_move()
        
        # Test two moves for player 2 (white tile)
        game.current_player = 1

        self.assertTrue(game.has_tile_to_flip((2, 4), (+1, 0)))
        no_flip_dirs = [(-1, -1), (-1, +1), (0, -1), (0, +1), 
                        (+1, -1), (-1, 0), (+1, +1)]
        for direction in no_flip_dirs:
            self.assertFalse(game.has_tile_to_flip((2, 4), direction))
        
        self.assertTrue(game.has_tile_to_flip((2, 2), (+1, +1)))
        no_flip_dirs =  [(-1, -1), (-1, 0), (-1, +1), (0, -1),
                         (0, +1), (+1, -1), (+1, 0)]
        for direction in no_flip_dirs:
            self.assertFalse(game.has_tile_to_flip((2, 2), direction))

        # Test when player 1 has tiles to flip but player 2 does not
        game.board = [[2, 0, 2, 2, 2, 2, 2, 2], 
                      [2, 2, 2, 2, 1, 1, 1, 1],
                      [2, 1, 2, 1, 1, 1, 1, 1], 
                      [1, 1, 1, 1, 1, 1, 1, 1],
                      [2, 2, 1, 1, 1, 2, 2, 1], 
                      [0, 2, 1, 1, 2, 2, 2, 1], 
                      [1, 2, 1, 2, 2, 2, 2, 1], 
                      [1, 2, 2, 2, 2, 2, 0, 1]]

        game.current_player = 0
        flip_dirs = {(0, 1) : [(+1, 0), (+1, +1)], 
                     (5, 0) : [(-1, 0), (0, +1), (-1, +1)],
                     (7, 6) : [(-1, 0), (0, -1), (-1, -1)]}
        for move in flip_dirs:
            for direction in flip_dirs[move]:
                self.assertTrue(game.has_tile_to_flip(move, direction))

        game.current_player = 1
        for direction in MOVE_DIRS:
            self.assertFalse(game.has_tile_to_flip((0, 1), direction))
            self.assertFalse(game.has_tile_to_flip((5, 0), direction))
            self.assertFalse(game.has_tile_to_flip((7, 6), direction))
示例#9
0
def mobility(board):
    # defined number of possible moves : black - white
    g1 = Othello()
    g1.board = board
    g1.current_player = BLACK
    score_black = len(g1.find_all_valid_moves())
    g1.current_player = WHITE
    score_white = len(g1.find_all_valid_moves())
    return score_black - score_white
示例#10
0
    def test_report_winner(self, mocked_print):
        game = Othello(4)
        game.report_winner()
        game = Othello(4)
        game.board.black_tiles = 3
        game.report_winner()
        game = Othello(4)
        game.board.white_tiles = 4
        game.report_winner()

        # Check that report_winner prints correct text to the terminal
        self.assertEqual(mocked_print.mock_calls, \
          [call("Game over! Score is 2 for black and 2 for white."),
           call("It's a tie!"),
           call("Game over! Score is 3 for black and 2 for white."),
           call("Black wins!"),
           call("Game over! Score is 2 for black and 4 for white."),
           call("White wins!")])
示例#11
0
def test_update_legal_move():
    othello = Othello(400, 4, "Name", "black")
    othello.update_legal_move()

    # worked in "d"
    assert isinstance(othello.board.grids[0][1], Record)
    assert not othello.board.grids[0][1].record["u"]
    assert othello.board.grids[0][1].record["d"] == 1
    assert not othello.board.grids[0][1].record["l"]
    assert not othello.board.grids[0][1].record["r"]
    assert not othello.board.grids[0][1].record["ul"]
    assert not othello.board.grids[0][1].record["ur"]
    assert not othello.board.grids[0][1].record["dl"]
    assert not othello.board.grids[0][1].record["dr"]

    # worked in "r"
    assert isinstance(othello.board.grids[1][0], Record)
    assert othello.board.grids[1][0].record["r"] == 1

    # worked in "u"
    assert isinstance(othello.board.grids[3][2], Record)
    assert othello.board.grids[3][2].record["u"] == 1

    # worked in "l"
    assert isinstance(othello.board.grids[2][3], Record)
    assert othello.board.grids[2][3].record["l"] == 1

    assert not isinstance(othello.board.grids[0][0], Record)

    # worked in "ul"
    othello.board.grids[1][1].flip()
    othello.update_legal_move()
    assert isinstance(othello.board.grids[3][3], Record)
    assert othello.board.grids[3][3].record["ul"] == 1
    othello.board.grids[1][1].flip()

    # worked in "ur"
    othello.board.grids[2][1].flip()
    othello.update_legal_move()
    assert isinstance(othello.board.grids[3][0], Record)
    assert othello.board.grids[3][0].record["ur"] == 1
    othello.board.grids[2][1].flip()

    # worked in "dr"
    othello.board.grids[2][2].flip()
    othello.update_legal_move()
    assert isinstance(othello.board.grids[0][0], Record)
    assert othello.board.grids[0][0].record["dr"] == 1
    othello.board.grids[2][2].flip()

    # worked in "dl"
    othello.board.grids[1][2].flip()
    othello.update_legal_move()
    assert isinstance(othello.board.grids[0][3], Record)
    assert othello.board.grids[0][3].record["dl"] == 1
    othello.board.grids[1][2].flip()
示例#12
0
def main():
    random_state = random.Random()

    player_w = OthelloAgent("W", RandomAction(random_state))
    player_b = OthelloAgent("B", RandomAction(random_state))

    environment = Othello(player_w, player_b)
    episode = OthelloVerboseEpisode()

    run_episode(environment, episode)
 def __call__(self, number_of_games):
     for i in range(number_of_games):
         #print("Training game:",i)
         game = Othello(self.window, self.players, self.affichage)
         game()
         self.games.append(game)
         for id_player, player in enumerate(self.players):
             if isinstance(player, NeuralNetwork):
                 self.teach(id_player, game)
                 self.players[id_player].train()
示例#14
0
def test_skip_or_finish():
    # test when game is not finished
    othello = Othello(400, 4, "Name", "black")
    othello.update_legal_move()
    othello.skip_or_finish()
    assert not othello.gc.is_finished

    # test when skipping this turn
    othello.board.take_off(1, 1)
    othello.board.take_off(1, 2)
    othello.board.take_off(2, 1)
    othello.board.take_off(2, 2)
    for i in range(4):
        othello.is_black = False
        othello.put_tile_on(0, i)
        if i > 0:
            othello.is_black = True
            othello.put_tile_on(1, i)
    othello.update_legal_move()
    othello.skip_or_finish()
    assert othello.gc.is_skip
    assert not othello.is_black

    othello.control(2, 0)
    othello.update_legal_move()
    othello.skip_or_finish()
    assert not othello.gc.is_skip

    # test whether no empty grids will finish the game
    othello = Othello(400, 2, "Name", "black")
    othello.skip_or_finish()
    assert othello.gc.is_finished

    # test whether no legal moves will finish the game
    othello.board.take_off(0, 0)
    othello.skip_or_finish()
    assert othello.gc.is_finished

    # test whether all tiles are in one color will finish the game
    othello.board.take_off(1, 1)
    othello.skip_or_finish()
    assert othello.gc.is_finished
示例#15
0
def main():
    episodes = 10

    random_state = random.Random()

    player_w = OthelloAgent("W", MonteCarloTreeSearch())
    player_b = OthelloAgent("B", RandomAction(random_state))

    environment = Othello(player_w, player_b)

    run_timed_episodes(environment, episodes)
示例#16
0
def test_put_tile_on():
    othello = Othello(400, 4, "Name", "black")
    tile = Tile(100)

    othello.put_tile_on(0, 0)
    assert othello.board.grids[0][0] == tile

    othello.is_black = False
    othello.put_tile_on(0, 0)
    tile.flip()
    assert othello.board.grids[0][0] == tile
示例#17
0
def main():
    episodes = 10

    random_state = random.Random()

    player_w = OthelloAgent("W", AlphaBetaPruning(2))
    player_b = OthelloAgent("B", RandomAction(random_state))

    environment = Othello(player_w, player_b)

    run_timed_episodes(environment, episodes)
示例#18
0
    def test_get_coord(self):
        # Test for board of size 4x4
        game = Othello(4)

        # Test valid points (on board but not on line)
        valid_points = [(40.1, 39.5), (75.0, -77.2), (-22.78, -11.16), 
                        (-61.99, 5.0), (-71.23, 1.0)]
        expected_results = [(1, 2), (3, 3), (2, 1), (1, 0), (1, 0)]
        for i in range(len(valid_points)):    
            game.get_coord(valid_points[i][0], valid_points[i][1])
            self.assertEqual(game.move, expected_results[i])

        # Test invalid points (on line or not on board)
        invalid_points = [(0.0, 0.0), (-100.0, 100.0), (150.23, 77.0),
                          (5.0, -100.10), (-68.98, 177.54), (-71.23, 0.0)]           
        for point in invalid_points:
            game.get_coord(point[0], point[1])  
            self.assertEqual(game.move, ())

        # Test for board of size 8x8
        game = Othello()

        # Test valid points (on board but not on line)
        valid_points = [(40.1, 39.5), (175.0, -77.2), 
                        (-22.78, -11.16), (-61.99, 105.1),
                        (-159.23, 175.02), (-111.0, 99.9), (82.56, 130.78)]
        expected_results = [(3, 4), (5, 7), (4, 3), (1, 2),
                            (0, 0), (2, 1), (1, 5)]
        for i in range(len(valid_points)):    
            game.get_coord(valid_points[i][0], valid_points[i][1])
            self.assertEqual(game.move, expected_results[i])

        # Test invalid points (on line or not on board)
        invalid_points = [(0.0, 0.0), (-100.0, 100.0), (100.0, 100.0), 
                          (250.23, 77.0), (5.0, -200.10), (-68.98, 377.54), 
                          (-1.5, 200.0), (200.0, 200.0), (-200.0, -200.0), 
                          (200.0, -100.0), (-71.23, 0.0)]    
        for point in invalid_points:
            game.get_coord(point[0], point[1])  
            self.assertEqual(game.move, ())
示例#19
0
def test_game_AI():
    othello = Othello(400, 4, "Name", "white")
    othello.update_info()
    othello.game_AI()
    assert any([
        isinstance(othello.board.grids[0][1], Tile),
        isinstance(othello.board.grids[1][0], Tile),
        isinstance(othello.board.grids[3][2], Tile),
        isinstance(othello.board.grids[2][3], Tile)
    ])
    for i, j in [(0, 1), (1, 0), (3, 2), (2, 3)]:
        if isinstance(othello.board.grids[i][j], Tile):
            assert othello.board.grids[i][j].is_black
示例#20
0
    def test_init(self):
        # Test for board of size 0
        game = Othello(0)
        self.assertEqual(game.n, 0)
        self.assertEqual(game.board, [])

        # Test for board of size 2x2
        game = Othello(2)
        self.assertEqual(game.n, 2)
        expected_board = [[0, 0], [0, 0]]
        self.assertEqual(game.board, expected_board)

        # Test for board of size 4x4
        game = Othello(4)
        self.assertEqual(game.n, 4)
        expected_board = [[0, 0, 0, 0], [0, 0, 0, 0],
                          [0, 0, 0, 0], [0, 0, 0, 0]]
        self.assertEqual(game.board, expected_board)
        self.assertEqual(game.square_size, 50)
        self.assertEqual(game.board_color, 'forest green')
        self.assertEqual(game.line_color, 'black')
        self.assertEqual(game.tile_size, 20)
        self.assertEqual(game.tile_colors, ['black', 'white'])
        self.assertEqual(game.move, ())
        self.assertEqual(game.current_player, 0)
        self.assertEqual(game.num_tiles, [2, 2])

        # Test for board of size 8x8
        game = Othello()
        self.assertEqual(game.n, 8)
        self.assertEqual(game.board, EMPTY_BOARD)
        self.assertEqual(game.square_size, 50)
        self.assertEqual(game.board_color, 'forest green')
        self.assertEqual(game.line_color, 'black')
        self.assertEqual(game.tile_size, 20)
        self.assertEqual(game.tile_colors, ['black', 'white'])
        self.assertEqual(game.move, ())
        self.assertEqual(game.current_player, 0)
        self.assertEqual(game.num_tiles, [2, 2])
示例#21
0
    def test_initialize_board(self):
        # Test for board of size 0
        game = Othello(0)
        game.initialize_board()
        self.assertEqual(game.board, [])

        # Test for board of size 2x2
        game = Othello(2)
        game.initialize_board()
        expected_board = [[2, 1], [1, 2]]
        self.assertEqual(game.board, expected_board)

        # Test for board of size 4x4
        game = Othello(4)
        game.initialize_board()
        expected_board = [[0, 0, 0, 0], [0, 2, 1, 0], 
                          [0, 1, 2, 0], [0, 0, 0, 0]]
        self.assertEqual(game.board, expected_board)

        # Test for board of size 8x8
        game = Othello()
        game.initialize_board()
        self.assertEqual(game.board, INITIAL_BOARD)
示例#22
0
    def test_eq(self):
        game1 = Othello(4)
        game2 = Othello(4)
        game3 = Othello(8)

        self.assertTrue(game1 == game2)
        self.assertFalse(game1 == game3)
        self.assertFalse(game2 == game3)

        game1.board[0][0] = 1
        self.assertFalse(game1 == game2)

        game2.board[0][0] = 1
        self.assertTrue(game1 == game2)

        game1.current_player = 1
        self.assertFalse(game1 == game2)

        game2.current_player = 1
        self.assertTrue(game1 == game2)

        game2.current_player = 2
        self.assertFalse(game1 == game2)
示例#23
0
    def test_is_valid_coord(self):
        # Test for board of size 0 (no valid coordinate)
        game = Othello(0)

        coords = [(0, 0), (1, 2), (3, 8), (0, 1), (-4, 3), (8, -7), (-1, -5)]
        for coord in coords:
            self.assertFalse(game.is_valid_coord(coord[0], coord[1]))

        # Test for board of size 4x4
        game = Othello(4)

        invalid_coords = [(4, 0), (1, 4), (5, 8), (3, 9), (0, -1),
                          (-2, 3), (8, -7), (-1, -5), (-2, -2)]
        for coord in invalid_coords:
            self.assertFalse(game.is_valid_coord(coord[0], coord[1]))
        
        valid_coords = []
        for i in range(4):
            for j in range(4):
                valid_coords.append((i, j))
        for coord in valid_coords:
            self.assertTrue(game.is_valid_coord(coord[0], coord[1]))

        # Test for board of size 8x8
        game = Othello()

        invalid_coords = [(8, 0), (1, 8), (9, 10), (3, 9), (0, -1),
                          (-2, 3), (8, -7), (-1, -5), (-2, -2)]
        for coord in invalid_coords:
            self.assertFalse(game.is_valid_coord(coord[0], coord[1]))
        
        valid_coords = []
        for i in range(8):
            for j in range(8):
                valid_coords.append((i, j))
        for coord in valid_coords:
            self.assertTrue(game.is_valid_coord(coord[0], coord[1]))
示例#24
0
    def test_convert_coord(self):
        # Test for board of size 4x4
        game = Othello(4)

        valid_coords = [(0.0, 0.0), (40.1, 39.5), (75.0, -77.2), 
                        (-22.78, -11.16), (-61.99, 5.0), (-71.23, 0.0)]
        expected_results = [(1, 2), (1, 2), (3, 3), (2, 1), (1, 0), (1, 0)]
        for i in range(len(valid_coords)):
            self.assertEqual(game.convert_coord(valid_coords[i][0], 
                             valid_coords[i][1]), expected_results[i])
        
        invalid_coords = [(-100.0, 100.0), (100.0, 100.0), (150.23, 77.0),
                          (5.0, -100.10), (-68.98, 177.54), (-1.5, 200.2)]
        for i in range(len(invalid_coords)):
            self.assertEqual(game.convert_coord(invalid_coords[i][0], 
                             invalid_coords[i][1]), ())
        
        # Test for board of size 8x8
        game = Othello()

        valid_coords = [(0.0, 0.0), (40.1, 39.5), (175.0, -77.2), 
                        (-22.78, -11.16), (-61.99, 105.1), (-71.23, 0.0),
                        (-159.23, 175.02), (-111.0, 99.9), (82.56, 130.78),
                        (-100.0, 100.0), (100.0, 100.0)]
        expected_results = [(3, 4), (3, 4), (5, 7), (4, 3), (1, 2), (3, 2),
                            (0, 0), (2, 1), (1, 5), (1, 2), (1, 6)]
        for i in range(len(valid_coords)):
            self.assertEqual(game.convert_coord(valid_coords[i][0], 
                             valid_coords[i][1]), expected_results[i])
        
        invalid_coords = [(250.23, 77.0), (5.0, -200.10), (-68.98, 377.54), 
                          (-1.5, 200.0), (200.0, 200.0), (-200.0, -200.0), 
                          (200.0, -100.0)]
        for i in range(len(invalid_coords)):
            self.assertEqual(game.convert_coord(invalid_coords[i][0], 
                             invalid_coords[i][1]), ())
示例#25
0
    def test_make_move(self):
        game = Othello()
        game.initialize_board()

        # Test making illegal moves before making any legal moves
        illegal_moves = [(), (3, 3), (3, 4), (4, 3), (4, 4), (-1, 0), 
                         (8, 2), (-5, 9), (0, 0), (3, 1), (2, 2), (5, 3)]
        for move in illegal_moves:
            game.move = move
            game.make_move()
            self.assertEqual(game.board, INITIAL_BOARD)
            self.assertEqual(game.num_tiles, [2, 2])

        # Test making legal moves for different players
        game.move = (2, 3)
        game.make_move()
        self.assertEqual(game.board[2][3], 1)
        self.assertEqual(game.board[3][3], 1)
        self.assertEqual(game.board[4][3], 1)

        game.current_player = 1
        game.move = (2, 2)
        game.make_move()
        self.assertEqual(game.board[2][2], 2)
        self.assertEqual(game.board[3][3], 2)
        self.assertEqual(game.board[4][4], 2)

        game.current_player = 0
        game.move = (4, 5)
        game.make_move()
        self.assertEqual(game.board[4][3], 1)
        self.assertEqual(game.board[4][4], 1)
        self.assertEqual(game.board[4][5], 1)

        # Test making illegal moves after making some legal moves
        game.current_player = 1
        game.move = (5, 4)
        game.make_move()
        self.assertEqual(game.board[5][4], 0)
        game.move = (5, 2)
        game.make_move()
        self.assertEqual(game.board[5][2], 0)
        game.move = (6, 0)
        game.make_move()
        self.assertEqual(game.board[6][0], 0)
示例#26
0
    def test_get_legal_moves(self):
        game = Othello()
        game.initialize_board()

        # Test legal moves for player 1 (black tile)
        legal_moves = [(2, 3), (3, 2), (4, 5), (5, 4)]
        self.assertEqual(game.get_legal_moves(), legal_moves)

        # Let player 1 make a legal move
        game.move = (2, 3)
        game.make_move()
        
        # Test legal moves for player 2 (white tile)
        game.current_player = 1
        legal_moves = [(2, 2), (2, 4), (4, 2)]
        self.assertEqual(game.get_legal_moves(), legal_moves)

        # Test when player 1 has legal moves but player 2 has no legal moves
        game.current_player = 0
        game.board = [[2, 0, 2, 2, 2, 2, 2, 2], 
                      [2, 2, 2, 2, 1, 1, 1, 1],
                      [2, 1, 2, 1, 1, 1, 1, 1], 
                      [1, 1, 1, 1, 1, 1, 1, 1],
                      [2, 2, 1, 1, 1, 2, 2, 1], 
                      [0, 2, 1, 1, 2, 2, 2, 1], 
                      [1, 2, 1, 2, 2, 2, 2, 1], 
                      [1, 2, 2, 2, 2, 2, 0, 1]]
        legal_moves = [(0, 1), (5, 0), (7, 6)]
        self.assertEqual(game.get_legal_moves(), legal_moves)

        game.current_player = 1
        self.assertEqual(game.get_legal_moves(), [])

        # Test when the board is full (both players have no legal moves)
        game.board = [[2, 1, 2, 2, 2, 2, 2, 2], [2, 1, 1, 2, 1, 1, 1, 1],
                      [2, 1, 2, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1],
                      [1, 1, 1, 1, 1, 2, 1, 1], [1, 1, 1, 1, 1, 2, 1, 1], 
                      [1, 2, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]]
        self.assertEqual(game.get_legal_moves(), [])
        game.current_player = 0
        self.assertEqual(game.get_legal_moves(), [])
示例#27
0
def test_control():
    othello = Othello(400, 4, "Name", "black")

    # test if I can make an illegal move
    othello.update_info()
    othello.control(0, 0)
    assert not othello.board.grids[0][0]
    assert othello.is_black
    assert not othello.is_control

    # test if I can make a legal move
    othello.update_info()
    othello.control(0, 1)
    assert not othello.is_black
    assert othello.is_control

    assert isinstance(othello.board.grids[0][1], Tile)
    assert othello.board.grids[0][1].is_black

    assert isinstance(othello.board.grids[1][1], Tile)
    assert othello.board.grids[1][1].is_black
示例#28
0
    def test_has_legal_move(self):
        game = Othello()
        game.initialize_board()

        # Test when the board is in the initial state
        self.assertTrue(game.has_legal_move())

        # Test when player 1 (black tile) has legal moves
        game.board = [[2, 0, 0, 1, 0, 0, 0, 2], [2, 1, 1, 1, 0, 0, 2, 0],
                      [2, 1, 2, 1, 2, 2, 2, 2], [1, 1, 1, 1, 1, 2, 1, 0],
                      [2, 2, 2, 1, 2, 1, 2, 0], [0, 2, 1, 1, 1, 2, 1, 2], 
                      [1, 1, 2, 0, 1, 2, 1, 1], [1, 0, 0, 2, 1, 0, 0, 1]]
        self.assertTrue(game.has_legal_move())

        # Test when player 2 (white tile) has legal moves
        game.current_player = 1
        game.board = [[2, 0, 0, 1, 1, 1, 1, 2], [2, 1, 1, 2, 0, 0, 1, 1],
                      [2, 1, 2, 1, 2, 2, 1, 2], [1, 1, 1, 1, 1, 1, 2, 0],
                      [2, 2, 1, 1, 1, 2, 2, 0], [0, 2, 1, 1, 2, 2, 1, 2], 
                      [1, 1, 1, 2, 2, 2, 2, 1], [1, 0, 1, 1, 1, 2, 0, 1]]
        self.assertTrue(game.has_legal_move())

        # Test when player 2 (white tile) has no legal moves
        game.board = [[2, 0, 2, 2, 2, 2, 2, 2], [2, 2, 2, 2, 1, 1, 1, 1],
                      [2, 1, 2, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1],
                      [2, 2, 1, 1, 1, 2, 2, 1], [0, 2, 1, 1, 2, 2, 2, 1], 
                      [1, 2, 1, 2, 2, 2, 2, 1], [1, 2, 2, 2, 2, 2, 0, 1]]
        self.assertFalse(game.has_legal_move())

        # Test when the board is full (both players have no legal moves)
        game.board = [[2, 1, 2, 2, 2, 2, 2, 2], [2, 1, 1, 2, 1, 1, 1, 1],
                      [2, 1, 2, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1],
                      [1, 1, 1, 1, 1, 2, 1, 1], [1, 1, 1, 1, 1, 2, 1, 1], 
                      [1, 2, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]]
        self.assertFalse(game.has_legal_move())
        game.current_player = 0
        self.assertFalse(game.has_legal_move())
示例#29
0
        if not os.path.isfile(f"result-{i}.txt"):
            outfile_name = f"result-{i}.txt"
        print(i)
        i = i + 1

    with open(outfile_name, 'w') as outfile:
        outfile.write(outfile_info_string + "\n")

    for game_counter in range(games_nr):
        print(f"game: {game_counter}")
        # Store the players in a dict with the internal player codes as key to allow easy access and maintaining the correct order
        players = {PLAYER_ONE: player_one, PLAYER_TWO: player_two}
        times = {PLAYER_ONE: 0, PLAYER_TWO: 0}

        # Create a new game state
        game = Othello()
        # Initialize it to start a new game
        game.init_game()

        # store the start time
        start = time.time()
        # While the game is still running continue to make turns
        while not game.game_is_over():
            # Get the symbol for the current player
            current_player = game.get_current_player()
            # Get the Player object assigned to that player
            player_object = players[current_player]
            # Ask the Player to calculate it's move based on the current state
            calculation_start = time.time()
            move = player_object.get_move(game)
            calculation_time = time.time() - calculation_start
示例#30
0
 def run(self):
     self.game_gui = Canvas(self.root, width=600, height=600, background='green')
     self.game_gui.bind("<Button-1>", self.click)
     self.game_gui.focus_set()
     self.game_gui.bind("<Key>", self.key)
     self.game_gui.pack()
     for i in range(1, 8):
         self.game_gui.create_line(0, i*75, 600, i*75)
         self.game_gui.create_line(i*75, 0, i*75, 600)
     
     self.pieces = []
     for i in range(8):
         self.pieces.append([])
         for j in range(8):
             self.pieces[i].append(self.game_gui.create_oval(i*75+5, j*75+5, (i+1)*75-5, (j+1)*75-5, fill="green", outline="green"))
     
     self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
     self.root.resizable(0,0)
     self.running = True
     config = EvaluateConfig()
     tf_util.update_memory(config.gpu_mem_fraction)
     AIPlayer.create_if_nonexistant(config)
     self.game = Othello()
     if(random() > 0.5):
         self.human = 1
     else:
         self.human = -1
     
     ai = create_player(config.model_1, config)
     #print("You are playing against", config.model_1)
     #print("Playing games with %d simulations per move" % config.game.simulation_num_per_move)
     self.side = -1
     self.draw_board()
     self.value = ai.evaluate(self.game, self.side)
     while self.running and not self.game.game_over():
         #play move
         if self.side != self.human:
             self.value = ai.evaluate(self.game, self.side)
             self.root.title("Othello (Thinking of Move) Current Value: %0.2f (1 white wins, -1 black wins)" % self.value)
             self.root.config(cursor="wait")
             t = ai.pick_move(self.game, self.side)
             self.game.play_move(t[0], t[1], self.side)
             self.draw_board()
             self.side *= -1
             self.value = ai.evaluate(self.game, self.side)
         else:
             if len(self.game.possible_moves(self.side)) == 0:
                 self.side *= -1
                 continue
             if self.side == -1:
                 color = "black"
             else:
                 color = "white"
             self.root.title("Othello (Play as %s) Current Value: %0.2f (1 white wins, -1 black wins)" % (color, self.value))
             self.root.config(cursor="")
             if self.update:
                 self.update = False
                 if (self.x, self.y) in self.game.possible_moves(self.side):
                     self.game.play_move(self.x, self.y, self.side)
                     self.draw_board()
                     self.side *= -1
         time.sleep(0.01)
     if self.human == self.game.get_winner():
         self.root.title("Othello (You Win!)")
     elif self.game.get_winner() == 0:
         self.root.title("Othello (Its a draw!)")
     else:
         self.root.title("Othello (You Lose!)")