def create_all_next_surviving_actions(self, game: Game) -> List[Action]: """Calculates not only one but all actions that will let the player survive for the next rounds. Args: game: The current state of the game. Returns: A list of actions which will let the player survive for the next rounds. """ root = SearchTreeRoot(game.copy()) player_ids_to_watch = game.get_other_player_ids( self.player, self.__distance_to_check, True) combinations = Action.get_combinations(len(player_ids_to_watch)) search_tree_actions = [] for action in Action.get_actions(): if root.calculate_action(self.player, player_ids_to_watch, combinations, self.__depth, self._turn_ctr, True, [action], self._max_speed, True) is not None: search_tree_actions.append(action) return search_tree_actions
def test_player_with_id_should_be_returned(self): player1 = Player(1, 0, 0, Direction.up, 0, True, "Name") player2 = Player(2, 1, 0, Direction.up, 0, True, "Name") cells = [[Cell([player1]), Cell([player2])]] game = Game(2, 1, cells, [player1, player2], 1, True, datetime.now()) self.assertEqual(player1, game.get_player_by_id(1))
def test_return_no_player_who_is_not_reachable(self): player1 = Player(1, 4, 4, Direction.up, 0, True, "Name 1") player2 = Player(2, 2, 3, Direction.up, 0, True, "Name 2") player3 = Player(3, 1, 4, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell(), Cell(), Cell([player2]), Cell(), Cell()], [Cell(), Cell(), Cell([player2]), Cell(), Cell()], [Cell(), Cell(), Cell([player2]), Cell(), Cell()], [Cell(), Cell(), Cell([player2]), Cell(), Cell()], [ Cell(), Cell([player3]), Cell([player2]), Cell(), Cell([player1]) ]] game = Game(5, 5, cells, players, 1, True, datetime.now()) result = game.get_other_player_ids(player1, 3) self.assertEqual([2], result)
def _create_game(self) -> None: player1 = Player(1, 5, 5, Direction.down, 1, True, "Human Player 1") player2 = Player(2, 25, 5, Direction.down, 1, True, "AI Player 1") player3 = Player(3, 5, 15, Direction.up, 1, True, "AI Player 2") player4 = Player(4, 25, 15, Direction.up, 1, True, "AI Player 4") players = [player1, player2, player3, player4] height = 20 width = 30 cells = [[Cell() for _ in range(width)] for _ in range(height)] cells[player1.y][player1.x] = Cell([player1]) cells[player2.y][player2.x] = Cell([player2]) cells[player3.y][player3.x] = Cell([player3]) cells[player4.y][player4.x] = Cell([player4]) self._game = Game(width, height, cells, players, 1, True, datetime.now(time_zone)) self._game_round = 0 self.__you = None ai0 = ai_classes.RandomAI(player1) # Make a comment out of the next two lines if you do not want to play on your own. self.__you = player1 ai0 = None ai1 = ai_classes.PathfindingAI(player2, 2, 75) ai2 = ai_classes.NotKillingItselfAI(player3, [ai_classes.AIOptions.max_distance], 1, 0, 3) ai3 = ai_classes.SearchTreeAI(player4, 2, 1, True, 10) self._ais = [ai0, ai1, ai2, ai3]
def test_raise_exception_for_winner_in_running_game(self): player = Player(1, 0, 0, Direction.up, 0, True, "Name") cells = [[Cell([player]), Cell()]] game = Game(2, 1, cells, [player], 1, True, datetime.now()) with self.assertRaises(Exception): game.get_winner()
def _create_game(self) -> None: height = randint(30, 70) width = randint(30, 70) player_count = randint(3, 6) players = [] occupied_coordinates = [] for i in range(1, player_count + 1): next_coordinate = (randint(0, width - 1), randint(0, height - 1)) while next_coordinate in occupied_coordinates: next_coordinate = (randint(0, width - 1), randint(0, height - 1)) occupied_coordinates.append(next_coordinate) player = Player(i, next_coordinate[0], next_coordinate[1], Direction.get_random_direction(), 1, True, str(i)) players.append(player) cells = [[Cell() for _ in range(width)] for _ in range(height)] for player in players: cells[player.y][player.x] = Cell([player]) self._game = Game(width, height, cells, players, 1, True, datetime.now() + timedelta(5, 15)) self._game_round = 0 self._ais = [] if self.__evaluation_type == 1: self.__generate_ais_for_first_evaluation(player_count, players) elif self.__evaluation_type == 2: self.__generate_ais_for_second_evaluation(player_count, players)
def test_return_all_players_except_one_within_distance_2(self): player1 = Player(1, 4, 4, Direction.up, 0, True, "Name 1") player2 = Player(2, 2, 3, Direction.up, 0, True, "Name 2") player3 = Player(3, 1, 4, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell(), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell(), Cell([player2]), Cell(), Cell()], [ Cell(), Cell([player3]), Cell([player2]), Cell(), Cell([player1]) ]] game = Game(5, 5, cells, players, 1, True, datetime.now()) result = game.get_other_player_ids(player1, 3) self.assertEqual([2], result)
def test_raise_exception_when_player_id_invalid(self): player1 = Player(1, 1, 0, Direction.up, 0, True, "Name") player2 = Player(2, 0, 0, Direction.up, 0, True, "Name") cells = [[Cell([player2]), Cell([player1])]] game = Game(2, 1, cells, [player1, player2], 1, True, datetime.now()) with self.assertRaises(PlayerWithGivenIdNotAvailableException): game.get_player_by_id(100)
def test_return_no_winner_in_ended_game(self): player1 = Player(1, 0, 0, Direction.up, 0, False, "Name") player2 = Player(1, 1, 0, Direction.up, 0, False, "Name") cells = [[Cell([player1]), Cell([player2])]] game = Game(2, 1, cells, [player1, player2], 1, False, datetime.now()) result = game.get_winner() self.assertEqual(None, result)
def test_return_all_other_active_players(self): player1 = Player(1, 1, 1, Direction.up, 0, True, "Name 1") player2 = Player(2, 1, 0, Direction.up, 0, False, "Name 2") player3 = Player(3, 0, 0, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell([player3]), Cell([player2])], [Cell([]), Cell([player1])]] game = Game(2, 2, cells, players, 1, True, datetime.now()) result = game.get_other_player_ids(player1, check_active=True) self.assertEqual([3], result)
def test_translate_cell_matrix_to_pathfinding_matrix_should_be_correct( self): player1 = Player(1, 0, 0, Direction.up, 1, True, "") player2 = Player(2, 0, 1, Direction.down, 3, True, "") players = [player1, player2] cells = [[Cell([player1]), Cell()], [Cell([player2]), Cell()], [Cell(), Cell()]] game = Game(2, 3, cells, players, 2, True, datetime.now()) expected_matrix = [[0, 1], [0, 1], [1, 1]] matrix = game.translate_cell_matrix_to_pathfinding_matrix() self.assertEqual(matrix, expected_matrix)
def test_copying_a_game_should_return_same_game_but_different_identity( self): player1 = Player(1, 1, 1, Direction.up, 0, True, "Name") player2 = Player(2, 1, 0, Direction.up, 0, True, "Name2") player3 = Player(3, 0, 0, Direction.up, 0, True, "Name3") players = [player1, player2, player3] cells = [[Cell([player3]), Cell([player2])], [Cell([]), Cell([player1])]] game = Game(2, 2, cells, players, 2, True, datetime.now()) result = game.copy() self.assertEqual(game, result) self.assertNotEqual(id(game), id(result))
def create_next_action(self, game: Game, return_value: Value): """See base class.""" self._turn_ctr += 1 root = SearchTreeRoot(game.copy()) player_ids_to_watch = game.get_other_player_ids( self.player, self.__distance_to_check, True) combinations = Action.get_combinations(len(player_ids_to_watch)) action = root.calculate_action(self.player, player_ids_to_watch, combinations, self.__depth, self._turn_ctr, True, [], self._max_speed, self.__randomize) return_value.value = (action if action is not None else Action.get_random_action()).get_index()
def test_convert_json_to_running_game(self): json = tests.read_test_file("service/game.json") player1 = Player(1, 2, 2, Direction.up, 1, True, "") player2 = Player(2, 1, 0, Direction.down, 3, True, "") player3 = Player(3, 4, 3, Direction.left, 2, False, "Name 3") players = [player1, player2, player3] cells = [[Cell(), Cell([player2]), Cell(), Cell(), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell([player1]), Cell([player1]), Cell(), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell([player3])]] time = datetime(2020, 10, 1, 12, 5, 13, 0, timezone.utc) expected = Game(5, 4, cells, players, 2, True, time) result = self.sut.load(json) self.assertEqual(expected, result)
def test_convert_json_to_ended_game(self): json = tests.read_test_file("service/game_ended.json") player1 = Player(1, 2, 2, Direction.up, 1, True, "") player2 = Player(2, 1, 0, Direction.down, 3, True, "") player3 = Player(3, 4, 3, Direction.left, 2, False, "Name 3") players = [player1, player2, player3] cells = [[Cell(), Cell([player2]), Cell(), Cell(), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell([player1]), Cell([player1]), Cell(), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell([player3])]] expected = Game(5, 4, cells, players, 2, False) result = self.sut.load(json) self.assertEqual(expected, result)
def test_raise_exception_on_non_existing_own_player(self): player1 = Player(1, 0, 1, Direction.up, 0, True, "Name 1") player3 = Player(3, 0, 0, Direction.up, 0, True, "Name 3") players = [player1, player3] cells = [[Cell([player3]), Cell([])], [Cell([player1]), Cell()]] with self.assertRaises(OwnPlayerMissingException): Game(2, 2, cells, players, 2, True, datetime.now())
def test_correct_output_no_winner(self, mock_stdout): player1 = Player(1, 0, 0, Direction.up, 1, False, "p1") player2 = Player(2, 0, 1, Direction.down, 3, False, "") cells = [[Cell([player1])], [Cell([player2])]] game = Game(1, 2, cells, [player1, player2], 2, False, datetime.now()) self.sut.update(game) self.assertTrue("No winner in game." in str(mock_stdout.getvalue()))
def test_raise_exception_on_wrong_player_position(self): player1 = Player(1, 1, 1, Direction.up, 0, True, "Name 1") player2 = Player(2, 0, 0, Direction.up, 0, True, "Name 2") player3 = Player(3, 0, 1, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell([player2]), Cell([player3])], [Cell(), Cell([player1])]] with self.assertRaises(PlayerPositionException): Game(2, 2, cells, players, 2, True, datetime.now())
def update(self, game: Game): """See base class.""" if not self._interface_initialized: self._initialize_interface(game) print("Round : ", self.__round) self.__round += 1 table_player_ids = [] for row in range(len(game.cells)): row_cells = [] for col in range(len(game.cells[0])): cell = game.cells[row][col] if cell.get_player_id() == 0: row_cells.append(' ') else: player = game.get_player_by_id(cell.get_player_id()) color = self._player_colors[self.__player_representation[ cell.get_player_id()]] if player.x == col and player.y == row: if player == game.you: row_cells.append(colored("x", color)) else: row_cells.append(colored("o", color)) else: row_cells.append( colored( str(self.__player_representation[player.id]), color)) table_player_ids.append(row_cells) print( tabulate(table_player_ids, tablefmt="jira").replace( " ", "").replace("||", "| |").replace("||", "| |")) if not game.running: player = game.get_winner() if player is None: print("No winner in game.") else: print("Winner: Player " + str(self.__player_representation[player.id]) + " (" + player.name + "). Your player ID was " + str(self.__player_representation[game.you.id]))
def test_examines_your_player_after_creation(self): player1 = Player(1, 0, 1, Direction.up, 0, True, "Name 1") player2 = Player(2, 1, 0, Direction.up, 0, True, "Name 2") player3 = Player(3, 0, 0, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell([player3]), Cell([player2])], [Cell([player1]), Cell()]] game = Game(2, 2, cells, players, 2, True, datetime.now()) self.assertEqual(game.you, player2)
def test_draws_all_players_correctly_in_ended_game_with_winner(self, mock_stdout): player1 = Player(1, 1, 0, Direction.up, 1, True, "Jonas") player2 = Player(2, 0, 1, Direction.down, 3, False, "Florian") cells = [[Cell(), Cell([player1])], [Cell([player2]), Cell()]] game = Game(2, 2, cells, [player1, player2], 2, False, datetime.now()) self.sut.update(game) self.assertTrue("Winner: Player 1 (Jonas). Your player ID was 2." in str(mock_stdout.getvalue()))
def test_correct_output_round_2(self, mock_stdout): player1 = Player(1, 0, 0, Direction.up, 1, True, "p1") player2 = Player(2, 0, 1, Direction.down, 3, True, "") cells = [[Cell([player1]), Cell([player1])], [Cell([player2]), Cell()]] game = Game(2, 2, cells, [player1, player2], 2, True, datetime.now()) self.sut.update(game) self.sut.update(game) self.assertTrue("Round : 0" in str(mock_stdout.getvalue())) self.assertTrue("Round : 1" in str(mock_stdout.getvalue()))
def test_dont_raise_exception_on_wrong_inactive_player_position(self): player1 = Player(1, 1, 1, Direction.up, 0, False, "Name 1") player2 = Player(2, 1, 0, Direction.up, 0, True, "Name 2") player3 = Player(3, 0, 1, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell([]), Cell([player2])], [Cell([player3]), Cell([player3])]] game = Game(2, 2, cells, players, 2, True, datetime.now()) self.assertEqual(game.you, player2)
def setUp(self): self.player1 = Player(1, 10, 10, Direction.down, 1, True, "") self.player2 = Player(2, 10, 30, Direction.down, 3, True, "") self.player3 = Player(3, 30, 10, Direction.right, 2, True, "Name 3") players = [self.player1, self.player2, self.player3] cells = [[Cell() for _ in range(40)] for _ in range(40)] cells[self.player1.y][self.player1.x] = Cell([self.player1]) cells[self.player2.y][self.player2.x] = Cell([self.player2]) cells[self.player3.y][self.player3.x] = Cell([self.player3]) time = datetime(2020, 10, 1, 12, 5, 13, 0, timezone.utc) self.game = Game(40, 40, cells, players, 2, True, time) self.sut = GameService(self.game)
def create_game(game_ended: bool): player1 = Player(1, 10, 10, Direction.down, 1, True, "") player2 = Player(2, 10, 30, Direction.down, 3, True, "") player3 = Player(3, 30, 10, Direction.right, 2, True, "Name 3") players = [player1, player2, player3] cells = [[Cell() for _ in range(40)] for _ in range(40)] for player in players: cells[player.y][player.x] = Cell([player]) return Game(40, 40, cells, players, 2, game_ended, datetime(2020, 10, 1, 12, 5, 13, 0, timezone.utc))
def test_create_action_should_return_None_if_given_action_list_is_none(self): player1 = Player(1, 0, 0, Direction.right, 2, True, "") player2 = Player(2, 0, 2, Direction.down, 3, True, "") players = [player1, player2] cells = [[Cell([player1]), Cell(), Cell()], [Cell(), Cell([player2]), Cell()], [Cell([player2]), Cell(), Cell()]] game = Game(3, 3, cells, players, 2, True, datetime.now()) sut = PathfindingAI(player1, 2, 10) actions = sut.find_actions_by_best_path_connection(None, game) self.assertIsNone(actions)
def test_create_action_should_return_one_of_the_possible_action_with_best_connection(self): player1 = Player(1, 0, 0, Direction.right, 2, True, "") player2 = Player(2, 0, 2, Direction.down, 3, True, "") players = [player1, player2] cells = [[Cell([player1]), Cell(), Cell()], [Cell(), Cell([player2]), Cell()], [Cell([player2]), Cell(), Cell()]] game = Game(3, 3, cells, players, 2, True, datetime.now()) sut = PathfindingAI(player1, 2, 10) actions = sut.find_actions_by_best_path_connection([Action.change_nothing, Action.slow_down], game) self.assertEqual(actions[0][0], Action.slow_down)
def __try_combination(game: Game, player_ids_to_watch: List[int], combination: Tuple[Action], turn_counter: int): modified_game = game.copy() game_service = GameService(modified_game) game_service.turn.turn_ctr = turn_counter players = modified_game.get_players_by_ids(player_ids_to_watch) for j in range(len(combination)): action = combination[j] player = players[j] SearchTreeRoot.__perform_simulation(game_service, action, player) game_service.check_and_set_died_players() return SearchTreeRoot(modified_game.copy())
def test_create_action_should_return_action_with_best_connection(self): player1 = Player(1, 0, 0, Direction.down, 1, True, "") player2 = Player(2, 0, 2, Direction.down, 3, True, "") players = [player1, player2] cells = [[Cell([player1]), Cell(), Cell()], [Cell(), Cell([player2]), Cell()], [Cell([player2]), Cell(), Cell()]] game = Game(3, 3, cells, players, 2, True, datetime.now()) sut = PathfindingAI(player1, 2, 10) result = Value('i') sut.create_next_action(game, result) self.assertEqual(Action.turn_left, Action.get_by_index(result.value))
def update(self, game: Game): """See base class.""" if not self._interface_initialized: self._initialize_interface(game) if not game.running: player = game.get_winner() if player is None: print("No winner in game.") else: print("Winner: Player " + str(player.id) + " (" + player.name + "). Your player ID was " + str(game.you.id) + ".") self.__screen.fill((0, 0, 0)) # black background for row in range(game.height): for col in range(game.width): self.__pygame.draw.rect(self.__screen, self.__get_player_color(game.cells[row][col]), (col * self.RECT_SIZE + col, row * self.RECT_SIZE + row, self.RECT_SIZE, self.RECT_SIZE)) if game.cells[row][col].get_player_id() != 0: player = game.get_player_by_id(game.cells[row][col].get_player_id()) if player.x == col and player.y == row: # print head border_width = 2 if player == game.you: border_width = 4 # head of the own player has a smaller dot self.__pygame.draw.rect(self.__screen, self._player_colors[0], (col * self.RECT_SIZE + col + border_width, row * self.RECT_SIZE + row + border_width, self.RECT_SIZE - (2 * border_width), self.RECT_SIZE - (2 * border_width))) self.__pygame.display.update() self.__clock.tick(60)