Пример #1
0
def test_board_execute_move_3_1_1():
    board = Board(3)
    board.execute_move([1, 1])

    assert board.board == [[' ', ' ', ' '], [' ', 'X', ' '], [' ', ' ', ' ']]
    assert board.turn == 2
    assert board.gameover == False
Пример #2
0
def test_board_init_4():
    board = Board(4)

    assert board.board == [[' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '],
                           [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ']]
    assert board.turn == 1
    assert board.gameover == False
Пример #3
0
def test_board_execute_move_invalid():
    board = Board(3)
    board.execute_move([1])

    assert board.board == [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
    assert board.turn == 1
    assert board.gameover == False
Пример #4
0
def prepare_game(board_file: str, players: List[discord.User],
                 channel: discord.TextChannel) -> MonopolyCore.Monopoly:
    players_class = []
    for player in players:
        players_class.append(Player.Player(player))
    board = Board.Board(board_file)
    return MonopolyCore.Monopoly(monopoly_bot, channel, players_class, board)
Пример #5
0
def main():
    """Run the XOD game loop."""
    board = Board()

    player_1 = CPU('X', 'O')
    player_2 = CPU('O', 'X')

    board.display()
    while True:
        player_1.move(board)
        board.display()

        winner = board.is_there_a_winner()
        if winner == player_1.marker:
            print('Player %s has won!' % winner)
            break
        elif winner == '-':
            print('No winners.')
            break

        player_2.move(board)
        board.display()

        winner = board.is_there_a_winner()
        if winner == player_2.marker:
            print('Player %s has won!' % winner)
            break
        elif winner == '-':
            print('No winners.')
            break
Пример #6
0
 def test_has_difference_true(self):
     test_board = Board(dimension=n, color_count=m)
     test_plate = [[
         random.choice(string.ascii_uppercase) for i in range(n)
     ] for j in range(n)]
     test_plate[0][0] = '1'
     test_board.set_plate(plate=test_plate)
     self.assertEqual(True, test_board.has_differences())
Пример #7
0
    def test_current_player(self):
        b = Board()

        self.assertEqual(b.current_player(), 'p1')
        b.tick()
        self.assertEqual(b.current_player(), 'p2')
        b.tick()
        self.assertEqual(b.current_player(), 'p1')
Пример #8
0
    def load_scenario(self):
        """Load the chosen Scenario."""
        self.rendering_mode = RenderingMode.LOAD_SCENARIO
        # Unpickle the Scenario file
        self.scenario = load(open(self.scenario, "rb"))

        # Log Version of the scenario and code
        print("Loading Scenario Version %s with code base Version %s" %
              (self.scenario.get_version(), __version__))

        license = self.scenario.get_license()
        if license is not None:
            print("Scenario licensed as follows:")
            print("")
            print(license)
        else:
            print("No license provided in scenario file.")

        # Get the logo to display (if any)
        self.logo = self.scenario.get_logo()

        # Load variables into memory
        self.step = self.scenario.get_board_step()
        self.height = self.scenario.get_logical_height() * self.step
        self.width = self.scenario.get_logical_width() * self.step

        self.board = Board(self.scenario)

        self.robot = BeeBot(self.scenario)

        self.clock = pygame.time.Clock()

        buttons_on_the_left = True

        self.create_buttons(buttons_on_the_left)

        if buttons_on_the_left:
            # Make space for:
            # - the Buttons to the right of the map.
            # - the CommandLog below the map.
            self.size = (self.width + 400, self.height + 30)
            # Create the empty CommandLog
            self.command_log = CommandLog(Point(0, self.height),
                                          (self.width, 30))
        else:
            # Make space for:
            # - the Buttons below the map.
            # - the CommandLog to the right of the map.
            self.size = (self.width + 30, self.height + 400)
            # Create the empty CommandLog
            self.command_log = CommandLog(Point(self.width, 0),
                                          (30, self.height))

        # Only want to do this once, so sadly can't do it in the rendering
        # loop without a potential race condition as
        # size gets set by loading the Scenario
        if self._rendering_running:
            self.screen = pygame.display.set_mode(self.size)
    def test_score_calculation(self):
        current_state = [[0, 0, 0, 0], [0, 0, 2, 0], [0, 0, 2, 2],
                         [0, 2, 4, 4]]

        current_score = 0
        test_board = Board(current_state)
        test_board.move_board('down')
        test_board_score = test_board.score
        self.assertEqual(current_score + 4, test_board_score)
Пример #10
0
    def test_score_calculation_multiple_merges(self):
        current_state = [[0, 0, 0, 0], [0, 0, 2, 0], [0, 0, 2, 2],
                         [0, 2, 4, 4]]

        current_score = 0
        test_board = Board(current_state)
        test_board.move_board('left')
        test_board_score = test_board.score
        self.assertEqual(current_score + 12, test_board_score)
Пример #11
0
    def test_move_left_restricted(self):
        current_state = [[2, 0, 0, 0], [2, 0, 0, 0], [4, 2, 0, 0],
                         [4, 2, 0, 0]]

        test_board = Board(current_state)
        test_board.move_board('left')
        next_state = test_board.board

        self.assertEqual(next_state, current_state)
Пример #12
0
    def test_random_spawn_on_stationary_board(self):
        current_state = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, 2],
                         [0, 2, 4, 4]]

        test_board = Board(current_state)
        test_board.move_board('down')
        test_board.add_random_tile()  # should not spawn a random tile

        self.assertEqual(current_state, test_board.board)
Пример #13
0
    def test_move_down_restricted(self):
        current_state = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, 2],
                         [0, 2, 4, 4]]

        test_board = Board(current_state)
        test_board.move_board('down')
        next_state = test_board.board

        self.assertEqual(next_state, current_state)
