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
def testMulitCellRevealCounter(self): random.seed(0xDEADBEEF) expected_value = 19 test_board = Board(5, 5) test_board.scatter_bombs(5, rand=random.random) observed_value = test_board.reveal_location(0, 4) self.assertEqual(expected_value, observed_value)
def testPlaceMultipleBombs(self): expected_board = [[2, -1], [-1, 2]] test_board = Board(2,2) test_board.place_bomb(1, 0) test_board.place_bomb(0, 1) observed_board = test_board.board self.assertEqual(expected_board, observed_board)
def testCollidingSums(self): expected_board = [[0, 2, 0], [1, 2, 1], [0, 0, 0]] test_board = Board(3,3) test_board.sum_surrounding(0, 0) test_board.sum_surrounding(2, 0) observed_board = test_board.board self.assertEqual(expected_board, observed_board)
def testBombReveal(self): random.seed(0xDEADBEEF) expected_value = -1 test_board = Board(5, 5) test_board.scatter_bombs(5, rand=random.random) observed_value = test_board.reveal_location(0, 2) self.assertEqual(expected_value, observed_value)
def test_board_execute_move_invalid(): board = Board(3) board.execute_move([1]) assert board.board == [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] assert board.turn == 1 assert board.gameover == False
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
def testDuplicateSpotScatter(self): random.seed(3) expected_board = [[2,-1],[-1,2]] test_board = Board(2,2) test_board.scatter_bombs(2, rand=random.random) observed_board = test_board.board self.assertEqual(expected_board, observed_board)
class TestBoard(unittest.TestCase): """This test class unit tests the Board class.""" 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) def test_display(self): """ Test the display method of a Board. All this really does is make sure the method executes correctly. If the method call errors, the test will fail. """ # Create a test screen to dsiplay things on test_screen = pygame.display.set_mode((1500, 1500)) # Attempt to display the test Board self.test_board.display(test_screen)
def testSingleCellReveal(self): random.seed(0xDEADBEEF) expected_board = [[False, True], [False, False]] test_board = Board(2,2) test_board.scatter_bombs(1, rand=random.random) test_board.reveal_location(1,0) observed_board = test_board.trackboard self.assertEqual(expected_board, observed_board)
def testNormalScatter(self): # Fake out the random number generator random.seed(0xDEADBEEF) expected_board = [[-1,1],[1,1]] test_board = Board(2,2) test_board.scatter_bombs(1, rand=random.random) observed_board = test_board.board self.assertEqual(expected_board, observed_board)
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())
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)
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)
def testMultiCellReveal(self): random.seed(6702) expected_board = [[True, True, False], [True, True, False], [False, False, False]] test_board = Board(3,3) test_board.scatter_bombs(4, random.random) test_board.reveal_location(0,0) observed_board = test_board.trackboard self.assertEqual(expected_board, observed_board)
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)
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)
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)
class Engine: def __init__(self): self.board = Board() def step(self, player_char, column): step_success = False game_is_running = True for i in range(0, Board.NUM_ROWS): row = Board.NUM_ROWS - 1 - i if self.board.board_char_representation[row][ column] == Board.CHAR_EMPTY: if player_char == Board.CHAR_PLAYER_A: self.board.set_cell_state(row, column, Board.X_OCCUPIED_CELL) step_success = True break elif player_char == Board.CHAR_PLAYER_B: self.board.set_cell_state(row, column, Board.O_OCCUPIED_CELL) step_success = True break self.board.convert_to_char_representation() self.board.print_char_representation() are_4_connected, char = self.board.are_4_connected() if (are_4_connected): print("4 connected by " + char) game_is_running = False return step_success, game_is_running def get_board(self): return self.board
class Match(): """Logic of connect4 ongoing match""" def __init__(self, first_player=const.PlayerTurn.RED) -> None: """Constructor""" self.board = Board() self.column_selected = 0 self.state = const.MatchState.PLAYING self.player_turn = first_player def add_checker(self): """Add checker of current player to currently selected column""" if self.player_turn == const.PlayerTurn.RED: self.board.add_checker_red(self.column_selected) else: self.board.add_checker_yellow(self.column_selected) if self.board.is_game_won(): self.state = (const.MatchState.RED_WON if self.player_turn == const.PlayerTurn.RED else const.MatchState.YELLOW_WON) else: self._toggle_player() def column_next(self): """Change column selection to column immediately right""" increment = 1 self._column_change(increment) def column_previous(self): """Change column selection to column immediately left""" increment = -1 self._column_change(increment) def is_being_played(self): """Return if match is still ongoing""" return self.state == const.MatchState.PLAYING def _column_change(self, increment): """Change current column according to increment/offset""" self.column_selected += increment if self.column_selected == const.BOARD_TOTAL_COLUMNS: self.column_selected = 0 elif self.column_selected < 0: self.column_selected = const.BOARD_TOTAL_COLUMNS - 1 if self.board.columns[self.column_selected].is_full(): self._column_change(increment) def _toggle_player(self): """Toggle current player""" self.player_turn = (const.PlayerTurn.RED if self.player_turn == const.PlayerTurn.YELLOW else const.PlayerTurn.YELLOW)
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')
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
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)
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)
def testBombCellReveal(self): random.seed(0xDEADBEEF) expected_board = " 0 1 2 3 4\n" + \ "0: |_|_|_|_|_|\n" + \ "1: |_|_|_|_|_|\n" + \ "2: |*|_|_|_|_|\n" + \ "3: |_|_|_|_|_|\n" + \ "4: |_|_|_|_|_|" test_board = Board(5,5) test_board.scatter_bombs(5, rand=random.random) test_board.reveal_location(0,2) observed_board = str(test_board) self.assertEqual(expected_board, observed_board)
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)
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
def test_board_init_4(): board = Board(4) assert board.board == [[' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ']] assert board.turn == 1 assert board.gameover == False
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)
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 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)
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
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)
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)
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
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)
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()
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')
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)
def testFullBoardReveal(self): expected_board = [[True]*10]*10 test_board = Board(10, 10) test_board.reveal_location(0,0) observed_board = test_board.trackboard self.assertEqual(expected_board, observed_board)
def testSmallDimensions(self): expected_board = [[0]] observed_board = Board.create_empty_board(1, 1) self.assertEqual(expected_board, observed_board)
def testLoneCell(self): expected_board = [[1,1,1],[1,0,1],[1,1,1]] test_board = Board(3,3) test_board.sum_surrounding(1,1) observed_board = test_board.board self.assertEqual(expected_board, observed_board)
def testDifferentDimensions(self): expected_board = [[0] *3] *4 observed_board = Board.create_empty_board(3, 4) self.assertEqual(expected_board, observed_board)
def testPlaceBomb(self): expected_board = [[1, 1], [-1, 1]] test_board = Board(2,2) test_board.place_bomb(0, 1) observed_board = test_board.board self.assertEqual(expected_board, observed_board)
def testPlaceBombDifferentDimensionBoard(self): expected_board = [[0, 1, -1], [0, 1, 1]] test_board = Board(3, 2) test_board.place_bomb(2, 0) observed_board = test_board.board self.assertEqual(expected_board, observed_board)
def testNormalDimensions(self): expected_board = [[0] *10] *10 observed_board = Board.create_empty_board(10, 10) self.assertEqual(expected_board, observed_board)