def setup(self): self.dungeon = Dungeon("map.txt") self.hero = Hero("Geralt", "white wolf", 150, 150, 5) self.hero.equip(Weapon("Sword", 30)) self.hero.learn(Spell("wolf's attack", 20, 20, 2)) self.dungeon.spawn(self.hero) self.command = None
def lets_play(): command_list = [{ 'w': 'up', 's': 'down', 'a': 'left', 'd': 'right' }, 'f', 'spawn', 'status', 'u', 'p'] print('\nLets play a game!\n ') name = input('Write a name for your hero: ') title = input('How is your hero known as: ') h = Hero(name=name, title=title, health=100, mana=100, mana_regeneration_rate=2) name = input('Give a name to your weapon: ') w = Weapon(name=name, damage=20) h.equip(w) print('\n{} will fight with {} to save The Princess!\n'.format( h.known_as(), w.name)) input('Press enter to start the game!') map = Dungeon("level1.txt") map.spawn(h) map.print_map() input_data = input( "\nType w/s/a/d to move your hero up/down/left/right\ , f for fight, spawn for spawn, status to show hero's status, u for update spell/weapon or e for exitd: " ) while (input_data != 'e'): if input_data in command_list[0].keys(): map.move_hero(command_list[0][input_data]) map.print_map() elif input_data == command_list[1]: map.hero_attack() map.print_map() elif input_data == command_list[2]: map.spawn(h) map.print_map() elif input_data == command_list[3]: print('\n', h, h.weapon, h.spell) elif input_data == command_list[4]: which = input('Type spell/weapon: ') print( 'Are you sure. You have {} and the update is 20. Type y or n:' .format(map.hero.money)) result = input() if result == 'y': map.hero.update(which) else: print('Update not successful') elif input_data == 'm': print("\nType w/s/a/d to move your hero up/down/left/right\ , f for fight, spawn for spawn, status to show hero's status, u for update spell/weapon or e for exit" ) else: print('Comming soon!') print('Type m to see the curret command menu.') print('\n') input_data = input('Command: ')
def main(): hero_name = input("Enter hero's name: ") hero_title = input("Enter hero's title: ") hero = Hero(hero_name, hero_title, 150, 150, 5) hero.equip(Weapon("Sword", 30)) hero.learn(Spell("KillALL", 35, 30, 3)) dungeon = Dungeon("map.txt", "basic_loot_list_example.json") dungeon.spawn(hero) dict_commands = {"mu": "up", "md": "down", "ml": "left", "mr": "right", "au": "up", "ad": "down", "al": "left", "ar": "right", "h": "help"} dict_commands_move = {"mu": "up", "md": "down", "ml": "left", "mr": "right"} dict_commands_attack = {"au": "up", "ad": "down", "al": "left", "ar": "right"} index_of_hero = [1, 1] print_commands() while not dungeon.end_of_game: dungeon.print_map() print() player_input = "" while player_input not in dict_commands.keys(): player_input = str(input(">>> ")) if player_input == "h": print_commands() if player_input in dict_commands_move.keys(): dungeon.move_hero(dict_commands_move[player_input]) if player_input in dict_commands_attack.keys(): dungeon.hero_atack(dict_commands_attack[player_input]) if dungeon.end_of_game: break
def create_dungeons(world): for dungeon_info in dungeon_table: name = dungeon_info['name'] hint = dungeon_info['hint'] if 'hint' in dungeon_info else name if world.settings.logic_rules == 'glitched': if not world.dungeon_mq[name]: dungeon_json = os.path.join(data_path('Glitched World'), name + '.json') else: dungeon_json = os.path.join(data_path('Glitched World'), name + ' MQ.json') else: if not world.dungeon_mq[name]: dungeon_json = os.path.join(data_path('World'), name + '.json') else: dungeon_json = os.path.join(data_path('World'), name + ' MQ.json') world.load_regions_from_json(dungeon_json) boss_keys = ItemFactory(['Boss Key (%s)' % name] * dungeon_info['boss_key']) if not world.dungeon_mq[dungeon_info['name']]: small_keys = ItemFactory(['Small Key (%s)' % name] * dungeon_info['small_key']) else: small_keys = ItemFactory(['Small Key (%s)' % name] * dungeon_info['small_key_mq']) dungeon_items = ItemFactory( ['Map (%s)' % name, 'Compass (%s)' % name] * dungeon_info['dungeon_item']) world.dungeons.append( Dungeon(world, name, hint, boss_keys, small_keys, dungeon_items))
def create_dungeons(world): for dungeon_info in dungeon_table: name = dungeon_info['name'] hint = dungeon_info['hint'] if 'hint' in dungeon_info else name font_color = dungeon_info['font_color'] if 'font_color' in dungeon_info else 'White' if world.settings.logic_rules == 'glitched': if not world.dungeon_mq[name]: dungeon_json = os.path.join(data_path('Glitched World'), name + '.json') else: dungeon_json = os.path.join(data_path('Glitched World'), name + ' MQ.json') else: if not world.dungeon_mq[name]: dungeon_json = os.path.join(data_path('World'), name + '.json') else: dungeon_json = os.path.join(data_path('World'), name + ' MQ.json') world.load_regions_from_json(dungeon_json) boss_keys = ItemFactory(['Boss Key (%s)' % name] * dungeon_info['boss_key']) if not world.dungeon_mq[dungeon_info['name']]: small_keys = ItemFactory(['Small Key (%s)' % name] * dungeon_info['small_key']) else: small_keys = ItemFactory(['Small Key (%s)' % name] * dungeon_info['small_key_mq']) dungeon_items = ItemFactory(['Map (%s)' % name, 'Compass (%s)' % name] * dungeon_info['dungeon_item']) if world.settings.shuffle_mapcompass in ['any_dungeon', 'overworld']: for item in dungeon_items: item.priority = True world.dungeons.append(Dungeon(world, name, hint, font_color, boss_keys, small_keys, dungeon_items))
def make_dungeon_from_dict(self, dungeon_dict): self.dungeon = Dungeon(dungeon_dict['name'], dungeon_dict['theme'], dungeon_dict['next'], dungeon_dict['x'], dungeon_dict['y'], dungeon_dict['roomstr'], dungeon_dict['d_id']) self.enable_room_icons(True) self.view_dungeon_grid()
def test_move_hero_(self): d = Dungeon('map.txt', 'basic_loot_list_example.json') d.spawn(Hero("nz", "nz", 200, 120, 2)) d.move_hero("right") d.move_hero("down") d.move_hero("right") d.move_hero("down") self.assertEqual(d.hero_place, [2, 1])
def test_check_for_enemy_down(self): d = Dungeon('map.txt', 'basic_loot_list_example.json') d.spawn(Hero("nz", "nz", 200, 120, 2)) d.hero.learn(Spell("idk", 20, 20, 2)) d.hero_place = [0, 5] d.change_map("H") result = d.check_for_enemy("down") self.assertEqual(result, 2)
def main(): c_bid = 0.1 random.seed(0) dungeon = Dungeon(30, 40) random.seed() simulator1 = RoomGraphSimulator(dungeon) simulator2 = CellMoveSimulator({}, dungeon) simulator3 = Simulator2({}, dungeon) destination_map = learn_room_move(simulator1) print(destination_map) q = np.random.random((5, 13, 12, 5, 5, 5, 5, 5)) eps = np.full((5, 13, 12, 5, 5, 5, 5), 0.99) max_step = 400000 file = open('profit_sharing_log_0_.csv', "w") for step in range(max_step): state = simulator2.info() sum_reward = 0 turn = 0 rules = [] while not state['isEnd']: s = state_tuple(state) action = int(select_action(q[s], eps[s])) eps[s] *= 0.99 rules.append((*s, action)) reward = simulator2.action({ 'action': action, 'nextRoomId': destination_map[state['roomId']] }) if reward == -1: sum_reward += reward else: sum_reward += reward state = simulator2.info() turn += 1 for rule in rules: q[rule] = q[rule] + c_bid * (sum_reward - q[rule]) simulator2.reset() print(step, '/', max_step, 'reward:', sum_reward, 'turn:', turn) file.write(f'{step},{sum_reward},{turn}\n') if step % (max_step // 10) == 0: test(simulator3, q) file.close() np.save('q_table1_0_.npy', destination_map) np.save('q_table2_0_.npy', q) for _ in range(15): test(simulator3, q) time.sleep(1)
def setUpClass(cls): """ This class method setup the dungeon generator once and it can be used in the test classes below. Otherwise it generates every time and because there is a random generation in the dungeon generator and it saves time. """ cls.nrows = 20 cls.ncols = 20 cls.dungeon = Dungeon(cls.nrows, cls.ncols) cls.dungeon.dungeon_generator()
def create_dungeon_cb(self, widget, data): name = data['name'].get_text() theme = data['theme'].get_active() #.get_active_text() next = find_key(data['d_list'], data['next_dungeon'].get_active_text()) width = data['width'].get_value_as_int() height = data['height'].get_value_as_int() self.dungeon = Dungeon(name, theme, next, width, height) self.enable_room_icons(True) self.view_dungeon_grid()
def __load_dungeon(self, id): self.position = (-1, -1) self.playerFacing = NORTH d = self.game_engine.get_object('dungeon') self.dungeon_id = id d.remove_from_engine() self.game_engine.remove_object('dungeon') self.game_engine.add_object('dungeon', Dungeon(self.dungeon_id)) self.remove_keys()
def enterAction(self): super(InitializationMode, self).enterAction() try: del (self.game.dungeon) except: pass self.game.dungeon = Dungeon(self.game.screen.get_width(), self.game.screen.get_height(), 10, 10) pass
def level_readers(path): print("----Welcome to Dungeons and Pythons!!!----") print("Move your hero with a, w, s, d.") print("Press X to exit.") name = input("Enter name for your hero: ") title = input("Enter your hero's nickname: ") h = Hero(name, title, health=100, mana=100, mana_regeneration_rate=2) w = Weapon(name='The Axe of Destiny', damage=10) h.equip(w) #there is no hero without weapon. Start game with some levels = os.listdir(path) levels.sort() cls() print_logo() sleep(3) #wait for 3 seconds for idx, lvl in enumerate(levels): map = Dungeon(path + '/' + lvl, h, idx + 1) map.spawn() key = '' exited = False legit_keys = {'a', 'w', 's', 'd', 'x'} while map.hero.is_alive(): #does every move print('level {}'.format(idx + 1)) map.print_map() print("||||HEALTH: {}||||".format(map.hero.get_health())) print("||||MANA: {}||||\n".format(map.hero.get_mana())) key = getch() cls() key = key.lower() if key in legit_keys: if key == 'a': map.move_hero('left') if key == 'd': map.move_hero('right') if key == 's': map.move_hero('down') if key == 'w': map.move_hero('up') if key == 'x': exited = True break else: print("Invalid command") if map.endpoint == (map.hero_position_X, map.hero_position_Y): break #we're done here, go to next level if exited: break if map.hero.is_alive() and not exited: print("Congratulations! You win!") else: print("Bye!")
def test_entrance_location_is_positive(self): """ This tests whether the entrance location is positive """ try: dungeon = Dungeon(6, 6) temp4 = dungeon.entrance_generator() self.assertGreaterEqual(temp4, [0, 0], "entrance location is positive") except ValueError as value_error: self.assertEqual(True, True)
def __init__(self, row=30, column=40): self.dungeon = Dungeon(row, column) self.is_end = False self.friend_agent = None # 保護解除したマップ self.map = self.dungeon.floor_map.copy() self.map[self.map == CellInfo.PROTECTED] = CellInfo.ROOM self.map[self.map == CellInfo.ENEMY] = CellInfo.ROOM self.enemy_list = [] self.reset()
def setUp(self): path = open("path.txt", "w") self.dung_map = """S.##...... #.##..### #.###.###. #.....### ###.####S""" path.write(self.dung_map) path.close() self.dungeon = Dungeon("path.txt") self.bron = Hero("Bron", 100, "DragonSlayer") self.orc = Orc("orc", 90, 1.4) self.bron.equip_weapon(Weapon("Mighty Axe", 25, 0.2)) self.orc.equip_weapon(Weapon("basher", 16, 0.75))
def new(self): """Game class method to start a new game. """ # start a new game # initialise sprite groups self.all_sprites = pygame.sprite.LayeredUpdates() self.walls = pygame.sprite.LayeredUpdates() self.gui = pygame.sprite.LayeredUpdates() self.enemies = pygame.sprite.LayeredUpdates() self.item_drops = pygame.sprite.LayeredUpdates() # instantiate dungeon self.dungeon = Dungeon(self, cfg.DUNGEON_SIZE) if self.loaded: self.dungeon.tileset = self.saveGame.data['tileset'] else: self.dungeon.create() self.WSign = self.imageLoader.WarnSign self.WSign2 = self.imageLoader.WarnSign2 self.inventory = Inventory(self) # spawn the player in the middle of the room self.player = Player(self, (cfg.WIDTH // 2, cfg.TILESIZE * 12)) self.currentpistol = Pistol(self, self.player) self.currentmachine = MachineGun(self, self.player) if self.pistolpick == True: self.player.itemA = self.currentpistol elif self.machinegunpick == True: self.player.itemA = self.currentmachine # load settings if self.loaded: self.loadSavefile() # spawn the new objects (invisible) self.prev_room = self.dungeon.current_room_index self.transitRoom(self, self.dungeon) # create a background image from the tileset for the current room self.background = self.tileRoom(self, self.imageLoader.tileset, self.dungeon.current_room_index) self.run()
def reset(self): with open(self.filename) as file: line = file.readline() dimL = line.split(" ") n = int(dimL[0]) m = int(dimL[1]) self.Dungeon = Dungeon(n, m) self.X = self.Dungeon.size_x self.Y = self.Dungeon.size_y self.start_position = self.Dungeon.start_position for i in range(n): line = file.readline() ElemL = line.split(" ") for j in range(m): elmnt = ElemL[j][:1] self.add_element(elmnt, i, j) self.Adventurer = Adventurer(self)
def __init__(self, param, dungeon=None): self.random_enemy = param.get('randomEnemy', False) if dungeon is None: self.dungeon = Dungeon(30, 40, no_generate_enemy=self.random_enemy) else: self.dungeon = dungeon self.is_end = False self.friend_agent: Friend = None self.turn = 0 self.first_room = param.get('firstRoom', None) self.no_enemy = param.get('noEnemy', False) self.max_turn = param.get('maxTurn', 1500) self.map = self.dungeon.floor_map.copy() self.map[self.map == CellInfo.PROTECTED] = CellInfo.ROOM self.map[self.map == CellInfo.ENEMY] = CellInfo.ROOM self.enemy_list = [Enemy(-1, -1), Enemy(-1, -1)] self.reset()
def __init__(self, dungeon=None): if dungeon is None: self.dungeon = Dungeon(30, 40) else: self.dungeon = dungeon self.is_end = False # 部屋のグラフを指す隣接行列 self.map = [[0] * 5 for _ in range(5)] for road in self.dungeon.roads: room1_id = road.connected_rooms[0].id room2_id = road.connected_rooms[1].id self.map[room1_id][room2_id] = len(road.cells) self.map[room2_id][room1_id] = len(road.cells) self.goal_room_id = self.dungeon.goal_room_index self.first_room_index_candidate = list(range(5)) self.first_room_index_candidate.remove(self.goal_room_id) self.agent_room_id = random.choice(self.first_room_index_candidate)
def create_quest(self, loc_id, player_id): dungeonInst = Dungeon() charInst = Character() level = charInst.get_char_level(18) dung_id = dungeonInst.create_dungeon(level, loc_id, player_id) reward = randint(50, 200) typeInt = randint(1, 3) #set the type if (typeInt == 1): typeChar = 'K' description = "Kill this monster" elif (typeInt == 2): typeChar = 'F' description = "Fetch an item for me" elif (typeInt == 3): typeChar = 'R' description = "Rescue my buddy" #set the experience if (level < 5): experience = randint(100, 800) else: experience = randint(1000, 3000) self.connection.cursor.execute( """CALL Test.create_quest('{}','{}', '{}', '{}', '{}', '{}')""". format(reward, description, typeChar, loc_id, experience, dung_id)) self.connection.conn.commit() self.connection.cursor.execute( """SELECT quest_id FROM Quest WHERE Quest.dungeon_id = {}""". format(dung_id)) quest_id = self.connection.cursor.fetchall()[0][0] self.connection.cursor.execute( """INSERT INTO Quest_log (character_id, quest_id) VALUES ({}, {})""" .format(player_id, quest_id)) self.connection.conn.commit() return description
def parse(inputStream): dungeon = Dungeon() start_point = None end_point = None for line in inputStream: if line == '\n': continue line = line.replace('\n', '') # parse start_point and end_point if re.match(r'^\S+ \S+$', line) and start_point is None and end_point is None: start_point, end_point = line.split() # parse edge with type elif re.match( r'^\S+ \S+ \d+ [ud]$', line) and start_point is not None and end_point is not None: start, end, dist, edge_type = line.split() try: dungeon.add_edge(start, end, int(dist), edge_type) except Exception as msg: return dungeon, start_point, end_point, msg # parse edge without type (by default, the edge is oriented) elif re.match( r'^\S+ \S+ \d+$', line) and start_point is not None and end_point is not None: start, end, dist = line.split() try: dungeon.add_edge(start, end, int(dist)) except Exception as msg: return dungeon, start_point, end_point, msg else: return dungeon, start_point, end_point, 'Invalid input' if start_point is None or end_point is None: return dungeon, start_point, end_point, 'Invalid input' return dungeon, start_point, end_point, None
def __init__(self): GameEngineElement.__init__(self, has_draw=False, has_event=True) self.add_to_engine() game_size_ratio_x = self.game_engine.width/1200.0 game_size_ratio_y = self.game_engine.height/900.0 term_width_offset = game_size_ratio_x * 200 term_height = game_size_ratio_y * 200 term_height_offset = game_size_ratio_y * 700 term_width = game_size_ratio_x * 1000 """ term_width_offset = self.game_engine.width/4 term_height = self.game_engine.height/6 term_height_offset = self.game_engine.height - term_height term_width = self.game_engine.width - term_width_offset """ self.game_engine.add_object('mesg', TermBox(term_width_offset, term_height_offset,term_width,term_height,5) ) self.game_engine.get_object('mesg').add_line("Welcome to Fortune Hunter") self.game_engine.add_object('dungeon', Dungeon( self.game_engine.get_object('profile').dungeon_id))
def __init__(self): print("Starting server...") # Init vars Global.is_server = True # Used for local client spawning # Initialise the database system Database.startup() # Create the dungeon self.dungeon = Dungeon() # Create the server interface self.server = Server(self.dungeon) # Create a client for the local player (for testing). self.do_shutdown = False #self.create_local_client() # Comment this out unless a test client is desired # Run the game loop self.game_loop() # Shut down the database Database.shutdown()
def Run(self): self.myDungeon = Dungeon() self.myDungeon.Init() while True: self.Process()
def main(): alpha = 0.1 gamma = 0.8 q = np.zeros((5, 20, 15, 5, 5, 5, 5, 5)) eps = np.full((5, 20, 15, 5, 5, 5, 5), 0.99) # sum_r = np.zeros((5, 13, 12, 5, 5, 5, 5, 5)) # sum_c = np.zeros((5, 13, 12, 5, 5, 5, 5, 5), dtype=np.int64) random.seed(0) dungeon = Dungeon(30, 40) q1 = np.array(learn_room_move(dungeon)) print(q1) sim = CellMoveSimulator({}, dungeon=dungeon) t = Simulator2({}, dungeon=dungeon) random.seed() max_step = 1000000 # log = [] file = open('QL_log.csv', 'w') for step in range(max_step): state = sim.info() e = enemy(state) sum_reward = 0 episode_reward = 0 turn = 0 while not state['isEnd']: print(state['roomId'], state['x'], state['y'], 'reward:', sum_reward, 'turn:', turn, '\r', end='') action = select_action( q[state['roomId'], state['x'], state['y'], e[0][0], e[0][1], e[1][0], e[1][1]], eps[state['roomId'], state['x'], state['y'], e[0][0], e[0][1], e[1][0], e[1][1]]) eps[state['roomId'], state['x'], state['y'], e[0][0], e[0][1], e[1][0], e[1][1]] *= 0.98 # log.append(( # state['roomId'], state['x'], state['y'], e[0][0], e[0][1], e[1][0], e[1][1], # action # )) reward = sim.action({ 'action': int(action), 'nextRoomId': q1[state['roomId']] }) next_state = sim.info() e2 = enemy(next_state) sum_reward += reward q[state['roomId'], state['x'], state['y'], e[0][0], e[0][1], e[1][0], e[1][1], action] = (1.0 - alpha) * q[ state['roomId'], state['x'], state['y'], e[0][0], e[0][1], e[1][0], e[1][1], action] + alpha * (reward + gamma * q[ next_state['roomId'], next_state['x'], next_state['y'], e2[0][0], e2[0][1], e2[1][0], e2[1][1]].max()) # if reward != 0: # for rule in log: # sum_r[rule] += sum_reward # sum_c[rule] += 1 # q[rule] = sum_r[rule] / sum_c[rule] # log.clear() # episode_reward += sum_reward # sum_reward = 0 state = next_state e = e2 turn += 1 sim.reset() print(step, '/', max_step, 'reward:', sum_reward, 'turn:', turn) file.write(f'{step},{sum_reward},{turn}\n') if step % (max_step // 10) == 0: test(t, q) np.save('q_table1.npy', q1) np.save('q_table2.npy', q) for _ in range(5): test(t, q) time.sleep(1)
def run(): m = Dungeon(119, 47) m.setNumTries(500) m.createRooms(0.0) m.createMaze(1) print(m)
def test_move_hero_wrong_direction(self): d = Dungeon('map.txt', 'basic_loot_list_example.json') d.spawn(Hero("nz", "nz", 200, 120, 2)) self.assertFalse(d.move_hero("up"))
def main(self): """ This is the main method. """ global my_image, adventurer_i_index, adventurer_j_index, dng, exit_i_index, exit_j_index, n_rows, n_cols adventurer_i_index = 0 adventurer_j_index = 0 # Create tk windows and bind key strokes DungeonGui.create_tk_windows(self) # Create GUI rooms dungeon = DungeonGui(n_rows, n_cols) dungeon.create_rooms() # Populate the GUI rooms with dungeon content dng = Dungeon(n_rows, n_cols) dng.dungeon_generator() print(dng) for i in range(0, n_rows): for j in range(0, n_cols): row_index = i col_index = j content = dng.room_list[i][j].room_content if content == 'i': dungeon.create_content(row_index, col_index, content) if content == 'O': dungeon.create_content(row_index, col_index, content) east_door_symbol = dng.room_list[i][j].room_matrix[1][2] # dungeon.create_east_door(row_index, col_index, east_door_symbol) west_door_symbol = dng.room_list[i][j].room_matrix[1][0] # dungeon.create_west_door(row_index, col_index, west_door_symbol) north_door_symbol = dng.room_list[i][j].room_matrix[0][1] # dungeon.create_north_door(row_index, col_index, north_door_symbol) south_door_symbol = dng.room_list[i][j].room_matrix[2][1] # dungeon.create_south_door(row_index, col_index, south_door_symbol) if content == 'i': adventurer_i_index = i adventurer_j_index = j my_image = dungeon.create_adventurer( adventurer_j_index * 100 + 32, adventurer_i_index * 100 + 32) if content == 'O': exit_i_index = i exit_j_index = j #print(exit_i_index,exit_j_index) """ Displays """ label1a = tk.Label(my_window, text='INSTRUCTIONS:', fg="blue") label1a.config(font=('Arial', 15)) my_canvas.create_window(950, 50, window=label1a) label1b = tk.Label(my_window, text='Use Keyboard Arrow Keys') label1b.config(font=('Arial', 15)) my_canvas.create_window(950, 75, window=label1b) label2 = tk.Label(my_window, text='Entrance: i, Exit: O') label2.config(font=('Arial', 15)) my_canvas.create_window(950, 100, window=label2) label3 = tk.Label(my_window, text='Pillars and Doors Hidden') label3.config(font=('Arial', 15)) my_canvas.create_window(950, 150, window=label3) label3 = tk.Label(my_window, text='Gather Pillars and Reach O') label3.config(font=('Arial', 15)) my_canvas.create_window(950, 180, window=label3) label7 = tk.Label(my_window, text=' SCORE:', fg='blue') label7.config(font=('Arial', 15)) my_canvas.create_window(950, 300, window=label7) my_window.mainloop() # enter main loop