Пример #14
0
    def test_move_right_restricted(self):
        current_state = [[0, 0, 0, 2], [0, 0, 0, 2], [0, 0, 2, 4],
                         [0, 0, 2, 4]]

        test_board = Board(current_state)
        test_board.move_board('right')
        next_state = test_board.board

        self.assertEqual(next_state, current_state)
Пример #15
0
def train(input_size: int, hidden_size: int, num_classes: int, num_epochs: int,
          num_games: int, batch_size: int, learning_rate: float,
          mcts_iter: int):
    # Create the model
    input_shape = (6, 7, 2)
    model = model_structure(hidden_size, input_shape)
    model._make_predict_function()

    # Train the model
    for e in range(num_games):

        # Create the board
        b = Board()

        # Create the players and the game
        p1 = NNPlayer(1, b, model, training=True)
        p2 = NNPlayer(2, b, model, training=True)
        nn_g = NNRecordedGame_mp(b, p1, p2, mcts_iter)
        nn_g.initialize()

        # Play the game
        nn_g.play_a_game(True)

        # Get all winner's moves
        # if nn_g.winner == p1.name:
        #     input_data, output_data = get_all_player_moves(nn_g, p1)
        # elif nn_g.winner == p2.name:
        #     input_data, output_data = get_all_player_moves(nn_g, p2)
        # else:
        input_p1, output_p1 = get_all_player_moves(nn_g, p1)
        input_p2, output_p2 = get_all_player_moves(nn_g, p2)
        input_data = np.concatenate([input_p1, input_p2])
        output_data = np.concatenate([output_p1, output_p2])

        # build the batch
        step = int(len(input_data) / batch_size)
        if step > 0:
            input_data = build_batch(input_data, step)
            output_data = build_batch(output_data, step)
            e_batch_size = batch_size
        else:
            e_batch_size = len(input_data)

        # fit the model
        model.fit(input_data,
                  output_data,
                  batch_size=e_batch_size,
                  epochs=num_epochs * (e + 1),
                  initial_epoch=num_epochs * e,
                  verbose=1)

        # save the model every 100 games played
        if e and e % 100 == 0:
            model.save(f'{round(time.time())}_my_model.h5')
    return model
Пример #16
0
    def test_move_down(self):
        current_state = [[0, 0, 0, 2], [0, 0, 0, 2], [0, 0, 2, 2],
                         [0, 0, 0, 2]]

        test_board = Board(current_state)
        test_board.move_board('down')
        next_state = test_board.board

        true_next_state = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 4],
                           [0, 0, 2, 4]]

        self.assertEqual(next_state, true_next_state)
