def load(self, saveFile): """ Loads the game from a save file, creates an empty game if the save is None """ save = json.load(open(saveFile, "r")) self.map = Map(save['map']) self.player = Player(save['player'])
def tests_move_on_walkable_objects_in_bounds_should_return_true(self, isinstance_mock): self.map.hero = self.hero isinstance_mock.return_value = True empty_cell = self.EmptyCellMock.return_value with self.subTest('move up'): self.map.grid = [[empty_cell], [empty_cell]] self.hero.row, self.hero.col = 1, 0 self.assertTrue(Map.move_hero(self.map, 'up')) with self.subTest('move down'): self.map.grid = [[empty_cell], [empty_cell]] self.hero.row, self.hero.col = 0, 0 self.assertTrue(Map.move_hero(self.map, 'down')) with self.subTest('move left'): self.map.grid = [[empty_cell, empty_cell]] self.hero.row, self.hero.col = 0, 1 self.assertTrue(Map.move_hero(self.map, 'left')) with self.subTest('move right'): self.map.grid = [[empty_cell, empty_cell]] self.hero.row, self.hero.col = 0, 0 self.assertTrue(Map.move_hero(self.map, 'right'))
def new_game(): # Initialize console & area lt.console_set_custom_font(FONT, lt.FONT_TYPE_GRAYSCALE | lt.FONT_LAYOUT_TCOD) lt.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'Armament', False) lt.sys_set_fps(LIMIT_FPS) global messages, log messages = list() log = lt.console_new(LOG_WIDTH, LOG_HEIGHT) message(' ') # Ensures log is rendered. global panel panel = lt.console_new(PANEL_WIDTH, SCREEN_HEIGHT) lt.console_set_default_background(panel, lt.darkest_blue) lt.console_rect(panel, 0, 0, PANEL_WIDTH, SCREEN_HEIGHT, True, lt.BKGND_SET) lt.console_print_frame(panel, 1, 1, PANEL_WIDTH-2, SCREEN_HEIGHT-2, False) lt.console_blit(panel, 0, 0, PANEL_WIDTH, SCREEN_HEIGHT, 0, 0, 0) while not lt.console_is_window_closed(): global area area = Map(MAP_WIDTH, MAP_HEIGHT) # I'd rather not global this, but I can't figure out a way to make collision detection play nicely without it. # Create player entity player = Player() area.update_fov(player.being.col, player.being.row, player.being.facing) entities = list() entities.append(player) # Enter game if main(area, entities) == "exit": return True
def test_move_should_update_hero_coordinated(self, isinstance_mock): self.map.hero = self.hero empty_cell = self.EmptyCellMock.return_value self.hero.row, self.hero.col = 0, 0 self.map.grid = [[empty_cell, empty_cell]] Map.move_hero(self.map, 'right') self.assertEqual((self.hero.row, self.hero.col), (0, 1))
def test_get_rba_array(): maze = Map('classic') g = Game(maze=maze, screen=pg.display.set_mode(maze.get_map_sizes()), sounds_active=False, state_active=False) arr = g.get_rba_array() assert type(arr) is np.ndarray assert arr.shape == (456, 552, 3)
def test_move_should_trigger_enter_event_on_targer_cell(self, isinstance_mock): self.map.hero = self.hero self.hero.row, self.hero.col = 0, 0 empty_cell = self.EmptyCellMock.return_value self.map.grid = [[empty_cell, empty_cell]] Map.move_hero(self.map, 'right') empty_cell.trigger_enter_event.assert_called_with(self.hero)
def __init__(self): # Initialize surface, backgorund self.surface = pygame.display.set_mode(RESOLUTION, 0, 32) pygame.display.set_caption('Oil Spill Simulation') self.background = pygame.Surface(RESOLUTION) self.background.fill(LIGHTBLUE) # Initialize manager for buttons self.manager = pygame_gui.UIManager(RESOLUTION) # Initialize Menu buttons self.startButton = pygame_gui.elements.UIButton( relative_rect=pygame.Rect(POSITION_STARTBUTTON, SIZE_STARTBUTTON), text='START', manager=self.manager) self.resetButton = pygame_gui.elements.UIButton( relative_rect=pygame.Rect(POSITION_RESETBUTTON, SIZE_RESETBUTTON), text='RESET', manager=self.manager) self.documentationButton = pygame_gui.elements.UIButton( relative_rect=pygame.Rect(POSITION_DOCUMENTATIONBUTTON, SIZE_DOCUMENTATIONBUTTON), text='Documentation', manager=self.manager) # Initlialize labels self.titleLablel = pygame_gui.elements.UIButton( relative_rect=pygame.Rect(POSITION_TITLELABEL, SIZE_TITLELABEL), text='DEEPWATER HORIZON OIL SPILL SIMULATION', manager=self.manager, tool_tip_text= "This is a simulation of DeepWater Horizon Oil Spill by Zuzanna Smiech and Mikolaj Ogarek." ) self.timeLabel = pygame_gui.elements.UILabel(relative_rect=pygame.Rect( POSITION_TIMELABEL, SIZE_TIMELABEL), text='Time[h]: 0.0', manager=self.manager) # Initialize map self.map = Map() # Initialize oil points list hardcoded values 100t of oil, start coords self.oil_point_list = DiscretizedOil(TOTAL_WEIGHT, NUMBER_OF_OIL_POINTS, (X_START, Y_START)) # at the begining all oil poitns are in start cell self.map.simulationArray[X_START][ Y_START].oil_points = self.oil_point_list.oil_points_array[:] #.copy() self.total_time = 0 self.total_oil_mass = TOTAL_WEIGHT self.nc = netCDF4.Dataset("src/daily_currents.nc") self.update_wind_and_currents(0) self.step = 0
def test_move_col_out_of_bounds_should_return_false(self): self.hero.row, self.hero.col = 0, 0 self.map.hero = self.hero self.map.grid = [[self.EmptyCellMock.return_value]] with self.subTest('move left'): self.assertFalse(Map.move_hero(self.map, 'left')) with self.subTest('move right'): self.assertFalse(Map.move_hero(self.map, 'right'))
def test_move_row_out_of_bounds_should_return_false(self): self.map.grid = [[self.EmptyCellMock.return_value]] self.map.hero = self.hero self.hero.row, self.hero.col = 0, 0 with self.subTest('move up'): self.assertFalse(Map.move_hero(self.map, 'up')) with self.subTest('move down'): self.assertFalse(Map.move_hero(self.map, 'down'))
def __init__(self): bit_map = assets.generate_map() super().__init__(bit_map.shape[1] * settings.BLOCK_SIZE, bit_map.shape[0] * settings.BLOCK_SIZE + settings.BLOCK_SIZE * 3, "PAC-MAN", resizable=False) self.map = Map(bit_map) self.event_loop = pyglet.app.EventLoop() pyglet.clock.schedule_interval(self.update, 1 / 120.0)
def A_star_test(path): i_start = 1 j_start = 1 i_goal = 13 j_goal = 28 width, height, cell = read_map_from_moving_ai_file(path) task_map = Map() task_map.set_grid_cells(width, height, cell) print(A_star(task_map, i_start, j_start, i_goal, j_goal, [])) print(A_star(task_map, i_start, j_start, i_goal, j_goal, [((2, 1), 1)])) print(A_star(task_map, i_start, j_start, i_goal, j_goal, [((1, 1), 0)]))
def __init__(self, network): """ Set up display and game map. Arguments: network {Network} -- Connection to server """ pygame.init() # Connection to the server self.network = network self.player_num = self.network.get_player_num() print("You are player", self.player_num) # Set up display window pygame.display.set_caption("A Game of Shapes - Player " + str(self.player_num)) screen_res = (WINDOW_WIDTH, WINDOW_HEIGHT) self.screen = pygame.display.set_mode(screen_res) # Set up font pygame.font.init() self.game_font = pygame.font.Font(GAME_FONT, 40) # Set up gameplay map self.map = Map(self.screen, self.player_num, self.network) # Represents the state of game # Modified by server and sent to clients self.gamestate = self.network.get_gamestate() is_turn = self.gamestate.is_players_turn(self.player_num) # Effects of turn that are sent across network self.turn = { "move": None, "attack": None, "phase": NOT_TURN, "result": None } # Let the starting player begin moving units if is_turn: self.turn["phase"] = SELECT_UNIT_TO_MOVE # Clock tracks time from beginning of game self.clock = pygame.time.Clock() # Keep track of user's cursor. Updates every frame self.mouse_position = pygame.mouse.get_pos() # Show waiting screen until other player connects self.waiting_screen() # Start the game self.game_loop()
def test_spawn_coords_of_hero_should_be_correct(self, next_mock): self.SpawnMock.return_value.row = 0 self.SpawnMock.return_value.col = 0 next_mock.return_value = self.SpawnMock.return_value test_map = Mock() test_map.grid = [[self.SpawnMock.return_value]] hero = self.HeroMock() Map.spawn(test_map, hero) self.assertEqual((hero.row, hero.col), (0, 0))
def test_spawn_should_make_spawn_cell_empty_cell(self, next_mock): self.SpawnMock.return_value.row = 0 self.SpawnMock.return_value.col = 0 next_mock.return_value = self.SpawnMock.return_value test_map = Mock() test_map.grid = [[self.SpawnMock.return_value]] Map.spawn(test_map, self.HeroMock()) self.EmptyCellMock.assert_called_with(row=0, col=0)
def test_spawn_should_trigger_enter_event_on_empty_cell(self, next_mock): self.SpawnMock.return_value.row = 0 self.SpawnMock.return_value.col = 0 next_mock.return_value = self.SpawnMock.return_value test_map = Mock() test_map.grid = [[self.SpawnMock.return_value]] hero = self.HeroMock() Map.spawn(test_map, hero) self.EmptyCellMock.return_value.trigger_enter_event.assert_called_with(hero)
class Window(pyglet.window.Window): def __init__(self, map_file, config_file): super().__init__(resizable=True, caption='Tourism Simulation', visible=False) self.set_minimum_size(640, 480) self.set_maximum_size(2260, 3540) self.frame_rate = 1 / 60.0 # Target frame-rate, usually can't keep up self.icon1 = pyglet.image.load('./graphics/Icon1.png') self.icon2 = pyglet.image.load('./graphics/Icon2.png') self.set_icon(self.icon1, self.icon2) self.map = Map(self.width, self.height, map_file) self.set_visible(True) self.x = 800 self.y = -800 self.simulation = Simulation(2260, 3540, self.width, self.height, config_file) def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): if (buttons & mouse.LEFT) or (buttons & mouse.MIDDLE): self.x = self.x + dx self.y = self.y + dy if self.x > 1120: self.x = 1120 pass if self.x < self.width - 1120: self.x = self.width - 1120 pass if self.y > 1760: self.y = 1760 pass pass if self.y < self.height - 1760: self.y = self.height - 1760 pass def update(self, dt): self.simulation.update(dt) def on_draw(self): self.clear() self.map.draw(self.width, self.height, self.x, self.y) self.simulation.draw(self.x, self.y, self.width, self.height)
def test_map_init(): maze = Map('classic') assert maze.map_matrix.shape == (22, 19) assert maze.map_matrix.min() == 10 assert maze.map_matrix.max() == 50 assert maze.map_matrix.dtype == int64 assert maze.map_matrix[16][9] == 40
def _create_test_map(self): self.map = Map(TEST_MAP) for row, tiles in enumerate(self.map.get_data): for column, tile in enumerate(tiles): if tile == "1": t = StaticTile(Vector2(column, row), self.image_manager.get_image("grass")) self.nature_tiles.add(t) self.visible_sprites.add(t, layer=0) if tile == "0": t = StaticTile(Vector2(column, row), self.image_manager.get_image("water")) self.nature_tiles.add(t) self.visible_sprites.add(t, layer=0) if tile == "8": t = StaticTile(Vector2(column, row), self.image_manager.get_image("grass")) self.nature_tiles.add(t) self.visible_sprites.add(t, layer=0) t = MovableTile(Vector2(column, row), self.image_manager.get_image("farmer")) self.player1_units.add(t) self.visible_sprites.add(t, layer=2) if tile == "9": # TODO: Remove double sprite on one coordinate t = StaticTile(Vector2(column, row), self.image_manager.get_image("grass")) self.nature_tiles.add(t) self.visible_sprites.add(t, layer=0) t = Tile(Vector2(column, row), self.image_manager.get_image("village")) self.player1_villages.add(t) self.visible_sprites.add(t, layer=1)
def compare_q_learning_sarsa(list_maps): param = [("max first", max_first, 'default'), ("Explore : softmax", explore, 'softmax'), ('Explore-exploitation : softmax', explore_exploitation, 'softmax')] for name_map, number_episodes in list_maps: game_map = Map(name_map) for p in param: _, _, _, _, q_values_q, number_q = q_learning( game_map=game_map, training_episode=number_episodes, epsilon_greedy=p[1], strategy=p[2]) _, _, _, _, q_values_sarsa, number_sarsa = sarsa( game_map=game_map, training_episode=number_episodes, epsilon_greedy=p[1], strategy=p[2]) plt.clf() fig = plt.figure() plt.plot(range(1, len(q_values_q) + 1), q_values_q, color='green', label='Q-Learning') plt.plot(range(1, len(q_values_sarsa) + 1), q_values_sarsa, color='red', label="SARSA") plt.title("Evolution q values : " + p[0] + " Map : " + name_map.split('/')[-1].split('.')[0]) plt.xlabel("Number episodes") plt.ylabel("Mean Q Values") plt.legend() plt.savefig('plot/Q_Learning_vs_SARSA_Value_' + p[0] + '_' + name_map.split('/')[-1].split('.')[0] + '.png') plt.clf() fig = plt.figure() plt.plot(range(1, len(number_q) + 1), number_q, color='yellow', label='Q-Learning') plt.plot(range(1, len(number_sarsa) + 1), number_sarsa, color='blue', label='SARSA') plt.title("Len Q " + p[0] + " Map : " + name_map.split('/')[-1].split('.')[0]) plt.xlabel("Number episodes") plt.ylabel("Len Q") plt.legend() plt.savefig('plot/Q_Learning_vs_SARSA_Len_' + p[0] + '_' + name_map.split('/')[-1].split('.')[0] + '.png')
def test_move_on_non_walkable_object_should_return_false(self, isinstance_mock): self.map.hero = self.hero empty_cell, wall_cell = self.EmptyCellMock.return_value, self.WallMock.return_value self.map.grid = [ [wall_cell, wall_cell, wall_cell], [wall_cell, empty_cell, wall_cell], [wall_cell, wall_cell, wall_cell] ] self.hero.row, self.hero.col = 1, 1 isinstance_mock.return_value = False self.assertFalse(Map.move_hero(self.map, 'up')) self.assertFalse(Map.move_hero(self.map, 'down')) self.assertFalse(Map.move_hero(self.map, 'left')) self.assertFalse(Map.move_hero(self.map, 'right'))
def __init__(self, screen, player, room_id=0): MapState.__init__(self, screen, player) # TODO init room settings from room_data with room_id self.set_map(Map(CONFIG['room_data'][room_id]['bg_file'])) test2 = UnitEntity(0) test2.set_unit_group(2) test1 = UnitEntity(0) test1.set_unit_group(2) test3 = UnitEntity(0) test3.set_unit_group(2) test4 = UnitEntity(0) test4.set_unit_group(2) self.add_entity_to_map(test2, 6, 6) self.add_entity_to_map(test1, 5, 5) self.add_entity_to_map(test3, 12, 12) self.add_entity_to_map(test4, 14, 14) #self.p1.bind_entity(test2) self.set_follow_camera(test1) #self.i_state = InventoryState(self.screen, self.p1, self) self._force_draw()
def test_spawn_should_return_false_when_gen_is_exhausted(self, next_mock): hero = self.HeroMock() next_mock.side_effect = StopIteration test_map = Mock() self.assertFalse(Map.spawn(test_map, hero))
def test_init_home(): p = Pacman() maze = Map('classic') home_x, home_y = maze.get_player_home() p.init_home(home_x, home_y) assert p.home_x == 9 assert p.home_y == 16 assert p.x == p.home_x * TILE_SIZE assert p.y == p.home_y * TILE_SIZE assert p.nearest_col == p.home_x assert p.nearest_row == p.home_y p.init_home(0, 0) assert p.home_x == 9 assert p.home_y == 16 assert p.x == p.home_x * TILE_SIZE assert p.y == p.home_y * TILE_SIZE assert p.nearest_col == p.home_x assert p.nearest_row == p.home_y
def __init__(self, levelname: str, world: esper.World): super().__init__() self.scene = self self.map: Map = Map(settings.BASE_DIR + "\\" + levelname) self.camera: Camera = Camera() self.entities = [] self.player = world.create_entity() self.world = world self.player: Player = Player(world, player_name="ShuzZzle") self.player.create((Velocity(velx=10, vely=10), Position(x=0, y=0)))
def __init__(self, map_file, config_file): super().__init__(resizable=True, caption='Tourism Simulation', visible=False) self.set_minimum_size(640, 480) self.set_maximum_size(2260, 3540) self.frame_rate = 1 / 60.0 # Target frame-rate, usually can't keep up self.icon1 = pyglet.image.load('./graphics/Icon1.png') self.icon2 = pyglet.image.load('./graphics/Icon2.png') self.set_icon(self.icon1, self.icon2) self.map = Map(self.width, self.height, map_file) self.set_visible(True) self.x = 800 self.y = -800 self.simulation = Simulation(2260, 3540, self.width, self.height, config_file)
def test_update_ghosts_positions(): maze = Map('classic') ghosts = [Ghost(i, (255, 0, 0, 255)) for i in range(4)] def get_random_allow_position() -> Tuple[int, int]: res = np.where(maze.state_matrix == 1) rnd = np.random.randint(0, high=len(res[0])) return res[1][rnd], res[0][rnd] rand_pos = [] for ghost in ghosts: x, y = get_random_allow_position() rand_pos.append((x, y)) ghost.nearest_col = x ghost.nearest_row = y maze.update_ghosts_position(ghosts) for x, y in rand_pos: assert maze.state_matrix[y][x] == -1
def test_init_cell_instance_correctess(self): # black magic input = ['S.#', 'GET'] expected = [ [self.SpawnMock, self.EmptyCellMock, self.WallMock], [self.GatewayMock, self.EmptyCellMock, self.EmptyCellMock]] Map(input) for row, mocks in zip(range(2), expected): for col, ctor_mock in zip(range(3), mocks): all_kwargs = [kwargs for args, kwargs in ctor_mock.call_args_list] self.assertIn({'row': row, 'col': col}, all_kwargs)
def compare_max_first_random(list_maps): for name_map, number_episodes in list_maps: game_map = Map(name_map) _, _, _, _, q_values_max, number_visited_max = q_learning( game_map=game_map, epsilon_greedy=max_first, training_episode=number_episodes) _, _, _, _, q_values_random, number_visited_random = q_learning( game_map=game_map, epsilon_greedy=random_choice_action, training_episode=number_episodes) plt.clf() fig = plt.figure() plt.plot(range(1, len(q_values_max) + 1), q_values_max, color='yellow', label='Max Fist') plt.plot(range(1, len(q_values_random) + 1), q_values_random, color='blue', label="Random") plt.title("Evolution q values, Map : " + name_map.split('/')[-1].split('.')[0]) plt.xlabel("Number episodes") plt.ylabel("Mean Q Values") plt.legend() plt.savefig('plot/Evolution_q_values_Map_' + name_map.split('/')[-1].split('.')[0] + '.png') plt.clf() fig = plt.figure() plt.plot(range(1, len(number_visited_max) + 1), number_visited_max, color='yellow', label='Max Fist') plt.plot(range(1, len(number_visited_random) + 1), number_visited_random, color='blue', label='Random') plt.title("Len Q, Map : " + name_map.split('/')[-1].split('.')[0]) plt.xlabel("Number episodes") plt.ylabel("Len Q") plt.legend() plt.savefig('plot/Len_Q_Map_' + name_map.split('/')[-1].split('.')[0] + '.png')
def __init__(self, layout: str, enable_render=True, state_active=False, player_lives: int = 3): """ PacmanEnv constructor :param layout: the layout of the game :param frame_to_skip: the frame to skip during training :param enable_render: enabling the display of the game screen :param state_active: enabling the display of the state matrix """ self.layout = layout self.state_active = state_active self.enable_render = enable_render if enable_render: pg.init() self.action_space = spaces.Discrete(Action.__len__()) self.maze = Map(layout) self.width, self.height = self.maze.get_map_sizes() self.game = Game( maze=self.maze, screen=Controller.get_screen(state_active, self.width, self.height) if enable_render else None, sounds_active=False, state_active=state_active, agent=None) self.timer = 0 self.reinit_game = False self.player_lives = player_lives self.observation_space = spaces.Space( shape=self.get_screen_rgb_array().shape, dtype=int) self.seed()
def gen_tileset_map(self, tileset_id): filename = CONFIG['tile_configs']['tilesets'][tileset_id]['filename'] rm.load_tileset_by_id(tileset_id) testmap = Map() testmap.empty_map() x = 0 y = 0 count = 0 for tileconfig in rm.tilesets[filename]: if y >= CONFIG['tool_tileviewer_max_col_size']: x += 1 y = 0 tile = Tile(0) tile.tileset_id = tileset_id tile.tile_id = count if x not in testmap.tiles: testmap.tiles.append([]) testmap.tiles[x].append(tile) y += 1 count += 1 return testmap
def __init__(self, width: int, height: int): """ :param width: width in pixels :param height: height in pixels """ # Global app window self.root = Tk() self.root.geometry("400x600") # labels and size self.width = width self.height = height self.main_label = Label(self.root) self.main_label.pack(pady=80) self.frame = Frame(self.root) self.scrollbar = Scrollbar(self.frame, orient=VERTICAL) self.listbox = Listbox(self.frame, width=50, yscrollcommand=self.scrollbar.set, selectmode=MULTIPLE) self.vehicles = Entry(self.root) self.vehicles.pack() self.vehicles.insert(0, "Number of vehicles:") # buttons self.open_from_file_button = Button( self.root, text="OPEN FROM FILE", command=self.open_from_file_on_click_listener) self.open_from_file_button.pack(pady=10) self.show_button = Button(self.root, text="SHOW MAP", command=self.show_on_click_listener) self.show_button.pack(pady=10) self.find_routes_button = Button( self.root, text="FIND ROUTES", command=self.find_routes_on_click_listener) self.find_routes_button.pack(pady=10) # data frame self.cities_df = pd.DataFrame() self.connections = [] # optimizer parameters self.number_of_vehicles = 1 # map object self.map = Map()
else: initial_coords = get_hme(sock) initial_x = initial_coords[0] initial_y = initial_coords[1] print("Received initial coords! \n") # RECEIVING 1ST MAP (MAP) commande4 = get_command(sock) if commande4 != "MAP": raise ValueError("Erreur protocole: attendu MAP (cote client)") else: map_infos = get_map(sock) print("Received first map! : ", map_infos, "\n") # Initialize map with initial coords and map new_map = Map(vampires=[], werewolves=[], humans=[], size_x=m, size_y=n) new_map.initialize_map(map_infos) team = new_map.find_grp(initial_x, initial_y) # Initialize brain = Brain(new_map, team[1]) while True: commande5 = get_command(sock) if commande5 not in ["UPD", "END"]: raise ValueError("Erreur protocole: mauvaise commande reçue.") elif commande5 == "END": break