def test_convert3(): game = Game(wait_agent, wait_agent) s = game.players[0].ships[0] game.players[0].halite = 499 assert s.halite == 0 s.convert() assert game.players[0].halite == 499 players = game.players ships0 = players[0].ships ship_array0 = players[0].ship_array shipyards0 = players[0].shipyards shipyard_array0 = players[0].shipyard_array ships1 = players[1].ships ship_array1 = players[1].ship_array shipyards1 = players[1].shipyards shipyard_array1 = players[1].shipyard_array assert len(ships0) == 1 assert len(ships1) == 1 assert ship_array0[10][5] != [] assert ship_array1[10][15] != [] assert len(shipyards0) == 0 assert len(shipyards1) == 0 assert shipyard_array0[10][5] == 0 assert shipyard_array1[10][15] == 0
def test_ship_collision4(): game = Game(wait_agent, wait_agent) s1 = Ship(10, 11, game.players[0]) s1.halite = 10 s2 = Ship(10, 11, game.players[1]) s2.halite = 10 game.players[0].add_ship(s1) game.players[1].add_ship(s2) assert len(game.players[0].ships) == 2 assert len(game.players[0].ship_array[11][10]) == 1 assert len(game.players[1].ships) == 2 assert len(game.players[1].ship_array[11][10]) == 1 assert game.get_halite(s1.x, s1.y) == 0 game.ship_collisions() assert len(game.players[0].ships) == 1 assert len(game.players[0].ship_array[11][10]) == 0 assert len(game.players[1].ships) == 1 assert len(game.players[1].ship_array[11][10]) == 0 assert game.get_halite(s1.x, s1.y) == 20
def reset(self): #Reset games self.games = [Game(None,None) for _ in range(self.batch_size)] self.game_length = self.games[0].length self.gradient_batch = [tf.zeros((2,self.batch_size,*w.shape),dtype=tf.float32) for w in self.vbm.parameters()] self.vbm.reset()
def test_init(): game = Game(wait_agent, wait_agent) players = game.players ships0 = players[0].ships ship_array0 = players[0].ship_array shipyards0 = players[0].shipyards shipyard_array0 = players[0].shipyard_array ships1 = players[1].ships ship_array1 = players[1].ship_array shipyards1 = players[1].shipyards shipyard_array1 = players[1].shipyard_array assert len(players) == 2 assert len(ships0) == 1 assert len(shipyards0) == 0 assert len(ships1) == 1 assert len(shipyards1) == 0 s0 = ships0[0] assert s0.x == 5 and s0.y == 10 assert ship_array0[10][5] == [s0] s1 = ships1[0] assert s1.x == 15 and s1.y == 10 assert ship_array1[10][15] == [s1]
def main(): config = Config( FPS, WIN_WIDTH, WIN_HEIGHT ) game = Game(config) game.sprite_manager.register([ SpriteConfig('bg', os.path.join(local_dir, "assets/bg.png"), [pygame.transform.scale2x]), SpriteConfig('bird1', os.path.join(local_dir, "assets/bird1.png"), [pygame.transform.scale2x]), SpriteConfig('bird2', os.path.join(local_dir, "assets/bird2.png"), [pygame.transform.scale2x]), SpriteConfig('bird3', os.path.join(local_dir, "assets/bird3.png"), [pygame.transform.scale2x]), SpriteConfig('base', os.path.join(local_dir, "assets/base.png"), [pygame.transform.scale2x]), SpriteConfig('pipe', os.path.join(local_dir, "assets/pipe.png"), [pygame.transform.scale2x]), ]) background = Background(game.sprite_manager.get('bg')) birds = [ Bird(230, 350, game.sprite_manager.get('bird1')), Bird(130, 350, game.sprite_manager.get('bird1')), ] game.state.add([background] + birds) game.start()
def test_get_full_game_representation_strategy(): def game_representation_strategy(game): return Game.get_full_game_representation_strategy(game) snake_length = 3 width = 8 height = 8 input_nodes = width * height + 4 hidden_layer_nodes = [64] output_nodes = 3 number_of_nn_weights = get_number_of_nn_weights(input_nodes, hidden_layer_nodes, output_nodes) weight_lower_threshold = -1 weight_upper_threshold = 1 sample_genotype = SimpleGenotype.get_random_genotype( number_of_nn_weights, weight_lower_threshold, weight_upper_threshold) sample_phenotype = Phenotype(sample_genotype.weights, input_nodes, hidden_layer_nodes, output_nodes) sample_game = Game(width, height, sample_phenotype, 777, game_representation_strategy, snake_length) game_representation = Game.get_full_game_representation_strategy( sample_game) assert len(game_representation) == 8 * 8 + 4 assert game_representation[36] == 1 assert game_representation[44] == 1 assert game_representation[52] == 1
def test_remove_ship(): game = Game(wait_agent, wait_agent) s = game.players[0].ships[0] s.remove() assert len(game.players[0].ships) == 0 assert game.players[0].ship_array[10][5] == []
def test_add_ship(): game = Game(wait_agent, wait_agent) s = Ship(0, 0, game.players[0]) game.players[0].add_ship(s) assert len(game.players[0].ships) == 2 assert game.players[0].ship_array[0][0] != []
def reset(self): #Reset games self.games = [Game(None,None) for _ in range(self.batch_size)] self.game_length = self.games[0].length self.loss_batch = [[0. for i in range(self.batch_size)] for k in range(2)] self.vbm.reset()
def reset(self): #Reset games self.games = [Game(*self.bots[i]) for i in range(self.batch_size)] self.game_length = self.games[0].length self.vbm.reset() self.rewards = np.zeros(self.batch_size)
def load_game(): config = ConfigParser() config.read("./engine/data/config.ini") defaults = config["DEFAULT"] default_properties = {"FPS":defaults.getint("FPS")} window_settings = config["WINDOW SETTINGS"] window_properties = {"size":(window_settings.getint("width"),window_settings.getint("height")), "caption":window_settings.get("title")} return Game(default_properties, window_properties)
def test_halite_regeneration(): game = Game(wait_agent, wait_agent) game.set_halite(0, 0, 100) assert game.get_halite(0, 0) == 100 game.halite_regeneration() assert game.get_halite(0, 0) == 102 assert game.get_halite(0, 1) == 0
def test_shipyard_collision2(): game = Game(wait_agent, wait_agent) sy = Shipyard(5, 10, game.players[1]) game.players[1].add_shipyard(sy) game.shipyard_collisions() assert len(game.players[1].shipyards) == 0 assert game.players[1].shipyard_array[10][5] == 0
def __init__(self, code, game = None): self.data = json.loads(code) self.objects = {} self.events = {} self.battles = {} self.places = {} self.actions = {} if game is None: self.game = Game() else: self.game = game
def test_game_initialization(): def game_representation_strategy(game): return Game.get_full_game_representation_strategy(game) snake_length = 5 width = 32 height = 18 seed = 777 input_nodes = width * height + 4 hidden_layer_nodes = [64] output_nodes = 3 number_of_nn_weights = get_number_of_nn_weights(input_nodes, hidden_layer_nodes, output_nodes) weight_lower_threshold = -1 weight_upper_threshold = 1 sample_genotype = SimpleGenotype.get_random_genotype( number_of_nn_weights, weight_lower_threshold, weight_upper_threshold) sample_phenotype = Phenotype(sample_genotype.weights, input_nodes, hidden_layer_nodes, output_nodes) sample_game = Game(width, height, sample_phenotype, seed, game_representation_strategy, snake_length) assert len(sample_game.snake) == snake_length correct_snake_blocks = [(16, 9), (17, 9), (18, 9), (19, 9), (20, 9)] assert sample_game.snake == correct_snake_blocks assert sample_game.snack_perspective == (21, 9) assert sample_game.snack not in correct_snake_blocks assert 0 <= sample_game.snack[0] <= width assert 0 <= sample_game.snack[1] <= height another_game = Game(width, height, sample_phenotype, seed, game_representation_strategy, snake_length) assert sample_game.snack == another_game.snack
def test_collect(): game = Game(wait_agent, wait_agent) s = game.players[0].ships[0] game.halite[10, 5] = 40 assert game.players[0].halite == 5000 s.collect() assert game.get_halite(5, 10) == 30 assert s.halite == 10 assert game.players[0].halite == 5000
def test_notify_game(self): """ Make sure that when we move/add/remove cards from a zone that the game picks up on it. """ game = Game() game.register([self.zone, self.card1]) expected_transitions = [("add", self.card1.game_id, self.zone.game_id)] expected_transitions2 = [("add", self.card1.game_id, self.zone.game_id), ("remove", self.card1.game_id)] # Test add card self.zone.add_card(self.card1) self.assertEqual(game.get_public_transitions(), expected_transitions) self.zone.remove_card(self.card1) game.flush_transitions() # Test push card self.zone.push(self.card1) self.assertEqual(game.get_public_transitions(), expected_transitions) self.zone.remove_card(self.card1) game.flush_transitions() # Test remove card self.zone.add_card(self.card1) self.zone.remove_card(self.card1) self.assertEqual(game.get_public_transitions(), expected_transitions2) game.flush_transitions() # Test pop card self.zone.push(self.card1) card = self.zone.pop() self.assertEqual(self.card1, card) self.assertEqual(game.get_public_transitions(), expected_transitions2) game.flush_transitions() # Make sure we don't get transitions if there's bad data self.zone.add_card(self.card1) self.zone.add_card(self.card1) self.assertEqual(game.get_public_transitions(), expected_transitions) self.zone.remove_card(self.card1) game.flush_transitions() self.zone.pop() self.zone.remove_card(self.card1) self.assertEqual(game.get_public_transitions(), [])
def test_white_chips(self): """Тестируем постановку белых фишек, и определения белых групп""" game = Game() self.move((450, 450), (6, 4), game, self.color_white) self.move((485, 450), (7, 4), game, self.color_white) self.move((520, 450), (8, 4), game, self.color_white) self.move((275, 275), (1, 9), game, self.color_white) self.move((555, 555), (9, 1), game, self.color_white) expected_white_groups = [[(6, 4), (7, 4), (8, 4)], [(1, 9)], [(9, 1)]] actual_white_groups = game.get_white_groups() self.assertEqual(actual_white_groups, expected_white_groups)
def test_deposit(): game = Game(wait_agent, wait_agent) s = game.players[0].ships[0] s.halite = 50 sy = Shipyard(5, 10, game.players[0]) game.players[0].add_shipyard(sy) assert game.players[0].halite == 5000 s.deposit() assert s.halite == 0 assert game.players[0].halite == 5050
def test_is_mate(self): """Test of is_check() method.""" assert not GameLogic.is_mate(self.game) # Create dummy board board = Board() board.set_piece(Position(0, 1), Piece(PieceType.PAWN, Colour.WHITE)) board.set_piece(Position(1, 1), Piece(PieceType.PAWN, Colour.WHITE)) board.set_piece(Position(0, 0), Piece(PieceType.KING, Colour.WHITE)) board.set_piece(Position(2, 0), Piece(PieceType.ROOK, Colour.BLACK)) history_moves = [ Move(Position(4, 3), Position(4, 4)), Move(Position(3, 6), Position(3, 4)), ] game = Game(board, Colour.WHITE, history_moves) assert GameLogic.is_mate(game)
def __init__(self, title, winWidth): # These class variables will be useful for positioning GUI self.winWidth = winWidth self.winHeight = self.winWidth * 9 // 16 # initialize pygame pg.init() pg.font.init() pg.key.set_repeat(100, 100) pg.display.set_caption(title) self.window = pg.display.set_mode((self.winWidth, self.winHeight)) self.window.fill((51, 51, 51)) self.clock = pg.time.Clock() self.game = Game(self) self.running = True
def test_black_chips(self): """Тестируем постановку черных фишек, и определения черных групп""" game = Game() self.move((555, 310), (9, 8), game, self.color_black) self.move((520, 310), (8, 8), game, self.color_black) self.move((485, 310), (7, 8), game, self.color_black) self.move((450, 310), (6, 8), game, self.color_black) self.move((275, 555), (1, 1), game, self.color_black) self.move((310, 555), (2, 1), game, self.color_black) self.move((345, 555), (3, 1), game, self.color_black) expected_black_groups = [[(9, 8), (8, 8), (7, 8), (6, 8)], [(1, 1), (2, 1), (3, 1)]] actual_black_groups = game.get_black_groups() self.assertEqual(actual_black_groups, expected_black_groups)
def test_defender(self): """Тест защиты бота. Окружаем белую фишку тремя черными. Бот должен увеличить дыхания для данной фишки""" game = Game() self.move((380, 450), (4, 4), game, self.color_bot) self.move((345, 450), (3, 4), game, self.color) self.move((415, 450), (5, 4), game, self.color) self.move((380, 485), (4, 3), game, self.color) bot = SmartBot(game) response = bot.action() game.set_new_move() expected_white_groups = [[(4, 4), (4, 5)]] actual_white_groups = game.get_white_groups() self.assertEqual(actual_white_groups, expected_white_groups)
def test_attack(self): """Тест атаки бота. Заполняем доску четырмя фишками, отдаленных друг от друга. Такие фишки легко закрыть с помощью 16 ходов: 4 дыхания на каждую фишку""" game = Game() self.move((275, 275), (9, 9), game, self.color) self.move((555, 555), (9, 1), game, self.color) self.move((555, 380), (9, 6), game, self.color) self.move((380, 450), (4, 4), game, self.color) bot = SmartBot(game) for i in range(16): response = bot.action() game.set_new_move() expected_black_groups = [] actual_black_groups = game.get_black_groups() self.assertEqual(actual_black_groups, expected_black_groups)
def setUp(self) -> None: """Create dummy game.""" # Create dummy board self.board = Board() self.board.set_piece(Position(4, 0), Pieces.WHITE_KING) self.board.set_piece(Position(0, 0), Pieces.WHITE_ROOK) self.board.set_piece(Position(7, 0), Pieces.WHITE_ROOK) self.board.set_piece(Position(4, 4), Pieces.WHITE_PAWN) self.board.set_piece(Position(4, 1), Pieces.WHITE_BISHOP) self.board.set_piece(Position(3, 4), Pieces.BLACK_PAWN) self.board.set_piece(Position(5, 4), Pieces.BLACK_PAWN) self.board.set_piece(Position(4, 3), Pieces.BLACK_ROOK) self.board.set_piece(Position(2, 2), Pieces.BLACK_PAWN) # Create game self.game = Game(self.board, Colour.WHITE, [Move(Position(3, 6), Position(3, 4))])
def main(): try: import mrx except ImportError: print( "Failed to load Mr. X AI. Make sure it is in this directory and named 'mrx.py'" ) exit(1) try: import detectives except ImportError: print( "Failed to load the detective AI. Make sure it is in this directory and named 'detectives.py'" ) exit(1) the_game = Game(mrx, detectives) win = Window(the_game) win.mainloop()
def test_ship_collision1(): game = Game(wait_agent, wait_agent) s1 = Ship(10, 11, game.players[0]) s1.halite = 10 s2 = Ship(10, 11, game.players[0]) s2.halite = 20 game.players[0].add_ship(s1) game.players[0].add_ship(s2) assert len(game.players[0].ships) == 3 assert len(game.players[0].ship_array[11][10]) == 2 game.ship_collisions() assert len(game.players[0].ships) == 2 assert len(game.players[0].ship_array[11][10]) == 1 assert game.players[0].ship_array[11][10][0] == s1 assert s1.halite == 30
def test_game_max_points_threshold(): def game_representation_strategy(game): return Game.get_full_game_representation_strategy(game) snake_length = 5 width = 32 height = 18 snack_eaten_points = 2 input_nodes = width * height + 4 hidden_layer_nodes = [64] output_nodes = 3 number_of_nn_weights = get_number_of_nn_weights(input_nodes, hidden_layer_nodes, output_nodes) weight_lower_threshold = -1 weight_upper_threshold = 1 max_points_threshold = 200 min_points_threshold = -10 sample_genotype = SimpleGenotype.get_random_genotype( number_of_nn_weights, weight_lower_threshold, weight_upper_threshold) sample_phenotype = Phenotype(sample_genotype.weights, input_nodes, hidden_layer_nodes, output_nodes) sample_game = Game(width, height, sample_phenotype, 777, game_representation_strategy, snake_length, snack_eaten_points, max_points_threshold=max_points_threshold, min_points_threshold=min_points_threshold) sample_game.score = 200 next_game_state = Game.get_next_game(sample_game) assert next_game_state.status == GameStatus.ENDED next_game_state.score = -10 next_game_state = Game.get_next_game(next_game_state) assert next_game_state.status == GameStatus.ENDED
def __init__(self, rewards=None, rounds_number=100, verbose=False): self.action_space = spaces.Discrete(3) self.observation_space = spaces.Tuple( (spaces.Discrete(3), spaces.Discrete(3), spaces.Box(0, 10, shape=(3, )))) self._game = Game(verbose=verbose) self._player1 = Player(self._game) self._player2 = Player(self._game) self._done = False self._rounds_number = rounds_number if rewards is None: rewards = dict(local=1, glob=0) self.rewards = rewards self._game.move(choice(FIELDS), choice(FIELDS)) self.stats = {'games_played': 0}
def test_smart_attack(self): """Тест умной атаки. Белые и Черные фишки имеют достаточно дыханий и стоят рядом (>=3). Это самая частая ситуация в ГО. В данной ситуации нужно атаковать-защищать""" game = Game() self.move((275, 275), (1, 9), game, self.color) self.move((275, 310), (1, 8), game, self.color) self.move((275, 345), (1, 7), game, self.color) self.move((275, 380), (1, 6), game, self.color) self.move((310, 310), (2, 8), game, self.color_bot) bot = SmartBot(game) response = bot.action() game.set_new_move() expected_white_groups = [[(2, 8), (2, 7)]] actual_white_groups = game.get_white_groups() self.assertEqual(actual_white_groups, expected_white_groups)