Пример #17
0
    def test_move_left(self):
        current_state = [[0, 0, 0, 2], [0, 0, 0, 2], [0, 0, 2, 2],
                         [0, 0, 0, 2]]

        test_board = Board(current_state)
        test_board.move_board('left')
        next_state = test_board.board

        true_next_state = [[2, 0, 0, 0], [2, 0, 0, 0], [4, 0, 0, 0],
                           [2, 0, 0, 0]]

        self.assertEqual(next_state, true_next_state)
Пример #18
0
def test_board_check_win_ver():
    board = Board(3)
    board.execute_move([0, 0])
    board.execute_move([0, 1])
    board.execute_move([1, 0])
    board.execute_move([1, 1])
    board.execute_move([2, 0])
    board.check_win()

    assert board.board == [['X', 'O', ' '], ['X', 'O', ' '], ['X', ' ', ' ']]

    assert board.gameover == True
Пример #19
0
    def one_turn(self):
        """
        Run one turn of the game.
        Returns:
            continue (bool): whether restart the game
        """
        # initiate the board
        board_size = self.view.get_board_size()
        if board_size == {}:
            board = Board()
        else:
            board = Board(mine_count=board_size["mine_count"],
                          width=board_size["width"],
                          height=board_size["height"])

        while not board.is_game_finish():
            operation = self.view.run(board.get_board())
            if not board.update(operation["x"], operation["y"],
                                operation["flag"]):
                self.view.draw(board.get_board())
                return self.view.fail()
        return self.view.win()
Пример #20
0
def acquireSample(state):
    gui = GUI()
    board = Board()

    board.startDataAcquisition()
    gui.loadImage(state)
    time.sleep(10)

    sample = board.getEGG_Data()
    board.releaseBoardSession()
    gui.closeImage()

    return sample
Пример #21
0
    def test_play_10_games_randomVSrandom(self):

        board = Board()
        player1 = RandomPlayer()
        player2 = RandomPlayer()
        match = Match()

        cross_count, naught_count, draw_count = match.play(
            player1, player2, 10)

        self.assertGreaterEqual(cross_count, 0)
        self.assertGreaterEqual(naught_count, 0)
        self.assertGreaterEqual(draw_count, 0)
Пример #22
0
 def __init__(self, tree, manager, dimension, numbered):
     self.com_moves = []
     self.user_moves = []
     self.game = {'com': self.com_moves, 'user': self.user_moves}
     self.tree = tree
     self.manager = manager
     self.dimension = dimension
     self.game_board = Board(dimension, numbered)
     fin_game = self.play()
     if self.game_board.won:
         manager.trainer(fin_game,
                         tree,
                         board=self.game_board,
                         dimension=self.dimension)
Пример #23
0
def test_board_check_win_diag():
    board = Board(3)
    board.execute_move([0, 0])
    board.execute_move([0, 1])
    board.execute_move([1, 1])
    board.execute_move([1, 2])
    board.execute_move([2, 2])

    assert board.size == 3

    assert board.board == [['X', 'O', ' '], [' ', 'X', 'O'], [' ', ' ', 'X']]

    board.check_win()

    assert board.gameover == True
Пример #24
0
def set_up_game() -> Game:
    """
    This function sets up the logic and data structures for the game by
    initializing relevant classes
    """
    global GAME_MODE
    game_board = Board(DIMENSION)
    player1 = Human("Player 1", game_board)
    if GAME_MODE == 0:
        return Game(player1, Human("Player 2", game_board), game_board)
    elif GAME_MODE == 1:
        return Game(player1, EasyAI("Player 2", game_board), game_board)
    elif GAME_MODE == 2:
        return Game(player1, MediumAI("Player 2", game_board), game_board)
    elif GAME_MODE == 3:
        return Game(player1, HardAI("Player 2", game_board), game_board)
Пример #25
0
 def fire(self, lograte, print_board=False):
     for j in range(self.n_games):
         if j % lograte == 0:
             print(f'Playing Game {j + 1}')
         b = Board()
         self.player_one.board = b
         self.player_two.board = b
         g = Game(b, self.player_one, self.player_two)
         g.play_a_game(print_board)
         if j % lograte == 0:
             print(f'Player {g.winner} won')
         if g.winner is not None:
             self.results[g.winner] += 1
     print(f'Player {self.player_one.name} won'
           f' {self.results[self.player_one.name]} times\n'
           f'Player {self.player_two.name} won'
           f' {self.results[self.player_two.name]} times')
