def _ReadOverworldData(self) -> None: self.overworld_caves = [] for cave_type in Range.VALID_CAVE_TYPES: cave_num = cave_type - 0x10 if cave_type == CaveType.ARMOS_ITEM_VIRTUAL_CAVE: self.overworld_caves.append( Cave([0x3F, Item.POWER_BRACELET, 0x7F, 0x00, 0x00, 0x00])) elif cave_type == CaveType.COAST_ITEM_VIRTUAL_CAVE: self.overworld_caves.append( Cave([0x3F, Item.HEART_CONTAINER, 0x7F, 0x00, 0x00, 0x00])) else: assert cave_type in Range.VALID_CAVE_TYPES # Not needed? cave_data: List[int] = [] for position_num in range(0, 3): cave_data.append(self.overworld_raw_data[ self._GetOverworldCaveDataIndex(cave_type, position_num, is_second_byte=False)]) for position_num in range(0, 3): cave_data.append(self.overworld_raw_data[ self._GetOverworldCaveDataIndex(cave_type, position_num, is_second_byte=True)]) self.overworld_caves.append(Cave(cave_data)) assert len( self.overworld_caves ) == 22 # 0-19 are actual caves, 20-21 are for the armos/coast
def init_game(self): self.cave = Cave(self.screen, CAVE_HEIGHT) self.heli = HelicopterSprite(HELICOPTER_IMG, (250, SCREEN_HEIGHT / 2)) self.heli_group = pygame.sprite.RenderPlain(self.heli) self.score = 0 self.frame_counter = 0 self.has_crashed = False
def create_caves(self): """ Create all the caves for the game. """ random.shuffle(CAVE_NAMES) caves = [Cave(name) for name in CAVE_NAMES] for connections in CAVE_CONNECTIONS: start = connections[0] for destination in connections[1:]: caves[start].add_connection(caves[destination]) self.caves = caves self.current_cave = caves[0]
def run(): data = load_data("Day15.txt") cave = Cave(data, 3) cave.show() outcome, elf_deaths = cave.run() print(f"The outcome is {outcome}") # part 2 elf_ap = 4 elf_deaths = 1 while elf_deaths: cave = Cave(data, elf_ap) outcome, elf_deaths = cave.run() print(f"The elf ap of {elf_ap} leaves {elf_deaths} elves dead") elf_ap += 1 print(f"The outcome is {outcome}")
def updateWorld(self, caveRow, caveCol, isGold, isHole, isWind, isBones, allowDirects, monstersCount, arrowsCount, legsCount): self.__isKilledMonster = (monstersCount < self.__monstersCount) self.__monstersCount = monstersCount caveId = self.getCaveIdFromPos(caveRow, caveCol) cave = self.__cavesDict.get(caveId) # добавить пещеру в словарь если её там нет if (cave == None): cave = Cave(self, caveRow, caveCol, isGold, isHole, isWind, isBones, allowDirects) self.__cavesDict[caveId] = cave # установить пещеру как текущую self.__currCave = cave # обновить стоимость всех известных пещер for caveId in self.__cavesDict.keys(): self.__cavesDict[caveId].updateCost(monstersCount, arrowsCount, legsCount) # print('World was updated') # !!! TEST !!! return
def find_wanted_passages_and_cave(self): if len(self.current_plan) < 2: return [], [] wanted_passages = [] wanted_cave = [] index = 1 next_action = self.current_plan[0] if self.will_move_block_passage_entrance(next_action): row, col = next_action.required_free explored_entrances = [(row, col)] passages_to_explore = [(p, (row, col)) for p in LEVEL.map_of_passages[row][col]] while len(passages_to_explore) > 0: passage, enter = passages_to_explore.pop() next_on_path, new_index = self.is_passage_next_on_path( passage, index) #Do I want to enter one of them? -> add to list if next_on_path: wanted_passages.append((passage, enter)) if new_index is not None: index = new_index + 1 entrance = self.current_plan[new_index].required_free if entrance not in explored_entrances: new_passages = [(p, entrance) for p in LEVEL.map_of_passages[ entrance[0]][entrance[1]] if p != passage] explored_entrances.append(entrance) passages_to_explore = passages_to_explore + new_passages if len(wanted_passages) > 0: last_passage, enter = wanted_passages[-1] for entrance in last_passage.entrances: if entrance == enter: continue exit_location = entrance else: exit_location = next_action.required_free caves_to_explore = LEVEL.map_of_caves[exit_location[0]][ exit_location[1]] if caves_to_explore is not None: for cave in caves_to_explore: if self.is_cave_next_on_path(cave, index)[0]: #log("Agent {} thinks cave {} is the next on the path. index: {}, action self.current_plan[index]: {}".format(self.id_, cave, index, self.current_plan[index]), "TEST", False) wanted_cave.append((cave, exit_location)) if len(wanted_cave) == 0 and len(wanted_passages) > 0: #check if the wanted goal is in the last passage last_passage, entrance = wanted_passages[-1] location = None #get goal location if isinstance(self.intentions, Contract): if isinstance(self.intentions.performative, CfpMoveSpecificBoxTo): box = self.intentions.performative.box location = self.intentions.performative.location else: raise NotImplementedError("Unrecognized performative") elif isinstance(self.intentions, AgentGoal): location = (self.intentions.row, self.intentions.col) elif self.intentions is not None and not isinstance( self.intentions, Request): box, goal = self.intentions location = (goal.row, goal.col) #Check if goal in passage if location is not None and location in last_passage.locations: #create artificial cave artificial_cave = Cave(None, location) artificial_cave.entrance = entrance end = entrance for pos in last_passage.locations: if pos == location: break if is_adjacent(pos, end): end = pos artificial_cave.locations.insert(1, end) if pos in LEVEL.goals_by_pos: artificial_cave.goals.append( LEVEL.goals_by_pos[pos]) artificial_cave.update_status(self.beliefs) wanted_cave = [(artificial_cave, entrance)] wanted_passages = wanted_passages[:-1] return wanted_passages, wanted_cave
if __name__ == "__main__": # args parser = argparse.ArgumentParser() parser.add_argument("-m", "--model_path") parser.add_argument("-s", "--save", dest="save", action="store_true") parser.set_defaults(save=False) args = parser.parse_args() print('----------------------') print('space: moving up') print('q: exit') print('----------------------') # environmet, agent env = Cave(time_limit=False) # variables past_time = 0 state_t_1, reward_t, terminal = env.observe() action_t = 0 # animate fig = plt.figure(figsize=(env.screen_n_rows / 10, env.screen_n_cols / 10)) fig.canvas.set_window_title("{}".format(env.name)) cid = fig.canvas.mpl_connect('key_press_event', onkey) cid = fig.canvas.mpl_connect('key_release_event', offkey) img = plt.imshow(state_t_1, interpolation="none", cmap="gray") ani = animation.FuncAnimation(fig, animate, init_func=init,
class HelicopterGame(object): """ Wrapper class used for initializing Helicopter games and controlling state """ def __init__(self, agent=None): pygame.init() self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), DOUBLEBUF) self.clock = pygame.time.Clock() self.agent = agent self.init_game() if agent is None: self.has_started = False self.run_game() else: self.has_started = True def process_event(self, event): """ Process user interaction """ if event.type == pygame.QUIT: pygame.quit() elif event.type == MOUSEBUTTONDOWN: self.heli.throttle = True elif event.type == MOUSEBUTTONUP: self.heli.throttle = False if not hasattr(event, "key"): return elif event.key == K_SPACE: if self.has_crashed: self.init_game() self.has_started = True elif event.key == K_UP: BG_COLOR = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255)) def init_game(self): self.cave = Cave(self.screen, CAVE_HEIGHT) self.heli = HelicopterSprite(HELICOPTER_IMG, (250, SCREEN_HEIGHT / 2)) self.heli_group = pygame.sprite.RenderPlain(self.heli) self.score = 0 self.frame_counter = 0 self.has_crashed = False def update_state(self): """ Update game state and redraw screen """ if self.frame_counter % OBSTACLE_SPAWN_RATE == 0: midpoint = self.cave.sample_midpoint() self.cave.spawn_obstacle(midpoint[1] + OBSTACLE_HEIGHT / 2, midpoint[1] + CAVE_HEIGHT - OBSTACLE_HEIGHT / 2) self.heli_group.update(self.frame_counter) self.cave.update() if self.cave.check_collision(self.heli_group): self.has_crashed = True self.heli_group.draw(self.screen) self.score += 1 self.frame_counter += 1 self.display_score() def display_score(self): score_font = pygame.font.SysFont("arial", 20) score_surface = score_font.render("Score: {}".format(self.score), True, WHITE) score_rect = score_surface.get_rect() if self.has_crashed: score_rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) else: score_rect.topleft = (30, SCREEN_HEIGHT - 50) self.screen.blit(score_surface, score_rect) def display_start_menu(self): title_font = pygame.font.SysFont("arial", 30) title_surface = title_font.render("Helicopter", True, WHITE) title_rect = title_surface.get_rect() title_rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 3) self.screen.blit(title_surface, title_rect) def display_game_over(self): msg_font = pygame.font.SysFont("arial", 30) msg_surface = msg_font.render("Game Over!", True, WHITE) msg_rect = msg_surface.get_rect() msg_rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 3) self.screen.blit(msg_surface, msg_rect) self.display_score() def get_state_vector(self): velocity = self.heli.speed heli_x, heli_y = self.heli.position cave_y = self.cave.get_ceiling_at(heli_y) obs_pos, ceil_pos = self.cave.next_obstacle_coords(heli_x) obs_pos2, ceil_pos2 = self.cave.next_obstacle_coords(obs_pos[0]) W = float(self.screen.get_width()) H = float(self.screen.get_height()) state_vector = np.zeros((9, 1), dtype=np.float32) state_vector[0] = (heli_y - cave_y) * 1.0 / CAVE_HEIGHT state_vector[1] = cave_y / H * 2 state_vector[2] = velocity / 10.0 state_vector[3] = obs_pos[0] / (W * 1.5) state_vector[4] = obs_pos[1] / H state_vector[5] = ceil_pos[1] / H * 2 state_vector[6] = obs_pos2[0] / (W * 1.5) state_vector[7] = obs_pos2[1] / H state_vector[8] = ceil_pos2[1] / H * 2 return state_vector.T def get_current_screen(self, H=84, W=84): rgb = pygame.surfarray.array3d(self.screen) rgb = resize(rgb, (W, H)) rgb = rgb.astype(np.float32) return rgb[:, :, 0] * 0.2126 + rgb[:, :, 1] * 0.7152 + rgb[:, :, 2] * 0.0722 def get_current_state(self): velocity = self.heli.speed heli_x, heli_y = self.heli.position cave_y = self.cave.get_ceiling_at(heli_y) obs_pos, ceil_pos = self.cave.next_obstacle_coords(heli_x) H = self.screen.get_height() velocity_i = 0 if velocity > 0 else 1 heli_y_k = int(10.0 * (heli_y - cave_y) / float(CAVE_HEIGHT)) cave_y_k = int(10.0 * float(cave_y) / H) next_cave_y_k = int(10.0 * float(ceil_pos[1]) / H) next_obs_y_k = int(10.0 * (obs_pos[1] - ceil_pos[1]) / float(CAVE_HEIGHT)) state_index = 0 state_index += heli_y_k state_index += 10 * cave_y_k state_index += 100 * next_cave_y_k state_index += 1000 * next_obs_y_k if velocity > 0: state_index * 2 return state_index def get_current_reward(self): if self.has_crashed: return -1 else: return min(self.score / 100.0, 1.0) def run_game(self): if self.agent is not None: self.agent.start_new_game() prev_screen = None while True: delta_ms = self.clock.tick(FRAME_RATE) if self.agent is None: for event in pygame.event.get(): self.process_event(event) else: if type(self.agent) is ChainerAgent: state = self.get_state_vector() elif type(self.agent) is ConvQAgent: if prev_screen is None: state = self.get_current_screen(W=84, H=84) else: state = prev_screen else: state = self.get_current_state() agent_action = self.agent.act(state) if agent_action is not None: self.heli.throttle = agent_action self.screen.fill(BG_COLOR) if not self.has_started: self.display_start_menu() elif self.has_crashed: self.display_game_over() else: self.update_state() if self.agent is not None: action = int(self.heli.throttle) reward = self.get_current_reward() if type(self.agent) is ChainerAgent: new_state = self.get_state_vector() elif type(self.agent) is ConvQAgent: new_state = self.get_current_screen(W=84, H=84) prev_screen = new_state else: new_state = self.get_current_state() # self.agent.accept_reward(state, action, reward, new_state, self.has_crashed) if self.has_crashed: return self.score pygame.display.flip()
def main(): intro() global PK print ("Hello there! Welcome to the world of Bokémon! My name is Dr. Cottonwood! People call me the Bokémon Professor! This world is inhabited by creatures called Bokémon! For some people, Bokémon are pets. Others use them for fights. Myself...I study Bokémon as a profession.\n") time.sleep(2) art.bokesquare() art.cottonwood() time.sleep(4) PK = input ("What is your name?\n") print("Nice to meet you,",PK,'\n') time.sleep(1) print("What an interesting name") time.sleep(3) print("Im so sorry to jump right into it but your parents have disapeared\nthey were working at their laboratory at the dig site right out of town") time.sleep(4) print(" you see,") time.sleep(3) print("I tried to warn them that it was a bad idea to be working that late at night but they insisted") time.sleep(3) print("I am going to send you out on a journey to defeat the leader at the collesseum in this region, the Kantob region") time.sleep(3) print("You will catch bokémon and train them to battle the collisseum leader to get the badge") time.sleep(3) print("once you get a colosseum badge I will feel confident in sending you to the dig site to look for you parents") time.sleep(3) print("I have 3 bokémon and you can choose one of these bokémon as your companion") print('you will also run into other bokémon on your journey.\n sadly you can only carry 3 bokémon at a time') time.sleep(3) print("so you will send the rest back to me") time.sleep(3) print('take these 20 bokesquares. they can be used to capture wild bokémon') time.sleep(3) #choosing starter bokemon print('The time has come') time.sleep(4) print('Which bokémon do you want') print('you will type the corresponding letter ') print('CHOOSE YOUR BOKEMON') starter = input('(A): Kennen, the electic mouse bokémon\n(B): Belldolpine, the E-dolphin time bokémon\n(C): Meister beast, The monkey bokémon\n') while starter not in ("A","a","B","b","C","c"): starter = input('please input: A,B, or C\n') if starter == 'A' or starter == 'a': boke1 = Kennen() sboke = 'Kennen' elif starter == 'B' or starter == 'b': boke1 = Belldolpine() sboke = 'Belldolpine' elif starter == 'C' or starter == 'c': boke1 = MeisterBeast() sboke = 'MeisterBeast' print('I see you chose',sboke,'\n well then I will see you on your journey') #go to Paintbrush Town time.sleep(3) print(chr(27) + "[2J") journey1() time.sleep(3) PaintbrushTown.work() ColosseumFight.fight() print(chr(27) + "[2J") journey2() Cave.work() time.sleep(5) print(chr(27) + "[2J") art.bokesquare()
# Main Menu Aspects menu_bg = Background(0, 0, screen_height, screen_width, 'resources/menu/menu_bg.png') start_button = Button(330, 270, 60, 240, 'start_button', 'resources/menu/') exit_button = Button(330, 360, 60, 240, 'exit_button', 'resources/menu/') def draw_menu(): window.blit(menu_bg.image, (menu_bg.x, menu_bg.y)) window.blit(start_button.image, (start_button.x, start_button.y)) window.blit(exit_button.image, (exit_button.x, exit_button.y)) pygame.display.update() # Generate inital cave cave = Cave(screen_height // 15, screen_width // 15) bg = Background(0, 0, screen_height, screen_width) # Character Creation # Class definition in entity.py entities = [] user = Player(450, 350, 13, 30, 100, 5, 3) entities += [user] # Main Draw function def redraw(): cells_to_redraw = [] for entity in entities: cells_to_redraw += entity.get_cells(cave) for cell in cells_to_redraw:
class PlayGame: _game_over, _game_win = False, False _game_cave = [] _game_adventurer = Adventurer() _user_input = "" _RAND_MAX = 20 _RAND_MIN = 1 def __init__(self): self._game_cave = Cave() def start_game(self): print(" WELCOME TO HUNT THE WUMPUS\n" + "YOU MUST FIND THE WUMPUS IN HIS DARK AND DANGEROUS LAIR!\n" + "YOU ARE EQUIPPED WITH A BOW AND FIVE ARROWS.") while not self._game_over: self._game_turn() if self._game_win: print("YOU SLEW THE FOUL WUMPUS!!!!") def _game_turn(self): current_room = self._game_cave.visit_room(self._game_adventurer.current_room) print("YOU ARE IN ROOM : "+str(self._game_adventurer.current_room)) if current_room[0]: self._encountered_wumpus() elif current_room[1]: self._encountered_pit() elif current_room[2]: self._encountered_bats() if not self._game_over: self._check_connected_rooms() self._user_input = input(": ") self._interpret_command() def _interpret_command(self): goto_schemes = ("GO", "GOTO", "GO TO", "G") shoot_schemes = ("SHOOT", "S") look_schemes = ("LOOK", "L") quit_schemes = ("QUIT", "Q") if self._user_input.upper().startswith(goto_schemes): room = re.search("\d+", self._user_input).group() self._go_to_room(int(room)) elif self._user_input.upper().startswith(shoot_schemes): room = re.search("\d+", self._user_input).group() self._shoot_arrow(int(room)) elif self._user_input.upper().startswith(look_schemes): self._look() elif self._user_input.upper().startswith(quit_schemes): print("Goodbye....") self._game_over = True else: print("SORRY I DIDN'T UNDERSTAND THAT") def _go_to_room(self, room): if room in self._game_cave.cave_map[self._game_adventurer.current_room]: self._game_adventurer.set_current_room(room) else: print("YOU CANT GET THERE FROM HERE") def _shoot_arrow(self, room): print("TWWANG YOU LOOSE AN ARROW FROM YOUR MIGHTY YEW BOW!!") if room in self._game_cave.cave_map[self._game_adventurer.current_room]: if self._game_cave.visit_room(room)[0]: print("YOUR SWIFT ARROW PUNCTURES THE HEART OF THE STINKING BEAST!") self._game_win = True self._game_over = True return print("CRUNCH THE ARROW BREAKS AGAINST THE STONE WALL OF THE CAVE!") self._arrow_missed() def _look(self): rooms = self._game_cave.cave_map[self._game_adventurer.current_room] print("YOU SEE PATHS TO ROOMS "+str(rooms[0])+", "+str(rooms[1])+" and "+str(rooms[2])) def _check_connected_rooms(self): rooms = self._game_cave.cave_map[self._game_adventurer.current_room] for e in rooms: if self._game_cave.visit_room(e)[0]: print("YOU SMELL THE FOUL STENCH OF THE WUMPUS!") if self._game_cave.visit_room(e)[1]: print("YOU HEAR A RUSH OF WIND WHISTLING FROM A NEARBY CAVE!") if self._game_cave.visit_room(e)[2]: print("YOU HEAR A LEATHERY FLAPPING NOISE!") def _arrow_missed(self): if randint(0, 3) != 3: print("You woke the Wumpus!") self._game_cave.wumpus_move() def _encountered_wumpus(self): print("YOU ARE DEVOURED BY THE EVIL WUMPUS") self._game_over = True def _encountered_bats(self): print("OH NO YOU WERE GRABBED BY THE SUPER BATS") self._game_adventurer.current_room = randint(self._RAND_MIN, self._RAND_MAX) def _encountered_pit(self): print("YOU STUMBLE DOWN A BOTTOMLESS PIT!!") self._game_over = True
def __init__(self): self._game_cave = Cave()