def __init__(self): """ DungeonGame constructor. """ player_input = query_player_input('Load last game (y/n)? ', ('y', 'n')) if player_input == 'y': self.game_map = GameMap() self.player = Player('') try: self.on_game_load() except FileNotFoundError as error: logging.error(error) logging.info('Save file not found, new game started.') else: return self.map_size = int( query_player_input('Enter map size: ', POSSIBLE_MAP_SIZES)) self.game_map = GameMap(map_size=self.map_size) player_name = input('Enter your name: ') self.player = Player(player_name) self.player.randomize_position(self.map_size) while self.game_map.get_tile_character( *self.player.get_position()) != GAME_CHARACTERS['Empty']: self.player.randomize_position(self.map_size)
def get_game_variables(): player = Entity(0, 0, '@', tcod.black, 'Player', True, render_order=RenderOrder.ACTOR, inventory=component("INVENTORY"), equipment=component("EQUIPMENT"), purse=component("PURSE"), fighter=component("PLAYER")) entities = [player] game_map = GameMap(CONFIG.get('MAP_WIDTH'), CONFIG.get('MAP_HEIGHT')) game_map.make_map( CONFIG.get('MAX_ROOMS'), CONFIG.get('ROOM_MIN_SIZE'), CONFIG.get('ROOM_MAX_SIZE'), player, entities, CONFIG.get('MAX_MONSTERS'), CONFIG.get('MAX_ITEMS'), component) message_log = MessageLog(CONFIG.get("MESSAGE_X"), CONFIG.get("MESSAGE_WIDTH"), CONFIG.get("MESSAGE_HEIGHT")) game_state = GameStates.INSTRUCTIONS return player, entities, game_map, message_log, game_state
def generate(width: int, height: int) -> GameMap: ROOMS = {'min_size': 7, 'max_size': 10, 'max': 30} gm = GameMap(width, height) gm.tiles[...] = WALL rooms: List[Room] = [] for _ in range(ROOMS['max']): w = randint(ROOMS['min_size'], ROOMS['max_size']) h = randint(ROOMS['min_size'], ROOMS['max_size']) x = randint(0, width - w - 1) y = randint(0, height - h - 1) new_room = Room(x, y, w, h) if any(new_room.intersects(other) for other in rooms): continue gm.tiles[new_room.inner] = FLOOR if rooms: other_room = rooms[-1] t_start = new_room.center t_end = other_room.center t_middle = t_start[0], t_end[1] gm.tiles[tcod.line_where(*t_start, *t_middle)] = FLOOR gm.tiles[tcod.line_where(*t_middle, *t_end)] = FLOOR rooms.append(new_room) for room in rooms: room.place_entities(gm) gm.player = spawn_entity(entities_db.player(), gm[rooms[0].center]) gm.entities.append(gm.player) gm.update_fov() return gm
def generate_dungeon(max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, max_monsters_per_room: int, player: Entity) -> GameMap: dungeon = GameMap(map_width, map_height, entities=[player]) rooms: List[RectangularRoom] = [] for r in range(max_rooms): room_width = random.randint(room_min_size, room_max_size) room_height = random.randint(room_min_size, room_max_size) x = random.randint(0, dungeon.width - room_width - 1) y = random.randint(0, dungeon.height - room_height - 1) new_room = RectangularRoom(x, y, room_width, room_height) if any(new_room.intersects(other_room) for other_room in rooms): continue dungeon.tiles[new_room.inner] = tile_types.floor if len(rooms) == 0: player.x, player.y = new_room.center else: for x, y in tunnel_between(rooms[-1].center, new_room.center): dungeon.tiles[x, y] = tile_types.floor place_entities(new_room, dungeon, max_monsters_per_room) rooms.append(new_room) return dungeon
def dataReceived(self, data): if not '\n' in data: self.buf += data return full = (self.buf + data).split("\n") self.buf = full[-1] for line in full[:-1]: json_data = json.loads(line) if json_data["message_type"] == "hello": global game_map print "Hello message" units = [Unit.from_dict(u) for u in json_data["units"]] bullets = [Bullet.from_dict(b) for b in json_data["bullets"]] hero = Hero.from_dict(json_data["hero"]) commander = Commander.from_dict(json_data["commander"]) game_map = GameMap(json_data["rows"], json_data["cols"], json_data["map"], hero, commander, units, bullets) elif json_data["message_type"] == "update": # Drop any removed units/bullets, then update values for remaining if len(game_map.units) > len(json_data["units"]): game_map.units = game_map.units[:len(json_data["units"])] for i in xrange(len(json_data["units"]) - len(game_map.units)): game_map.units.append(Unit(1, 1999, 1999, 0, 0)) for u_old, u_new in zip(game_map.units, json_data["units"]): u_old.update_from_dict(u_new) if len(game_map.bullets) > len(json_data["bullets"]): game_map.bullets = game_map.bullets[:len(json_data["bullets"])] for i in xrange(len(json_data["bullets"]) - len(game_map.bullets)): game_map.bullets.append(Bullet(0, 999, 999, 0, 0)) for b_old, b_new in zip(game_map.bullets, json_data["bullets"]): b_old.update_from_dict(b_new) game_map.hero.update_from_dict(json_data["hero"]) game_map.commander.update_from_dict(json_data["commander"])
def generate_dungeon( max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, engine: Engine, ) -> GameMap: """Generate a new dungeon map.""" player = engine.player dungeon = GameMap(engine, map_width, map_height, entities=[player]) #rooms = naiveGenerate(dungeon, max_rooms, room_min_size, room_max_size) rooms = bspGenerate(dungeon, player, engine, max_rooms, room_min_size, room_max_size, 1) player.place(*rooms[0].center, dungeon) print_dungeon(dungeon) for room in rooms: place_entities(room, dungeon, engine.game_world.current_floor) last_room = rooms[len(rooms) - 1] dungeon.tiles[last_room.center] = tile_types.down_stairs dungeon.downstairs_location = last_room.center return dungeon
def get_game_variables(constants): inventory_component = Inventory(26) body_component = get_human_body() player = Entity(int(constants['screen_width'] / 2), int(constants['screen_height'] / 2), '@', tcod.white, "Player", blocks=True, render_order=RenderOrder.ACTOR, ai=Player, inventory=inventory_component, body=body_component) entities = [player] animator = Animator([]) turn_count = 0 game_map = GameMap(constants['map_width'], constants['map_height']) game_map.make_map(player, entities, constants) message_log = MessageLog(constants['message_x'], constants['message_width'], constants['message_height']) game_state = GameStates.PLAYER_TURN return player, entities, animator, turn_count, game_map, message_log, game_state
def generate_dungeon( max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, ) -> GameMap: """Generate a dungeon by carving floors out of a map full of walls""" dungeon = GameMap(map_width, map_height) rooms: List[RectangularRoom] = [] while len(rooms) < max_rooms: # size and place the room room_width = random.randint(room_min_size, room_max_size) room_height = random.randint(room_min_size, room_max_size) x = random.randint(0, dungeon.width - room_width - 1) y = random.randint(0, dungeon.height - room_height - 1) room = RectangularRoom(x, y, room_width, room_height) # avoid creating overlapping rooms if any(room.intersects(other_room) for other_room in rooms): continue # clear out the room's inner area dungeon.tiles[room.inner] = tile_types.floor # tunnel to the previous room if len(rooms) > 0: for x, y in tunnel_between(rooms[-1].center, room.center): dungeon.tiles[x, y] = tile_types.floor rooms.append(room) return dungeon
def __init__(self, map_rows, map_cols, life_init_ratio): """将在主程序中初始化实例""" self.map_rows = map_rows self.map_cols = map_cols self.life_init_ratio = life_init_ratio self.game_map = GameMap(map_rows, map_rows) self.game_map.reset(life_init_ratio)
def __init__(self): # Configfile try: config = configparser.ConfigParser() config.read('config.cfg') default = config['DEFAULT'] self.name = default['name'] self.width = int(default['width']) self.height = int(default['height']) self.tps = int(default['tps']) filenames = config['FILENAMES'] self.background = pygame.image.load(os.path.join("game_assets", filenames['background'])) except KeyError: create_config() Game() # Initialization pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() self.resolution = (self.width, self.height) self.screen = pygame.display.set_mode(self.resolution) self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.game_map = GameMap(self) self.player = Player(self) self.magic_ball = MagicBall(self) # Sounds pygame.mixer.music.load('game_assets/sounds/game_sound.wav') pygame.mixer.music.set_volume(0.3) pygame.mixer.music.play(-1) # Run main loop self.run()
def init(): global game_map global hero global commander hero = Hero(10, 11.0, 11.0, math.pi/2) commander = Commander() game_map = GameMap(20, 20, [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], hero, commander, [Unit(10, 10.5, 7.5, 0)]) game_map.generate_hostiles(5) game_map.generate_friendlies(3)
def __init__(self): # Initialization libtcodpy.console_set_custom_font('src/arial10x10.png', libtcodpy.FONT_TYPE_GREYSCALE | libtcodpy.FONT_LAYOUT_TCOD) libtcodpy.console_init_root(settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT, 'ROGuelike TUTorial', False) libtcodpy.sys_set_fps(settings.LIMIT_FPS) self.con = libtcodpy.console_new(settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT) self.game_map = GameMap(self.con) player_x, player_y = self.game_map.get_staring_position() # game objects self.player = Player( 'Player', self.con, player_x, player_y, '@', fighter=Fighter(hp=15, defense=5, power=5, death_function=player_death)) npc_x, npc_y = self.game_map.get_ending_position() self.npc = Npc('Trader', self.con, npc_x, npc_y, '@') self.objects = [self.npc, self.player] self.npcs = [self.npc] for monster in self.game_map.place_monsters(): self.objects.append(monster) if hasattr(monster, 'is_selfmoving') and monster.is_selfmoving: self.npcs.append(monster) self.game_state = 'playing' self.player_action = None
def new_game(logger, renderer): # clear console renderer.clear_all() # Game map game_map = GameMap(MAP_WIDTH, MAP_HEIGHT, logger=logger) # generate an populate dungeons, create fov map game_map.generate_map() player_pos = game_map.player_initial_pos # instantiate player fighter_component = Fighter(hp=30, defense=2, power=2, death_function=player_death) player = MainPlayer( player_pos[0], player_pos[1], PLAYER_TILE[USE_TILES].code, 'player', PLAYER_TILE[USE_TILES].color, blocks=True, fighter=fighter_component, logger=logger) # initial equipment: a dagger equipment_component = Equipment(slot=RIGHT_HAND, power_bonus=2) obj = BaseObject(player.get_x_position(), player.get_y_position, DAGGER_TILE[USE_TILES], 'dagger', DAGGER_TILE[USE_TILES].color, logger=logger, equipment=equipment_component) player.inventory.append(obj) equipment_component.equip(player.inventory) obj.always_visible = True # Greet the player logger.log_message( 'Welcome stranger! Prepare to perish in the Tombs of the Ancient Kings.', tcod.red ) return game_map, player
def adjust_convex( dungeon: GameMap, rooms: List, ) -> None: """ This function will connect empty convexes with tunnels, or generate something in the convex. ### # # #+# -> an example of an empty convex """ # Log print("Adjusting Tunnels...") # Search empty_convex = search_empty_convex(dungeon=dungeon) # Connect convexes while len(empty_convex) >= 2: con1 = empty_convex.pop() con2 = empty_convex.pop() for x, y in path_between(dungeon.tunnelmap, (con1[0], con1[1]), (con2[0], con2[1])): if dungeon.tilemap[x, y] == TilemapOrder.VOID.value: dungeon.tiles[x, y] = dungeon.tileset["t_floor"]() dungeon.tilemap[x, y] = TilemapOrder.TUNNEL.value dungeon.tunnelmap[x, y] = True else: continue # Search for leftover, and use it as something else empty_convex = search_empty_convex(dungeon=dungeon) for cor in empty_convex: dungeon.tiles[cor] = dungeon.tileset["t_DEBUG"]()# TODO: Add feature
def generate_dungeon( biome, engine, depth, ) -> GameMap: player = engine.player rooms: List[Room] = [] dungeon = GameMap(depth=depth, engine=engine, biome=biome, entities=[player]) #NOTE: tilemap initialization happens during gamemap.__init__() dungeon.tileset = tile_functions(biome=biome) generate_earth( dungeon=dungeon, map_width=biome.map_width, map_height=biome.map_height, engine=engine ) generate_rooms( dungeon=dungeon, rooms=rooms, max_rooms=biome.max_rooms, engine=engine ) generate_tunnels( dungeon=dungeon, rooms=rooms, ) adjust_convex( dungeon=dungeon, rooms=rooms, ) generate_terrain( dungeon=dungeon, rooms=rooms, map_width=biome.map_width, map_height=biome.map_height, ) generate_stair( dungeon=dungeon, rooms=rooms, stair_type="pair" ) generate_entities( dungeon=dungeon, rooms=rooms, depth=depth, max_monsters_per_room=biome.max_monsters_per_room, max_items_per_room=biome.max_items_per_room, ) # debug(dungeon=dungeon) return dungeon
def generate_dungeon( max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, max_monsters_per_room: int, max_items_per_room: int, engine: Engine, ) -> GameMap: """Genererer et Dungeon Map Args: max_rooms (int): Maks antal af rum i dungeon room_min_size (int): Mindste størrelse af et rum room_max_size (int): Største størrelse af et rum map_width (int): Hele Dungeons bredde map_height (int): Hele Dungeons højde player ([type]): Player entity Returns: GameMap: Området hvor PCen er. """ player = engine.player dungeon = GameMap(engine, map_width, map_height, entities=[player, ]) rooms: List[RectangularRoom] = [] center_of_last_room = (0, 0) for room in range(max_rooms): room_width = random.randint(room_min_size, room_max_size) room_height = random.randint(room_min_size, room_max_size) pos_x = random.randint(0, dungeon.width - room_width - 1) pos_y = random.randint(0, dungeon.height - room_height - 1) new_room = RectangularRoom(pos_x, pos_y, room_width, room_height) if any(new_room.intersects(other_room) for other_room in rooms): continue dungeon.tiles[new_room.inner] = tile_types.floor if len(rooms) == 0: # Første rum, hvor spilleren starter player.place(*new_room.center, dungeon) else: for x, y in tunnel_between(rooms[-1].center, new_room.center): dungeon.tiles[x, y] = tile_types.floor center_of_last_room = new_room.center place_entities(new_room, dungeon, max_monsters_per_room, max_items_per_room) dungeon.tiles[center_of_last_room] = tile_types.down_stairs dungeon.downstairs_location = center_of_last_room rooms.append(new_room) return dungeon
def generate_dungeon( max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, max_monsters_per_room: int, engine: Engine, ) -> GameMap: """Generate a new dungeon map.""" player = engine.player dungeon = GameMap(engine, map_width, map_height, entities=[player]) rooms: List[RectangularRoom] = [] dungeon.tiles[:] = tile_types.floor # for r in range(max_rooms): room_width = random.randint(room_min_size, room_max_size) room_height = random.randint(room_min_size, room_max_size) x = random.randint(0, dungeon.width - room_width - 1) y = random.randint(0, dungeon.height - room_height - 1) # "RectangularRoom" class makes rectangles easier to work with new_room = RectangularRoom(x, y, room_width, room_height) # Run through the other rooms and see if they intersect with this one. if any(new_room.intersects(other_room) for other_room in rooms): continue # This room intersects, so go to the next attempt. # If there are no intersections then the room is valid. # Dig out this rooms inner area. dungeon.tiles[new_room.outer] = tile_types.wall dungeon.tiles[new_room.inner] = tile_types.floor if len(rooms) == 0: # The first room, where the player starts. player.place(*new_room.center, dungeon) else: # All rooms after the first. # Dig out a tunnel between this room and the previous one. # in this new generation model this is sort of a hack -- it creates # doors but does nothing else. for x, y in tunnel_between(rooms[-1].center, new_room.center): dungeon.tiles[x, y] = tile_types.floor place_entities(new_room, dungeon, max_monsters_per_room) # Finally, append the new room to the list. rooms.append(new_room) # don't allow more than one enemy for now # this is disgusting but seems to work because sets have an implicit order # and I can trust it at this point in execution??? # dungeon.entities = set(list(dungeon.entities)[0:2]) return dungeon
def build_map(self, level=1): self.game_map = GameMap(self.message_log, level) self.entities = Entities(self.game_map) self.game_map.make_map(self.player, self.entities) self.entities.insert_entity(self.player) self.fov_recompute = True self.fov_map = initialize_fov(self.game_map)
def render_all(entities: List[Entity], game_map: GameMap, colors, camera: Camera): # Draw the map game_map.render(colors=colors, camera=camera) # Draw all entities in the list for entity in entities: if game_map.fov[entity.x, entity.y]: entity.draw(camera)
def __init__(self): self.my_game_map = GameMap() self.DIRECTION_TO_MOVE = { 'up': [-1, 0], 'down': [1, 0], 'left': [0, -1], 'right': [0, 1] }
def _place_downstairs( self, rooms: List[RectangularRoom], dungeon: GameMap ): field = self._get_random_room(rooms).random_field dungeon.tiles[field] = tile_types.down_stairs dungeon.downstairs_location = field
def generate_random_dungeon( max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, max_enemies: int, engine: Engine, ) -> GameMap: ''' Generates a new procedurally-built dungeon map. ''' # Get the player player = engine.player # Get the map width/height passed into the function and set a map instance with those dimensions. dungeon = GameMap(engine, map_width, map_height, entities=[player]) # Set a typed List to hold all the generated room instances (reference/key is 'rooms') rooms: List[RectangularRoom] = [] for room in range(max_rooms): # Set random room width/height room_width = random.randint(room_min_size, room_max_size) room_height = random.randint(room_min_size, room_max_size) # Set random coordinates to place the room x = random.randint(0, dungeon.width - room_width - 1) y = random.randint(0, dungeon.height - room_height - 1) # Create a room (class instance) using the random values new_room = RectangularRoom(x, y, room_width, room_height) # Iterate through other rooms in the List to determine if it overlaps (True or False) if any(new_room.intersects(other_room) for other_room in rooms): # If 'True', scrap the room and start the loop again to create a new one continue # When '.intersects()' does return 'False' (room doesn't overlap), the room is valid and can be tiled # (Set tiles to replace the default inner wall tiles initialized by the GameMap class) dungeon.tiles[new_room.inner] = tile_types.grass # Set player's starting position in the first room (from Tuple returned by room's '.center()' method) if len(rooms) == 0: player.place(*new_room.center, dungeon) else: # Connect the centers of the previous room and the current one (tunnel) # ('rooms[-1]' goes backward in the rooms array by one item) for x, y in tunnel_between(rooms[-1].center, new_room.center): # Set the tiling for the tunnel dungeon.tiles[x, y] = tile_types.dirt place_entities(new_room, dungeon, max_enemies) # Add the new room to the list of other rooms rooms.append(new_room) return dungeon
class LifeGame(object): """ Game of life. This class controls a game cycle triggered by timer. Attributes: game_map: GameMap instance. """ def __init__(self, map_rows=10, map_cols=10, life_init_possibility=0.5): self.game_map = GameMap(map_rows, map_cols) self.game_map.reset(life_init_possibility) def print_map(self): """Clear the console, then print the map""" os.system('cls' if os.name == 'nt' else 'clear') self.game_map.print_map() def game_cycle(self): nc_map = self.game_map.get_neighbor_count_map() for row in range(self.game_map.rows): for col in range(self.game_map.cols): nc = nc_map[row][col] if nc < 2 or nc > 3: self.game_map.set(row, col, 0) elif nc == 3: self.game_map.set(row, col, 1) self.print_map()
def generate_dungeon( max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, max_monsters_per_room: int, max_items_per_room: int, engine: Engine, ) -> GameMap: """Generate a new dungeon map.""" player = engine.player dungeon = GameMap(engine, map_width, map_height, entities=[player]) rooms: List[RectangularRoom] = [] center_of_last_room = (0, 0) for r in range(max_rooms): room_width = random.randint(room_min_size, room_max_size) room_height = random.randint(room_min_size, room_max_size) x = random.randint(0, dungeon.width - room_width - 1) y = random.randint(0, dungeon.height - room_height - 1) # "RectangularRoom" class makes rectangles easier to work with new_room = RectangularRoom(x, y, room_width, room_height) # Run through the other rooms and see if they intersect with this one. if any(new_room.intersects(other_room) for other_room in rooms): continue # This room intersects, go to the next attempt. # If there are no intersections then the room is valid. # Dig out this rooms inner area. dungeon.tiles[new_room.inner] = tile_types.floor if len(rooms) == 0: # The first room, where the player starts. player.place(*new_room.center, dungeon) else: # Dig out a tunnel between this room and the previous one. for x, y in tunnel_between(rooms[-1].center, new_room.center): dungeon.tiles[x, y] = tile_types.floor center_of_last_room = new_room.center place_entities(new_room, dungeon, max_monsters_per_room, max_items_per_room) dungeon.tiles[center_of_last_room] = tile_types.down_stairs dungeon.downstairs_location = center_of_last_room rooms.append(new_room) return dungeon
def generate_earth( dungeon: GameMap, map_width: int, map_height: int, engine: Engine ) -> None: # Log print("Generating Earth...") # Generate color-randomized walls for x in range(len(dungeon.tiles)): for y in range(len(dungeon.tiles[x])): dungeon.tiles[x, y] = dungeon.tileset["t_wall"]() # Generate unbreakable outer walls for x in range(len(dungeon.tiles)): dungeon.tiles[x, 0] = dungeon.tileset["t_border"]() dungeon.tilemap[x, 0] = TilemapOrder.MAP_BORDER.value dungeon.tiles[x, -1] = dungeon.tileset["t_border"]() dungeon.tilemap[x, -1] = TilemapOrder.MAP_BORDER.value for y in range(len(dungeon.tiles[0])): dungeon.tiles[0, y] = dungeon.tileset["t_border"]() dungeon.tilemap[0, y] = TilemapOrder.MAP_BORDER.value dungeon.tiles[-1, y] = dungeon.tileset["t_border"]() dungeon.tilemap[-1, y] = TilemapOrder.MAP_BORDER.value
def generate_dungeon( max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, engine: Engine, ) -> GameMap: """Generate a new dungeon map""" player = engine.player dungeon = GameMap(engine, map_width, map_height, entities=[player]) #keep a running list of all of the rooms rooms: List[RectangularRoom] = [] center_of_last_room = (0, 0) for r in range(max_rooms): #use given minimum and maximum room sizes to set the room's width and height room_width = random.randint(room_min_size, room_max_size) room_height = random.randint(room_min_size, room_max_size) x = random.randint(0, dungeon.width - room_width - 1) y = random.randint(0, dungeon.height - room_height - 1) #"RectangularRoom" class makes rectangles easier to work with new_room = RectangularRoom(x, y, room_width, room_height) #Run through the other rooms to see if they intersect with this one if any(new_room.intersects(other_room) for other_room in rooms): continue #This room intersects, so go on to next attempt #If there are no intersections then the room is valid. #dig out this room's inner area. dungeon.tiles[new_room.inner] = tile_types.floor if len(rooms) == 0: #The first room, where the player starts player.place(*new_room.center, dungeon) else: #All rooms that come after the first #Dig out a tunnel between this room and the previous room for x, y in tunnel_between(rooms[-1].center, new_room.center): dungeon.tiles[x, y] = tile_types.floor center_of_last_room = new_room.center place_entities(new_room, dungeon, engine.game_world.current_floor) dungeon.tiles[center_of_last_room] = tile_types.down_stairs dungeon.downstairs_location = center_of_last_room #Finally, append the new room to the list. rooms.append(new_room) return dungeon
def __init__(self): """ Constructor for GameStep class """ self.my_game_map = GameMap() self.DIRECTION_TO_MOVE = { 'up': [-1, 0], 'down': [1, 0], 'left': [0, -1], 'right': [0, 1] }
def generate_tunnels( dungeon: GameMap, rooms: List, ) -> None: """Generate a new dungeon map.""" # Log print("Generating Tunnels...") # Sort rooms by the distance between one another dist_order_rooms = [] temp = copy.deepcopy(rooms) new = None while len(temp) != 0: if len(dist_order_rooms) == 0: base_room = temp.pop() dist_order_rooms.append(base_room) else: base_room = new[0] dist_order_rooms.append(new[0]) temp.remove(new[0]) new = None for room in temp: dist_square = pow(base_room.x1 - room.x1, 2) + pow(base_room.y1 - room.y1, 2) if new == None: new = (room, dist_square) elif new[1] > dist_square: new = (room, dist_square) # Choose two rooms and make a tunnel while len(dist_order_rooms) >= 2: room1 = dist_order_rooms.pop(0) room2 = dist_order_rooms[0] # The path starts at the center of the room start_x = room1.center[0] start_y = room1.center[1] end_x = room2.center[0] end_y = room2.center[1] for x, y in path_between(dungeon.tunnelmap, (start_x, start_y), (end_x, end_y)): if dungeon.tilemap[x, y] == TilemapOrder.VOID.value: dungeon.tiles[x, y] = dungeon.tileset["t_floor"]() dungeon.tilemap[x, y] = TilemapOrder.TUNNEL.value dungeon.tunnelmap[x, y] = True else: continue return None
def generate_dungeon( max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, engine: Engine, ) -> GameMap: '''Generate a new dungeon map.''' player = engine.player dungeon = GameMap(engine, map_width, map_height, entities=[player]) rooms: List[RectangularRoom] = [] center_of_last_room = (0, 0) for r in range(max_rooms): room_width = random.randint(room_min_size, room_max_size) room_height = random.randint(room_min_size, room_max_size) x = random.randint(0, dungeon.width - room_width - 1) y = random.randint(0, dungeon.height - room_height - 1) # RectangularRoom class makes rectangles a bit easier to work w new_room = RectangularRoom(x, y, room_width, room_height) # spot some intersections if any(new_room.intersects(other_room) for other_room in rooms): continue # room intersects, so go to the next one # dig out room inner area dungeon.tiles[new_room.inner] = tile_types.floor if len(rooms) == 0: # first room, where player starts player.place(*new_room.center, dungeon) else: # dig a tunnel between this and the previous for x, y in tunnel_between(rooms[-1].center, new_room.center): dungeon.tiles[x, y] = tile_types.floor center_of_last_room = new_room.center place_entities(new_room, dungeon, engine.game_world.current_floor) # the very last room added will get the `tile_types.down_stairs` tile dungeon.tiles[center_of_last_room] = tile_types.down_stairs dungeon.downstairs_location = center_of_last_room # append room to list rooms.append(new_room) return dungeon
def generate_dungeon(map_width, map_height) -> GameMap: dungeon = GameMap(map_width, map_height) room_1 = RectangularRoom(x=20, y=15, width=10, height=15) room_2 = RectangularRoom(x=35, y=15, width=10, height=15) dungeon.tiles[room_1.inner] = tile_types.floor dungeon.tiles[room_2.inner] = tile_types.floor for x, y in tunnel_between(room_2.center, room_1.center): dungeon.tiles[x, y] = tile_types.floor return dungeon
def __init__(self, master, **kwargs): super().__init__(master, **kwargs) Oriented.__init__(self, 'north') Rectangular.__init__(self, (self.winfo_reqwidth(), self.winfo_reqheight())) Positionable.__init__(self, (0, 0)) self.images = {} self.sprites = {} self.key_pressed = False self.map = GameMap(GameMapConfig.size, self) self.map.place_rectangle(pos=(0, 0), dim=(500, 500), fill='green') self.map.draw()
def generate_dungeon( max_rooms: int, room_min_size: int, room_max_size: int, map_width: int, map_height: int, max_monsters_per_room: int, engine: Engine, ) -> GameMap: """Generate a new dungeon map""" player = engine.player dungeon = GameMap(engine, map_width, map_height, entities=[player]) rooms: List[RectangularRoom] = [] for r in range(max_rooms): room_width = random.randint(room_min_size, room_max_size) room_height = random.randint(room_min_size, room_max_size) # coordinates that keep it from going off the map x = random.randint(0, dungeon.width - room_width - 1) y = random.randint(0, dungeon.height - room_height - 1) # "RectangularRoom" class makes rectangles easier to work with new_room = RectangularRoom(x, y, room_width, room_height) # Run through the other rooms and see if they intersect with this one if any(new_room.intersects(other_room) for other_room in rooms): continue # This room intersects, so go to the next attempt # If there are no intersections then the room is valid # Dig out this rooms inner area dungeon.tiles[new_room.inner] = tile_types.floor if len(rooms) == 0: # The first room, where the player starts player.place(*new_room.center, dungeon) else: # All rooms after the first # Dig out a tunnel between this room and the previous one for x, y in tunnel_between(rooms[-1].center, new_room.center): dungeon.tiles[x, y] = tile_types.floor # places entities in the rooms place_entities(new_room, dungeon, max_monsters_per_room) # Finally, append the new room to the list rooms.append(new_room) return dungeon
def __init__(self, name, text, robot_point = None): """ """ self._name = name self._game_map = GameMap(text, robot_point) self._status = globals_.Status.NEW self._visible_map = None
def start(self): """ Method that starts a game, loading the robot if needed. It leaves the game ready to be played. """ self._game_map.load_robot() if self._visible_map is None: self._visible_map = GameMap(robot_point = self._game_map.get_robot_point()) self._visible_map.append(self._game_map.get_new_room(self._visible_map)) os.system("setterm -cursor off") self._play() os.system("setterm -cursor on")
def scnene_game( gameDisplay ): # create game object # map play_map = GameMap(res.position_game_map, res.size_game_map, res.color_map, res.size_grid, res.game_map_grids, res.width_game_map_wall, res.color_wall) play_map.kit_reset( res.kit_max, res.kit_freq ) play_map.kit_gen() play_map.kit_gen() # player arrow arrow_p1 = Arrow(res.size_arrow, play_map.grid_center(res.grid_position_start_p1), (1,0), 2, res.speed_max, res.color_p1) arrow_p2 = Arrow(res.size_arrow, play_map.grid_center(res.grid_position_start_p2), (-1,0), 2, res.speed_max, res.color_p2) # player panel bar_p1 = PowerBar( res.position_panel_p1+res.size_panel_p1, res.speed_max, res.color_p1, (0,0,0) ) bar_p2 = PowerBar( res.position_panel_p2+res.size_panel_p2, res.speed_max, res.color_p2, (0,0,0) ) panel_p1 = PlayerPanel( res.position_panel_p1, res.size_panel_p1, res.color_p1 ) panel_p1.set_item_slot( res.slot_layout ) panel_p1.set_player( arrow_p1 ) panel_p1.set_power_bar( bar_p1 ) panel_p2 = PlayerPanel( res.position_panel_p2, res.size_panel_p2, res.color_p2 ) panel_p2.set_item_slot( res.slot_layout ) panel_p2.set_player( arrow_p2 ) panel_p2.set_power_bar( bar_p2 ) # add object to game gameArrowList = [] gameArrowList.append( ArrowInGame(arrow_p1) ) gameArrowList.append( ArrowInGame(arrow_p2) ) for gameArrow in gameArrowList: gameArrow.set_grid_position( play_map.detect_grid(gameArrow.arrow.position) ) # register key done event key_control = { res.control_p1['right']:lambda :game_map_turn_correct(arrow_p1, play_map, (1,0)), res.control_p1['left']: lambda :game_map_turn_correct(arrow_p1, play_map, (-1,0)), res.control_p1['up']: lambda :game_map_turn_correct(arrow_p1, play_map, (0,-1)), res.control_p1['down']: lambda :game_map_turn_correct(arrow_p1, play_map, (0,1)), res.control_p1['kit']: lambda :arrow_p1.kit_invoke(), res.control_p2['right']:lambda :game_map_turn_correct(arrow_p2, play_map, (1,0)), res.control_p2['left']: lambda :game_map_turn_correct(arrow_p2, play_map, (-1,0)), res.control_p2['up']: lambda :game_map_turn_correct(arrow_p2, play_map, (0,-1)), res.control_p2['down']: lambda :game_map_turn_correct(arrow_p2, play_map, (0,1)), res.control_p2['kit']: lambda :arrow_p2.kit_invoke() } game_over = False while not game_over: # handle event for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.KEYDOWN: for key in key_control: if key == event.key: key_control[key]() # print(event) # raise game event if (game_arrow_encounter(arrow_p1, arrow_p2) == res.game_brokeback): return True game_arrow_map_event( gameArrowList, play_map ) # progress game play_map.kit_progress() arrow_p1.progress() game_map_bump_correct( arrow_p1, play_map ) arrow_p2.progress() game_map_bump_correct( arrow_p2, play_map ) # render gameDisplay.fill(res.color_background) play_map.draw( gameDisplay ) panel_p1.draw( gameDisplay ) panel_p2.draw( gameDisplay ) arrow_p1.draw( gameDisplay ) arrow_p2.draw( gameDisplay ) pygame.display.update() res.clock.tick( res.tick_game )
print "We are playing the Game" if response == "c": print("let's start driving a car!") myVeh = Car() elif response == "m": print("let's drive a Motorcycle") myVeh = Motorcycle() elif response == "b": print("let's ride a Bike") myVeh = Bike() else: print "your input was invalid" response = raw_input("What vehicle would you like to choose? (c)ar, (m)otorcycle, (b)ike, (q)uit") continue new_map = GameMap() #set vehicles while new_map.bool_win() is False: spaces = myVeh.run() print "The car is moving space %d" % spaces new_map.new_position(spaces) print "New position is %d" % new_map.position print "We are Finished Racing" response = raw_input( "Do you wish to play again? What vehicle would you like to choose? (c)ar, (m)otorcycle, (b)ike, (q)uit")
def __init__(self, map_rows=10, map_cols=10, life_init_possibility=0.5): self.game_map = GameMap(map_rows, map_cols) self.game_map.reset(life_init_possibility)
class Game: """Defines a game object. Is the acctual game populated with it's map component objects.""" def __init__(self, name, text, robot_point = None): """ """ self._name = name self._game_map = GameMap(text, robot_point) self._status = globals_.Status.NEW self._visible_map = None def start(self): """ Method that starts a game, loading the robot if needed. It leaves the game ready to be played. """ self._game_map.load_robot() if self._visible_map is None: self._visible_map = GameMap(robot_point = self._game_map.get_robot_point()) self._visible_map.append(self._game_map.get_new_room(self._visible_map)) os.system("setterm -cursor off") self._play() os.system("setterm -cursor on") def get_name(self): """ """ return self._name def get_status(self): """ """ return self._status def get_game_map(self): """ """ return self._game_map def print_map(self, visible_only = True): """ Cleans terminal and prints map """ os.system("clear") # os.system("cls") # windows if visible_only: self._visible_map.print_map() else: self._game_map.print_map() #### private functions ### def _on_key_press(self): """ Method that allows to the input on the key stroke without sowing in the terminal Reference: - http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/ """ stdin_file_descriptor = sys.stdin.fileno() old_settings = termios.tcgetattr(stdin_file_descriptor) try: tty.setraw(stdin_file_descriptor) ch = sys.stdin.read(1) finally: termios.tcsetattr(stdin_file_descriptor, termios.TCSADRAIN, old_settings) return ch def _play(self): """ Game loop. """ self._status = globals_.Status.IN_PLAY known_door_points = list() while True: self.print_map() self._print_keys() move = self._on_key_press() # move = raw_input() # windows while not self._game_map.move_is_valid(move): move = self._on_key_press() # move = raw_input() # windows if move == globals_.KEYS['QUIT']: print 'quit' break self._game_map.move_robot(move) if self._game_map.robot_at_door(): current_point = self._game_map.get_robot_point() current_point = Point(current_point.get_x(),current_point.get_y()) if current_point not in known_door_points: self._visible_map.append(self._game_map.get_new_room(self._visible_map, move)) known_door_points.append(current_point) if self._game_map.is_end_of_game(): self.print_map() self._status = globals_.Status.OVER print "---- YOU WIN!! ----" break def _print_keys(self): """ Prints the keys to be used to play """ keys = "" for name, k in globals_.KEYS.items(): if name != 'QUIT': keys = "{}\n{}\t-\t[{}]".format(keys, name, k) keys = "{}\n{}\t-\t[{}]".format(keys, 'QUIT', globals_.KEYS['QUIT']) print keys def __repr__(self): """ """ return "<Game: name {},\ntext: \n{}>".format(self._name, str(self)) def __str__(self): """ Tranforms the _game_map into text """ game_text = "" robot_point = self._robot.get_point() row = 0 for obj in self._game_map: if robot_point is not None and obj.get_point() == robot_point: obj = self._robot if obj.get_point().get_y() == row + 1: game_text = "{}\n".format(game_text) row += 1 game_text = "{}{}".format(game_text, obj.get_symbol()) return game_text