Пример #26
0
    def __init__(self):

        # Set up frame and window
        self.ROOT = Tk()
        self.EMPTY_FOUNDATION = PhotoImage(file='assets\\foundation.png')
        self.ROOT.config(pady=5)
        self.ROOT.title("Baker's Dozen")
        self.ROOT.geometry("1050x725")

        # Create game board
        self.mainboard = Board(self.ROOT)

        # Place placeholders
        self.place_placeholders()

        # Start the main window loop
        self.ROOT.mainloop()
Пример #27
0
    def setUp(self):
        """
        Create a minimal Scenario and use it to create a Board.

        The Scenario is 5x5 (logical size) with the no BeeBot,
        but one Obstacle and Goal.
        """
        # Create the minimal Scenario
        test_scenario = Scenario('Test')
        test_scenario.set_board_step(150)
        test_scenario.set_logical_width(5)
        test_scenario.set_logical_height(8)
        test_scenario.set_background('img/Default/background.jpg')
        test_scenario.add_goal(0, 0)
        test_scenario.add_obstacle(1, 1)

        # Create the test Board
        self.test_board = Board(test_scenario)
Пример #28
0
    def load_scenario(self):
        """Load the chosen Scenario."""
        self.rendering_mode = RenderingMode.LOAD_SCENARIO
        # Unpickle the Scenario file
        self.scenario = load(open(self.scenario, "rb"))

        # Log Version of the scenario and code
        print("Loading Scenario Version %s with code base Version %s" %
              (self.scenario.get_version(), __version__))

        license = self.scenario.get_license()
        if license is not None:
            print("Scenario licensed as follows:")
            print("")
            print(license)
        else:
            print("No license provided in scenario file.")

        # Get the logo to display (if any)
        self.logo = self.scenario.get_logo()

        # Load variables into memory
        self.step = self.scenario.get_board_step()
        self.height = self.scenario.get_logical_height() * self.step
        self.width = self.scenario.get_logical_width() * self.step

        self.board = Board(self.scenario)

        self.robot = BeeBot(self.scenario)

        self.clock = pygame.time.Clock()

        buttons_on_the_left = True

        self.create_buttons(buttons_on_the_left)

        if buttons_on_the_left:
            self.size = (self.width + 400, self.height)
        else:
            self.size = (self.width, self.height + 400)

        self.screen = pygame.display.set_mode(self.size)
Пример #29
0
 def fire(self):
     for j in range(self.n_games):
         print(f'Playing Game {j + 1}')
         b = Board()
         self.player_one.board = b
         self.player_two.board = b
         rg = RecordedAIGame(b, self.player_one, self.player_two)
         rg.initialize()
         rg.play_a_game()
         print(f'Player {rg.winner} won')
         if rg.winner is not None:
             self.results[rg.winner] += 1
         actions, states, res = rg.export_final_results()
         if res is 'ok' and b.plays > 3:
             dim_s = states.shape[0]
             last_states = states[np.array([dim_s - 2, dim_s - 1])]
             self.states = np.append(self.states, last_states, axis=0)
             last_actions = actions[np.array([dim_s - 2, dim_s - 1])]
             self.actions = np.append(self.actions, last_actions, axis=0)
     print(f'Player {self.player_one.name} won {self.results[self.player_one.name]} time'
           f's\nPlayer {self.player_two.name} won {self.results[self.player_two.name]} tim'
           f'es')
Пример #30
0
    def set_up_new_game(self):
        self.board = Board(self.display)
        self.pieces = []
        self.players = []

        # For two teams, white and black
        for t in [True, False]:
            # Create a lay out the pieces
            self.pieces.append(King(self.display, t))
            self.pieces.append(Queen(self.display, t))
            for p in range(8):
                self.pieces.append(Pawn(self.display, t, p))
                if p < 2:
                    self.pieces.append(Bishop(self.display, t, p))
                    self.pieces.append(Knight(self.display, t, p))
                    self.pieces.append(Rook(self.display, t, p))

            # Also create a player for the team
            #self.players.append(Player(t,True))
            self.players.append(Player(t, t))

        self.turn_counter = 0