def init_game_objects(self): self.grid = Grid(GRID_CELL_SIZE, GREY, pygame, self.screen, MAP_SIZE) self.player = Player(self.grid.center_x, self.grid.center_y, GRID_CELL_SIZE, BODY_LENGTH) self.food = Food(GRID_CELL_SIZE, self.grid.rows - 1, self.grid.columns - 1) self.controller = Controller(self.player)
def test_size_1(): grid = Grid(5, 3) assert grid.cols == 5 assert grid.rows == 3 grid = Grid(10, 20) assert grid.cols == 10 assert grid.rows == 20
def test_grid_has_width_height_read_only(self): my_grid = Grid(10, 20) with self.assertRaises(AttributeError, msg='width should be read only.'): my_grid.width = 42 with self.assertRaises(AttributeError, msg='height should be read only.'): my_grid.height = 42
def __init__(self, width: int, height: int, entropy: float, seed: int, population: int): self.width = width self.height = height self.grid = Grid(width, height) self.entropy = entropy self.is_running = True self.seed = seed self.population = population self.rabbits = dict() # type: Dict[int, Rabbit] self.random = numpy.random.default_rng(seed) self.generate_grid() self.create_rabbits()
def test_grid_clear(self): my_grid = Grid(3, 3) self.assertEqual(my_grid, Grid(3, 3)) my_grid.get(0, 0).is_bomb = True my_grid.get(1, 1).state = State.FLAGGED my_grid.get(2, 2).state = State.OPEN # Not default anymore so not equal default. self.assertNotEqual(my_grid, Grid(3, 3)) my_grid.clear() # reset should be equal again. self.assertEqual(my_grid, Grid(3, 3))
def test_get_count_remaining_to_open(self): my_grid = Grid(3, 3) self.assertEqual(my_grid.get_count_remaining_to_open(), 9) my_grid.get(1, 1).is_bomb = True self.assertEqual(my_grid.get_count_remaining_to_open(), 8) my_grid.get(2, 2).state = State.OPEN self.assertEqual(my_grid.get_count_remaining_to_open(), 7) for j in range(3): for i in range(3): my_grid.get(i, j).state = State.OPEN self.assertEqual(my_grid.get_count_remaining_to_open(), 0)
def test_play(game_factory, faker): lobby = Lobby() player1 = Player(faker.pystr(), faker.name()) player2 = Player(faker.pystr(), faker.name()) lobby.register_player(player1) lobby.register_player(player2) char1 = lobby.create_character() char2 = lobby.create_character() lobby.assign_character(player1, char1) lobby.assign_character(player2, char2) game = lobby.start_game(Grid(20, 20)) char1.spawn(game.grid, (1, 1), Direction.DOWN) char2.spawn(game.grid, (1, 2), Direction.UP) with pytest.raises(ActionNotAllowedError): game.action(char1, ActionType.STEP, step=Step.FORWARD) game.action(char1, ActionType.TURN, turn=Turn.LEFT) game.action(char1, ActionType.STEP, step=Step.FORWARD) game.action(char1, ActionType.STEP, step=Step.FORWARD) game.action(char1, ActionType.TURN, turn=Turn.LEFT) assert game.turn_manager.current_character() == char2 assert game.characters[char1.char_id].address == (3, 1) assert game.characters[char1.char_id].direction == Direction.UP
def test_grid_equal(self): my_grid = Grid(3, 3) # width self.assertNotEqual(my_grid, Grid(2, 3)) # height self.assertNotEqual(my_grid, Grid(3, 2)) # check game state. my_grid._state = GameState.WIN self.assertNotEqual(my_grid, Grid(3, 3)) my_grid._state = GameState.PLAYING # back to normal # same size both default self.assertEqual(my_grid, Grid(3, 3)) my_grid.get(0, 0).is_bomb = True # Not default state anymore self.assertNotEqual(my_grid, Grid(3, 3))
def change_difficulty(self): self.grid = Grid(self.current_difficulty['width'], self.current_difficulty['height']) self.grid.seed_grid(self.current_difficulty['bombs']) icon = self.icons['default'] for j in range(self.grid.height): for i in range(self.grid.width): cell = Label(self.grid_frame, width=icon.width(), height=icon.height(), borderwidth=0, image=icon, name=f'cell_{i}_{j}') cell.bind('<Button-1>', partial(self.open, i, j)) cell.bind('<Button-3>', partial(self.toggle_flagged, i, j)) cell.grid(column=i, row=j, ipadx=0, ipady=0, padx=0, pady=0) self.redraw_grid() self.game_over = False self.start_time = datetime.now()
def test_out_of_bounds(): grid = Grid(5, 5) assert not grid.is_out_of_bounds((1, 1)) assert grid.is_out_of_bounds((3, 6)) assert grid.is_out_of_bounds((6, 1)) assert grid.is_out_of_bounds((99, 99)) assert grid.is_out_of_bounds((0, 1)) assert grid.is_out_of_bounds((4, 0))
def make_game(self, traps, size, square_size, frame_limit, rendered, epochs): self.size = size self.grid = Grid(traps, size) self.grid.makeGrid() self.player = Player() self.grid_r = RenderedGrid() self.game = Game(self.grid, self.player, self.grid_r, square_size=square_size, frame_limit=frame_limit, rendered=rendered) self.frame_limit = self.game.frame_limit self.epochs = epochs self.q = Q((self.epochs * frame_limit)) self.q.set_decay_variables(eps_max=1, eps_min=.1) self.q.create_table(size=self.size, num_actions=4) # 4 actions up down left right self.q.set_variables(learning_rate=.1, discount_rate=.97) print(self.q.decay) self.q.up_decay(.0002)
def test_access_grid_in_bounds(self): my_grid = Grid(10, 20) self.assertEqual( my_grid.get(0, 0).state, State.DEFAULT, "Cannot access grid at 0, 0") self.assertEqual( my_grid.get(9, 0).state, State.DEFAULT, "Cannot access grid at 9, 0") self.assertEqual( my_grid.get(0, 19).state, State.DEFAULT, "Cannot access grid at 0, 19") self.assertEqual( my_grid.get(9, 19).state, State.DEFAULT, "Cannot access grid at 9, 19") self.assertEqual( my_grid.get(4, 9).state, State.DEFAULT, "Cannot access grid at 4, 9")
def test_grid_characters(game_factory, faker): grid = Grid(5, 5) assert len(grid.characters) == 0 char = Character(faker.pystr()) grid.add_character(char) assert len(grid.characters) == 1 assert grid.characters[0] == char char2 = Character(faker.pystr()) grid.add_character(char2) assert len(grid.characters) == 2 assert grid.characters[1] == char2
def test_access_grid_out_of_bounds(self): my_grid = Grid(10, 20) with self.assertRaises( ValueError, msg='Should not be able to access grid outside of bounds.'): # Row too small _ = my_grid.get(0, -1) with self.assertRaises( ValueError, msg='Should not be able to access grid outside of bounds.'): # Row too big - 1 _ = my_grid.get(0, 20) with self.assertRaises( ValueError, msg='Should not be able to access grid outside of bounds.'): # Row too big - 2 _ = my_grid.get(0, 21) with self.assertRaises( ValueError, msg='Should not be able to access grid outside of bounds.'): # Column too small _ = my_grid.get(-1, 0) with self.assertRaises( ValueError, msg='Should not be able to access grid outside of bounds.'): # Column too big - 1 _ = my_grid.get(10, 0) with self.assertRaises( ValueError, msg='Should not be able to access grid outside of bounds.'): # Column too big - 2 _ = my_grid.get(11, 0)
def string_to_grid(self, data): """Return a grid that matches the state given by the list of strings in data. ' ' => Unopened grid square not a bomb 'x' => Unopend grid square that is a bomb '/' => Flagged grid square not a bomb '*' => Flagged grid square that is a bomb '_' => Opened grid square that is not a bomb 'X' => Opened grid square that is a bomb """ height = len(data) width = len(data[0]) my_grid = Grid(width, height) for j in range(height): for i in range(width): ch = data[j][i] if ch == ' ': my_grid.get(i, j).is_bomb = False my_grid.get(i, j).state = State.DEFAULT elif ch == 'x': my_grid.get(i, j).is_bomb = True my_grid.get(i, j).state = State.DEFAULT elif ch == '/': my_grid.get(i, j).is_bomb = False my_grid.get(i, j).state = State.FLAGGED elif ch == '*': my_grid.get(i, j).is_bomb = True my_grid.get(i, j).state = State.FLAGGED elif ch == '_': my_grid.get(i, j).is_bomb = False my_grid.get(i, j).state = State.OPEN elif ch == 'X': my_grid.get(i, j).is_bomb = True my_grid.get(i, j).state = State.OPEN return my_grid
def __init__(self, grid_length, square_size): self.grid_length = grid_length self.square_size = square_size self.grid = Grid(grid_length=self.grid_length, square_size=self.square_size)
class GameWindow(object): def __init__(self): self.game_over = False def win(self): if not self.check_high_score(): showinfo('You Win!', 'Congratulations, you won') self.game_over = True def lose(self): showinfo('You lose', 'BOOM! You stepped on a mine.\r\nYou Lost the game.') self.game_over = True def check_high_score(self): connection_string = settings.get_db_path(settings.storage_type) rows = settings.get_high_scores(connection_string, self.current_difficulty['name'], settings.storage['high_score_count']) skip = True dt = datetime.now() - self.start_time seconds = dt.seconds if len(rows) > settings.storage['high_score_count']: for row in rows: if row['seconds'] > seconds: skip = False break else: skip = False if not skip: dialog = EnterHighScore(self.current_difficulty['name'], seconds, self.root) self.root.wait_window(dialog.top) return True else: return False def open(self, col, row, event): if not self.game_over: self.grid.open(col, row) self.redraw_grid() if self.grid.get(col, row).is_bomb: self.lose() elif self.grid.get_count_remaining_to_open() == 0: self.win() def toggle_flagged(self, col, row, event): if not self.game_over: self.grid.toggle_flagged(col, row) self.redraw_cell(col, row) def init_icons(self): file_path = os.path.dirname(os.path.realpath(__file__)) self.icons = {} for i in range(1, 9): self.icons[i] = PhotoImage( file=os.path.join(file_path, f'../res/{i}.ppm')) self.icons['blank'] = PhotoImage( file=os.path.join(file_path, '../res/blank.ppm')) self.icons['bomb'] = PhotoImage( file=os.path.join(file_path, '../res/bomb.ppm')) self.icons['default'] = PhotoImage( file=os.path.join(file_path, '../res/default.ppm')) self.icons['flagged'] = PhotoImage( file=os.path.join(file_path, '../res/flagged.ppm')) self.icons['logo'] = PhotoImage( file=os.path.join(file_path, '../res/logo.gif')) def redraw_grid(self): for j in range(self.grid.height): for i in range(self.grid.width): self.redraw_cell(i, j) def redraw_cell(self, col, row): cell = self.grid_frame.nametowidget(f'cell_{col}_{row}') if self.grid.get(col, row).state == State.FLAGGED: icon = self.icons['flagged'] elif self.grid.get(col, row).state == State.DEFAULT: icon = self.icons['default'] else: bomb_count = self.grid.get_bomb_count(col, row) icon = self.icons['blank'] if self.grid.get(col, row).is_bomb: icon = self.icons['bomb'] elif bomb_count >= 1 and bomb_count <= 8: icon = self.icons[bomb_count] cell.config(image=icon) def show_about(self): dialog = About(self.root) self.root.wait_window(dialog.top) def show_help(self): HelpWindow(self.root) def show_high_scores(self): dialog = HighScore(self.root) self.root.wait_window(dialog.top) def change_difficulty(self): self.grid = Grid(self.current_difficulty['width'], self.current_difficulty['height']) self.grid.seed_grid(self.current_difficulty['bombs']) icon = self.icons['default'] for j in range(self.grid.height): for i in range(self.grid.width): cell = Label(self.grid_frame, width=icon.width(), height=icon.height(), borderwidth=0, image=icon, name=f'cell_{i}_{j}') cell.bind('<Button-1>', partial(self.open, i, j)) cell.bind('<Button-3>', partial(self.toggle_flagged, i, j)) cell.grid(column=i, row=j, ipadx=0, ipady=0, padx=0, pady=0) self.redraw_grid() self.game_over = False self.start_time = datetime.now() def menu_change_difficulty(self): widgets = self.grid_frame.grid_slaves() for widget in widgets: widget.destroy() self.current_difficulty = settings.storage["difficulty"][ self.difficulty_idx.get()] settings.storage["default_difficulty"] = self.current_difficulty[ "name"] self.change_difficulty() def not_yet_implemented(self): showinfo('OK', 'This has not yet been implemented.') def build_gui(self): self.root = Tk() main_menu = Menu(self.root) game_menu = Menu(main_menu, tearoff=0) game_menu.add_command(label='New Game', command=self.menu_change_difficulty) game_menu.add_command(label='High Scores', command=self.show_high_scores) game_menu.add_separator() game_menu.add_command(label='Exit', command=self.root.quit) main_menu.add_cascade(label='Game', menu=game_menu) self.difficulty_idx = IntVar() difficulty_menu = Menu(main_menu, tearoff=0) for idx, item in enumerate(settings.storage['difficulty']): #difficulty_menu.add_radiobutton(label=item['name'], variable=self.current_difficulty, value=item, command=self.not_yet_implemented) difficulty_menu.add_radiobutton( label=item['name'], variable=self.difficulty_idx, value=idx, indicatoron=1, command=self.menu_change_difficulty) if item == self.current_difficulty: self.difficulty_idx.set(idx) print(f'Set Difficulty Index = {idx}') main_menu.add_cascade(label='Difficulty', menu=difficulty_menu) help_menu = Menu(main_menu, tearoff=0) help_menu.add_command(label='Index', command=self.show_help) help_menu.add_separator() help_menu.add_command(label='About', command=self.show_about) main_menu.add_cascade(label='Help', menu=help_menu) self.root.config(menu=main_menu) self.root.title('Minesweeper') self.init_icons() self.grid_frame = Frame() self.grid_frame.pack() self.change_difficulty() file_path = os.path.dirname(os.path.realpath(__file__)) icon = PhotoImage(file=os.path.join(file_path, '../res/logo.gif')) self.root.icon = icon # don't garbage collect me please. #self.icons['logo'] = icon self.root.tk.call('wm', 'iconphoto', self.root._w, self.icons['logo']) def run_game(self, default_difficulty): self.current_difficulty = reduce( lambda x, y: x if x['name'] == settings.storage['default_difficulty'] else y, settings.storage['difficulty'], settings.storage['difficulty'][0]) self.build_gui() self.game_over = False self.root.mainloop()
def test_toggle_flagged(self): my_grid = Grid(3, 3) # should not change if state != playing my_grid._state = GameState.LOSE my_grid.toggle_flagged(0, 0) self.assertEqual(my_grid.get(0, 0).state, State.DEFAULT) # should change if playing my_grid._state = GameState.PLAYING my_grid.toggle_flagged(0, 0) self.assertEqual(my_grid.get(0, 0).state, State.FLAGGED) my_grid.toggle_flagged(0, 0) self.assertEqual(my_grid.get(0, 0).state, State.DEFAULT) # Didn't mix up row and column did we? my_grid._state = GameState.PLAYING my_grid.toggle_flagged(1, 0) self.assertEqual(my_grid.get(1, 0).state, State.FLAGGED) my_grid.toggle_flagged(1, 0) self.assertEqual(my_grid.get(1, 0).state, State.DEFAULT) # should not change if open. my_grid.get(0, 0).state = State.OPEN my_grid.toggle_flagged(0, 0) self.assertEqual(my_grid.get(0, 0).state, State.OPEN) # should throw an error if out of bounds. with self.assertRaises( ValueError, msg='Should not be able to access grid outside of bounds.'): my_grid.toggle_flagged(-1, 0) my_grid.toggle_flagged(0, -1) my_grid.toggle_flagged(3, 0) my_grid.toggle_flagged(0, 3) my_grid.toggle_flagged(3, 3)
def test_get_count_bombs(self): my_grid = Grid(3, 3) self.assertEqual(my_grid.get_count_bombs(), 0) my_grid.get(0, 0).is_bomb = True self.assertEqual(my_grid.get_count_bombs(), 1) my_grid.get(2, 2).is_bomb = True self.assertEqual(my_grid.get_count_bombs(), 2) for j in range(3): for i in range(3): my_grid.get(i, j).is_bomb = True self.assertEqual(my_grid.get_count_bombs(), 9) my_grid.get(1, 1).is_bomb = False self.assertEqual(my_grid.get_count_bombs(), 8)
class Game: def __init__(self, width: int, height: int, entropy: float, seed: int, population: int): self.width = width self.height = height self.grid = Grid(width, height) self.entropy = entropy self.is_running = True self.seed = seed self.population = population self.rabbits = dict() # type: Dict[int, Rabbit] self.random = numpy.random.default_rng(seed) self.generate_grid() self.create_rabbits() def generate_grid(self): ground = OpenSimplex(self.seed) food = OpenSimplex(self.seed * 3) ratio = self.height / self.width max_x = self.width / 8 max_y = self.height / (8 * ratio) water = self.entropy - 0.05 grass = self.entropy + 0.15 for pos, cell in self.grid.cells.items(): rng = (ground.noise2d(pos.x / max_x, pos.y / max_y) + 1) rng2 = (food.noise2d(pos.x / max_x, pos.y / max_y) + 1) if rng < water: cell.celltype = Cell.CellType.WATER elif rng < grass: cell.celltype = Cell.CellType.FLOOR else: cell.celltype = Cell.CellType.FLOOR cell.is_grass = True # if rng > grass + 0.15 and rng2 > 1.50: # cell.is_food = True @staticmethod def run_rabbits(rabbit: Rabbit): rabbit.run() # print(rabbit.pos, rabbit.command) return rabbit def run(self): # with Pool(4) as p: # workers = [p.apply_async(Game.run_rabbits, args=(r,)) # for r in self.rabbits.values()] # rabs = [worker.get() for worker in workers] for r in self.rabbits.values(): r.run() free_cells = self.grid.get_free_cells() move_rabs = list() # type: List[Rabbit] for r in self.rabbits.values(): if r.command.is_moving(): free_cells.append(r.pos) move_rabs.append(r) while True: move_set = set() # type: Set[Coord] conflict = set() # type: Set[Coord] for r in move_rabs: if r.command.is_moving(): pos = r.check_move() if pos in move_set: move_set.remove(pos) conflict.add(pos) free_cells.remove(pos) elif pos not in conflict and pos in free_cells: move_set.add(pos) else: r.command = Rabbit.Action.NOTHING if len(conflict) == 0: break for r in self.rabbits.values(): if r.command.is_moving(): self.grid.get(r.pos).has_rabbit = False r.move() self.grid.get(r.pos).has_rabbit = True def create_rabbits(self): free_cells = self.grid.get_free_cells() list_pos = self.random.choice(free_cells, self.population, replace=False) seeds = self.random.integers(0, self.population, (self.population, )) for rabbit_id, pos in enumerate(list_pos): rabbit = Rabbit(rabbit_id, pos, seeds[rabbit_id]) self.rabbits[rabbit_id] = rabbit self.grid.get(pos).has_rabbit = True
from game.spell import MoveSpell, HarvestSpell, DropSpell from game.enchantment import SimpleEnchantment import game.resources as resources window = pyglet.window.Window(visible=False, resizable=True) window.set_caption('Legend Of Wizard') window.set_visible() pyglet.resource.path = ['resources'] pyglet.resource.reindex() pyglet.resource.add_font('04b_30.ttf') pyglet.resource.add_font('04b_03.ttf') grid_offset = Position(500, 0) grid = Grid() e0 = SimpleEnchantment("IA stupide") enchantments = [e0] entities = [] spells = [MoveSpell, HarvestSpell, DropSpell] class GameState: def __init__(self): self.enchantment_boxes = [] self.spell_boxes = [] self.wood_count = 0
def test_seed_grid(self): my_grid = Grid(10, 20) my_grid.seed_grid(10) self.assertEqual(my_grid.get_count_bombs(), 10) with self.assertRaises(TypeError, msg='Num_Bombs needs to be an integer.'): my_grid.seed_grid(1.1) my_grid.seed_grid(True) my_grid.seed_grid('stuff') my_grid.seed_grid([1, 2, 3]) with self.assertRaises(ValueError, msg='Too many bombs.'): my_grid.seed_grid(300) with self.assertRaises(ValueError, msg='Too many bombs.'): my_grid.seed_grid(200) my_grid.seed_grid(199) self.assertEqual(my_grid.get_count_bombs(), 199) my_grid.seed_grid(0) self.assertEqual(my_grid.get_count_bombs(), 0)
class Train: def __init__(self): self.frame_limit = None self.size = None self.grid = None self.player = None self.grid_r = None self.game = None self.info = None self.q = None def make_game(self, traps, size, square_size, frame_limit, rendered, epochs): self.size = size self.grid = Grid(traps, size) self.grid.makeGrid() self.player = Player() self.grid_r = RenderedGrid() self.game = Game(self.grid, self.player, self.grid_r, square_size=square_size, frame_limit=frame_limit, rendered=rendered) self.frame_limit = self.game.frame_limit self.epochs = epochs self.q = Q((self.epochs * frame_limit)) self.q.set_decay_variables(eps_max=1, eps_min=.1) self.q.create_table(size=self.size, num_actions=4) # 4 actions up down left right self.q.set_variables(learning_rate=.1, discount_rate=.97) print(self.q.decay) self.q.up_decay(.0002) def run_game(self, render_delay=0): steps = 0 prev_q_state = 0 for epoch in range(0, self.epochs): self.game.re_init() print(epoch) print(self.q.table) while True: if self.game.done or self.game.frame == self.frame_limit: #bug for some reason the game class doesnt stop it at frame limit all the time so i added it here break # get action from the Q class... for now it's random since class isn't finished action = self.q.get_action(prev_q_state) print(self.q.eps_val) self.game.action_state(action) state, reward, done, player_position, x, y = self.game.get_info( ) q_state = x * y #this is where the q value will be updated according to the next state self.q.update_table(prev_state=prev_q_state, state=q_state, action=action, reward=reward) prev_q_state = q_state self.q.eps_decay(steps) steps += 1 time.sleep(render_delay) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit()
def create_grid(self, cols=5, rows=5, obstacles=(), walls=()): self.grid = Grid(cols, rows, list(obstacles), list(walls)) return self.grid
def test_grid_can_be_created(self): my_grid = Grid(10, 20) self.assertEqual(type(my_grid), Grid, 'Could not create variable of type Grid.')
def test_open(self): my_grid = Grid(3, 3) # Don't open if the game isn't playing my_grid._state = GameState.WIN my_grid.open(0, 0) expected = [' ', ' ', ' '] self.assertEqual(expected, self.grid_to_string(my_grid)) my_grid._state = GameState.PLAYING # Empty grid will expose everything on click. my_grid.open(1, 1) expected = ['___', '___', '___'] self.assertEqual(expected, self.grid_to_string(my_grid)) # Empty grid with a bomb in the middle. my_grid.clear() expected = [' ', ' X ', ' '] my_grid.get(1, 1).is_bomb = True my_grid.open(1, 1) self.assertEqual(expected, self.grid_to_string(my_grid)) # New game with two bombs nothing opened my_grid.clear() expected = [' x', ' ', 'x '] my_grid.get(2, 0).is_bomb = True my_grid.get(0, 2).is_bomb = True self.assertEqual(expected, self.grid_to_string(my_grid)) # Same grid open at 1, 0 my_grid.open(1, 0) expected = [' 1x', ' ', 'x '] self.assertEqual(expected, self.grid_to_string(my_grid)) # Same grid open at 1, 0 my_grid.open(0, 0) expected = ['_1x', '1 ', 'x '] self.assertEqual(expected, self.grid_to_string(my_grid)) my_grid = Grid(4, 4) my_grid.get(0, 1).is_bomb = True my_grid.get(1, 3).is_bomb = True my_grid.open(2, 1) expected = [' 1__', 'x1__', ' 1_', ' x1_'] self.assertEqual(expected, self.grid_to_string(my_grid)) my_grid = Grid(3, 4) my_grid.get(1, 1).is_bomb = True my_grid.get(2, 2).is_bomb = True my_grid.open(0, 3) expected = [' ', ' x ', '1 x', '_1 '] self.assertEqual(expected, self.grid_to_string(my_grid))
batch_size = 128 # 256 - number of replay memory experiences considered gamma = 0.9 # 0.999 - discount factor in Bellman eqn eps_start = 1 # 1 - exploration rate eps_end = 0.01 # 0.01 eps_decay = 0.01 # 0.001 target_update = 10 # 10 - frequency for updating target network memory_size = 100000 # 100000 - capacity of replay memory lr = 0.001 # 0.001 - learning rate num_episodes = 1000 # 1000 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if __name__ == "__main__": strategy = EpsilonGreedyStrategy(eps_start, eps_end, eps_decay) agent = Agent(strategy, 4, device) memory = ReplayMemory(memory_size) grid = Grid(window_width, window_height, square_side) policy_net = DQN(grid.size_x, grid.size_y).to(device) target_net = DQN(grid.size_x, grid.size_y).to(device) target_net.load_state_dict(policy_net.state_dict()) target_net.eval() optimizer = optim.Adam(params=policy_net.parameters(), lr=lr) episode_scores = [] for episode in range(num_episodes): grid = Grid(window_width, window_height, square_side) game = MyGame(window_width, window_height, square_side, grid) current_state = game.pipe.get_state() score = 0 i = 0 while not game.pipe.done: i += 1
def test_grid_keeps_parameters(self): my_grid = Grid(10, 20) self.assertEqual(my_grid.width, 10, 'Grid did not save passed in width.') self.assertEqual(my_grid.height, 20, 'Grid did not save passed in height.')
def __init__(self): grid = Grid(24, 20, obstacles=OBSTACLES, walls=WALLS) self.char_faces = ['char1', 'char2', 'char3', 'char4'] self.lobby = Lobby() self.game = None
def test_grid_has_game_state_read_only(self): my_grid = Grid(3, 3) with self.assertRaises(AttributeError, msg='state should be read only'): my_grid.state = GameState.WIN