def read(self) -> None: """Read from all data""" map_num = len([m for m in os.listdir('maps/')]) path_num = len([m for m in os.listdir('paths/')]) # Reading game maps if map_num != 0: for i in range(1, map_num + 1): map_name = 'map{}'.format(i) new_map = GameMap(self.screen_size, self.div, False) new_map.read_map(map_name) self.map_list.append(new_map) # Reading paths if path_num != 0: for i in range(1, path_num + 1): path_name = 'path{}.csv'.format(i) path_dir = os.path.join(r'paths\\', path_name) pos = (int(self.screen_size[0] / self.div - self.player_rect[0] / 2), int(self.screen_size[1] / 2 - self.player_rect[1] / 2)) new_path = Path(initial_pos=pos) new_path.read_path(path_dir) self.path_list.append(new_path)
def __init__(self): #set everything to default initializations. self.player = None self.player_action = None self.game_state = None self.map = GameMap() self.screen = Screen() self.map.screen = self.screen
def get_game_variables(constants): fighter_component = Fighter(hp=30, defense=2, power=5) inventory_component = Inventory(26) player = Entity(0, 0, '@', libtcod.white, 'Player', blocks=True, render_order=RenderOrder.ACTOR, fighter=fighter_component, inventory=inventory_component) entities = [player] game_map = GameMap(constants['map_width'], constants['map_height']) game_map.make_map(constants['max_rooms'], constants['room_min_size'], constants['room_max_size'], constants['map_width'], constants['map_height'], player, entities, constants['max_monsters_per_room'], constants['max_items_per_room']) message_log = MessageLog(constants['message_x'], constants['message_width'], constants['message_height']) game_state = GameStates.PLAYERS_TURN return player, entities, game_map, message_log, game_state
def main(): screen_width = 80 screen_height = 50 map_width = 80 map_height = 45 room_max_size = 10 room_min_size = 6 max_rooms = 30 player = Entity('player', '@', tcod.white) player.interactable = NPC(player) player.fighter = Fighter(player, hp=30, defense=2, power=5) player.render_order = RenderOrder.ACTOR tcod.console_set_custom_font( 'terminal12x12_gs_ro.png', tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_ASCII_INROW ) with tcod.console_init_root( screen_width, screen_height, 'Roguelikedev2019', order='F', renderer=tcod.RENDERER_SDL2, vsync=True ) as root_console: con = tcod.console.Console(screen_width, screen_height, order='F') game_map = GameMap(map_width, map_height, player) game_map.load(make_sample_map(map_width, map_height)) #game_map.load(make_tutorial_map(map_width, map_height, max_rooms, room_min_size, room_max_size)) handler = Playing(game_map) while True: con.clear(fg=(255,255,255)) handler.update() handler.render(con) con.print(1, screen_height - 2, f'HP: {player.fighter.hp}/{player.fighter.max_hp}', (255,255,255), (0,0,0), tcod.BKGND_NONE, tcod.LEFT) con.blit(root_console, 0, 0, 0, 0, screen_width, screen_height) tcod.console_flush() for event in tcod.event.wait(): handler.dispatch(event)
def __init__(self): self.game_map = GameMap() self.game_logic = GameLogic(self.game_map) self.view = View() self.level_start() self.enemy_actions() self.player_actions() self.check_game_status()
def create_map(map_console, *, floor_schedule, terrain_schedule, monster_schedule, item_schedule): """Construct and return the game map. The game map is the main object representing the state of the game. """ floor = make_floor(GLOBAL_FLOOR_CONFIG, floor_schedule) game_map = GameMap(floor, map_console) terrain = add_random_terrain(game_map, terrain_schedule) # TODO: game_map should be the first argument here. spawn_entities(monster_schedule, MONSTER_GROUPS, game_map) spawn_entities(item_schedule, ITEM_GROUPS, game_map) return game_map
def set_general_paths(self, game_map: GameMap, rect_size: Tuple[int, int]): """Returns a path traversing through all possible routes""" div = game_map.get_div() h_step, v_step = game_map.get_step() obstacles = [x[0] for x in game_map.get_obstacles()] treasures = game_map.get_treasures() all_pos = [] for i in range(1, div): for j in range(1, div): x = int(i * h_step - rect_size[0] / 2) y = int(j * v_step - rect_size[1] / 2) temp_rect = pg.Rect((x, y), rect_size) if temp_rect.collidelist(obstacles) == -1 and temp_rect.collidelist(treasures) == -1: all_pos.append((x, y)) self._graph.add_vertex((x, y)) for pos1 in all_pos: for pos2 in all_pos: if pos1 != pos2: if abs(pos1[0] - pos2[0]) == 0 and abs(pos1[1] - pos2[1]) == v_step: self._graph.add_edge(pos1, pos2) if abs(pos1[1] - pos2[1]) == 0 and abs(pos1[0] - pos2[0]) == h_step: self._graph.add_edge(pos1, pos2)
def run(): pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF) resize(*SCREEN_SIZE) init() clock = pygame.time.Clock() glMaterial(GL_FRONT, GL_AMBIENT, (0.1, 0.1, 0.1, 1.0)) glMaterial(GL_FRONT, GL_DIFFUSE, (1.0, 1.0, 1.0, 1.0)) # This object renders the 'map' #print test_map object_list = [ ImmovableThing(2,2,3),PassableThing(2,3,2),PickupThing(2,4,1),PickupThing(1,1,1)] game_map = GameMap(test_map,object_list) player = game_map.add_player(2, 3) while True: for event in pygame.event.get(): if event.type == QUIT: return if event.type == KEYUP and event.key == K_ESCAPE: return # Clear the screen, and z-buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(FPS): time_passed = clock.tick(FPS) else: time_passed = clock.tick() time_passed_seconds = time_passed / 1000. pressed = pygame.key.get_pressed() player.do_input(pressed) player.update_vectors(time_passed_seconds) # Upload the inverse camera matrix to OpenGL glLoadMatrixd(player.camera_matrix.get_inverse().to_opengl()) # Light must be transformed as well glLight(GL_LIGHT0, GL_POSITION, (0, 1.5, 1, 0)) # Render the map game_map.render() game_map.objects_render(player) # Show the screen pygame.display.flip()
from renderer import render_map, render_projectiles from map import GameMap from tank import PlayerTank, EnemyTank from gamelevel import GameLevel from position import Position from gamerules import GameRules game_map = GameMap() player_tank = PlayerTank(Position(10, 10)) enemy_tanks = [ EnemyTank(Position(14, 10)), EnemyTank(Position(13, 15)), EnemyTank(Position(17, 1)), EnemyTank(Position(15, 22)), EnemyTank(Position(14, 20)) ] game_level = GameLevel(game_map, player_tank, enemy_tanks) game_rules = GameRules(game_level) while not game_rules.game_over: game_rules.check_if_enemy_tanks_exist() game_rules.check_player_health() render_map(game_level) game_rules.process_user_input() if len(game_level.projectiles) > 0: render_projectiles(game_level) game_rules.randomly_shoot_projectile() if len(game_level.projectiles) > 0: render_projectiles(game_level) game_rules.move_enemy_tanks()
class Game: def __init__(self): #set everything to default initializations. self.player = None self.player_action = None self.game_state = None self.map = GameMap() self.screen = Screen() self.map.screen = self.screen #Creates a new player. Used when calling a new game, or when the player dies. def initialize_new_player(self): fighter_component = BaseCharacterClass(hp=100, defense=1, power=4) self.player = Player(self.map.orig_player_x, self.map.orig_player_y, '@', 'player', libtcod.white, blocks=True, character_class=fighter_component, screen=self.screen) self.player.equipment['right hand'] = items.Equipment(0, 0, '/', 'sword', libtcod.light_blue, 'right hand', power_bonus=2) self.map.player = self.player self.map.objects.append(self.player) #Creates a new game, with a new player, and a new map. def new_game(self): #create object representing the player self.initialize_new_player() #generate map (at this point it's not drawn to the screen) and the FOV self.map.make() self.map.initialize_fov() #We're playing now, so send a message. self.game_state = 'playing' self.screen.message('Welcome stranger! Prepare to perish in the Tombs of the Ancient Kings.', 'red') #Plays the game, using a loop to capture player input, repaint the screen, etc. def play_game(self): self.player_action = None #capture inputs self.screen.mouse = libtcod.Mouse() self.screen.key = libtcod.Key() #iterate while the console screen is open. while not libtcod.console_is_window_closed(): #check for events. libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, self.screen.key, self.screen.mouse) #render the screen and flush the console. self.screen.render_all(self.map) libtcod.console_flush() #check for levelups self.player.check_level_up() #handle keys and exit game if needed for object in self.map.objects: object.clear(self.screen.con) self.player_action = self.screen.handle_keys(self.game_state, self.player, self.map.objects, self.map) #exit the game if the player select so if self.player_action == 'exit': self.save_game() break #let monsters take their turn if self.game_state == 'playing' and self.player_action != 'didnt-take-turn': for object in self.map.objects: if isinstance(object, Creature) and object.name != 'player' and not object.dead: #take monster turns and check to see if monsters have killed the player. object.ai.take_turn(self.player, self.map) #if monsters have killed the player, spawn a new player #set it at the original start of the dungeon if self.player.dead: #assign the player object and add it to the objects tree. self.initialize_new_player() #update the creatures player bindings self.map.update_player_bindings() #Saves the game to disk. def save_game(self): #open a new empty shelve (possibly overwriting an old one) to write the game data # file = open('savegame.sav', 'wb') # pickle.dump(self.map, file) # pickle.dump(self.map.objects, file) # pickle.dump(self.player, file) # pickle.dump(self.screen, file) # pickle.dump(self.screen.game_msgs, file) # pickle.dump(self.screen.fov_recompute, file) # pickle.dump(self.screen.fov_map, file) # pickle.dump(self.game_state, file) # pickle.dump(self.map.stairs, file) file = shelve.open('savegame.s', 'n') file['map'] = self.map file['objects'] = self.map.objects file['player'] = self.player file['game_msgs'] = self.screen.game_msgs file['fov_map'] = self.screen.fov_map file['fov_recompute'] = self.screen.fov_recompute file['game_state'] = self.game_state file['stairs'] = self.map.stairs file.close() #Loads the game from disk. def load_game(self): #open the previously saved shelve and load the game data # file = open('savegame.sav', 'rb') # self.map = pickle.load(file) # self.map.objects = pickle.load(file) # self.player = pickle.load(file) # self.map.player = self.player # self.screen = Screen() # self.screen.game_msgs = pickle.load(file) # self.screen.fov_map = pickle.load(file) # self.screen.fov_recompute = pickle.load(file) # self.game_state = pickle.load(file) # self.map.stairs = pickle.load(file) file = shelve.open('savegame.s', 'r') self.map = file['map'] self.map.objects = file['objects'] self.player = file['player'] self.screen.fov_map = file['fov_map'] self.screen.fov_recompute = file['fov_recompute'] self.screen.game_msgs = file['game_msgs'] self.game_state = file['game_state'] self.map.stairs = file['stairs'] file.close() self.map.player = self.player self.map.screen = self.screen self.map.update_player_bindings() self.map.initialize_fov() libtcod.sys_set_fps(self.screen.LIMIT_FPS) #Opens the Main Menu which lets the player choose between new game, loading, or quitting. def main_menu(self): #load the background. img = libtcod.image_load('menu_background.png') #while the window is open, display the menu. while not libtcod.console_is_window_closed(): #show the background image, at twice the regular console resolution libtcod.image_blit_2x(img, 0, 0, 0) #show the game's title and some credits! libtcod.console_set_default_foreground(0, libtcod.light_yellow) libtcod.console_print_ex(0, Screen.SCREEN_WIDTH / 2, Screen.SCREEN_HEIGHT / 2 - 4, libtcod.BKGND_NONE, libtcod.CENTER, 'TOMBS OF THE ANCIENT KINGS') libtcod.console_print_ex(0, Screen.SCREEN_WIDTH / 2, Screen.SCREEN_HEIGHT - 2, libtcod.BKGND_NONE, libtcod.CENTER, 'By Steven') #show options and wait for the player's choice choice = self.screen.menu('', ['Play a new game', 'Continue last game', 'Quit'], 24) if choice == 0: #new game self.new_game() self.play_game() elif choice == 1: #load game try: self.load_game() except: #there's an issue (of some sort) loading the game, so just default to no save game error. self.screen.msgbox('\n No saved game to load!\n', 24) continue #play the loaded game. self.play_game() elif choice == 2: #quit break def respawn_player(self): #assign the player object and add it to the objects tree. self.initialize_new_player() #update the creatures player bindings self.map.update_player_bindings() #set the dungeone_level back to the entrance self.map.dungeon_level = 1
y += amount elif direction == Direction.SOUTHWEST: y += amount x -= amount elif direction == Direction.WEST: x -= amount elif direction == Direction.NORTHWEST: y -= amount x -= amount return (x, y) def is_pos_on_board(self, (x, y)): return (x < self.width and y < self.height and x >= 0 and y >= 0) def get_visible_board(self, (x, y), radius): map = GameMap() map.radius = radius # Loop through each row in the visible circle iRow = 0 dy = y - radius while dy <= y + radius: # Find the desired row while iRow < len(self.rows) and self.rows[iRow][0].get_y() < dy: iRow += 1 # Make sure we don't go beyond the end of the array if iRow == len(self.rows): break # Check to see if we skipped over it (the row we wanted was empty)
def generate_maps(self, num: int, difficulty: int) -> None: """Generates a set number of maps, which are saved to 'maps/'""" for _ in range(num): new_map = GameMap(self.screen_size, self.div, True, difficulty) new_map.write_map()
class Game: def __init__(self): #set everything to default initializations. self.player = None self.player_action = None self.game_state = None self.map = GameMap() self.screen = Screen() self.map.screen = self.screen #Creates a new player. Used when calling a new game, or when the player dies. def initialize_new_player(self): fighter_component = BaseCharacterClass(hp=100, defense=1, power=4) self.player = Player(self.map.orig_player_x, self.map.orig_player_y, '@', 'player', libtcod.white, blocks=True, character_class=fighter_component, screen=self.screen) self.player.equipment['right hand'] = items.Equipment( 0, 0, '/', 'sword', libtcod.light_blue, 'right hand', power_bonus=2) self.map.player = self.player self.map.objects.append(self.player) #Creates a new game, with a new player, and a new map. def new_game(self): #create object representing the player self.initialize_new_player() #generate map (at this point it's not drawn to the screen) and the FOV self.map.make() self.map.initialize_fov() #We're playing now, so send a message. self.game_state = 'playing' self.screen.message( 'Welcome stranger! Prepare to perish in the Tombs of the Ancient Kings.', 'red') #Plays the game, using a loop to capture player input, repaint the screen, etc. def play_game(self): self.player_action = None #capture inputs self.screen.mouse = libtcod.Mouse() self.screen.key = libtcod.Key() #iterate while the console screen is open. while not libtcod.console_is_window_closed(): #check for events. libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, self.screen.key, self.screen.mouse) #render the screen and flush the console. self.screen.render_all(self.map) libtcod.console_flush() #check for levelups self.player.check_level_up() #handle keys and exit game if needed for object in self.map.objects: object.clear(self.screen.con) self.player_action = self.screen.handle_keys( self.game_state, self.player, self.map.objects, self.map) #exit the game if the player select so if self.player_action == 'exit': self.save_game() break #let monsters take their turn if self.game_state == 'playing' and self.player_action != 'didnt-take-turn': for object in self.map.objects: if isinstance( object, Creature ) and object.name != 'player' and not object.dead: #take monster turns and check to see if monsters have killed the player. object.ai.take_turn(self.player, self.map) #if monsters have killed the player, spawn a new player #set it at the original start of the dungeon if self.player.dead: #assign the player object and add it to the objects tree. self.initialize_new_player() #update the creatures player bindings self.map.update_player_bindings() #Saves the game to disk. def save_game(self): #open a new empty shelve (possibly overwriting an old one) to write the game data # file = open('savegame.sav', 'wb') # pickle.dump(self.map, file) # pickle.dump(self.map.objects, file) # pickle.dump(self.player, file) # pickle.dump(self.screen, file) # pickle.dump(self.screen.game_msgs, file) # pickle.dump(self.screen.fov_recompute, file) # pickle.dump(self.screen.fov_map, file) # pickle.dump(self.game_state, file) # pickle.dump(self.map.stairs, file) file = shelve.open('savegame.s', 'n') file['map'] = self.map file['objects'] = self.map.objects file['player'] = self.player file['game_msgs'] = self.screen.game_msgs file['fov_map'] = self.screen.fov_map file['fov_recompute'] = self.screen.fov_recompute file['game_state'] = self.game_state file['stairs'] = self.map.stairs file.close() #Loads the game from disk. def load_game(self): #open the previously saved shelve and load the game data # file = open('savegame.sav', 'rb') # self.map = pickle.load(file) # self.map.objects = pickle.load(file) # self.player = pickle.load(file) # self.map.player = self.player # self.screen = Screen() # self.screen.game_msgs = pickle.load(file) # self.screen.fov_map = pickle.load(file) # self.screen.fov_recompute = pickle.load(file) # self.game_state = pickle.load(file) # self.map.stairs = pickle.load(file) file = shelve.open('savegame.s', 'r') self.map = file['map'] self.map.objects = file['objects'] self.player = file['player'] self.screen.fov_map = file['fov_map'] self.screen.fov_recompute = file['fov_recompute'] self.screen.game_msgs = file['game_msgs'] self.game_state = file['game_state'] self.map.stairs = file['stairs'] file.close() self.map.player = self.player self.map.screen = self.screen self.map.update_player_bindings() self.map.initialize_fov() libtcod.sys_set_fps(self.screen.LIMIT_FPS) #Opens the Main Menu which lets the player choose between new game, loading, or quitting. def main_menu(self): #load the background. img = libtcod.image_load('menu_background.png') #while the window is open, display the menu. while not libtcod.console_is_window_closed(): #show the background image, at twice the regular console resolution libtcod.image_blit_2x(img, 0, 0, 0) #show the game's title and some credits! libtcod.console_set_default_foreground(0, libtcod.light_yellow) libtcod.console_print_ex(0, Screen.SCREEN_WIDTH / 2, Screen.SCREEN_HEIGHT / 2 - 4, libtcod.BKGND_NONE, libtcod.CENTER, 'TOMBS OF THE ANCIENT KINGS') libtcod.console_print_ex(0, Screen.SCREEN_WIDTH / 2, Screen.SCREEN_HEIGHT - 2, libtcod.BKGND_NONE, libtcod.CENTER, 'By Steven') #show options and wait for the player's choice choice = self.screen.menu( '', ['Play a new game', 'Continue last game', 'Quit'], 24) if choice == 0: #new game self.new_game() self.play_game() elif choice == 1: #load game try: self.load_game() except: #there's an issue (of some sort) loading the game, so just default to no save game error. self.screen.msgbox('\n No saved game to load!\n', 24) continue #play the loaded game. self.play_game() elif choice == 2: #quit break def respawn_player(self): #assign the player object and add it to the objects tree. self.initialize_new_player() #update the creatures player bindings self.map.update_player_bindings() #set the dungeone_level back to the entrance self.map.dungeon_level = 1
self.game_end(game.path.move_count) exit_game = True pg.display.flip() self.clock.tick(60) pg.quit() def next_pos(cur_pos: Tuple[int, int], move: str, h_step, v_step) -> Tuple[int, int]: """Helper function for analyzing next position coordinate by a given step""" possible_next_pos = { 'left': (cur_pos[0] - h_step, cur_pos[1]), 'right': (cur_pos[0] + h_step, cur_pos[1]), 'up': (cur_pos[0], cur_pos[1] - v_step), 'down': (cur_pos[0], cur_pos[1] + v_step) } return possible_next_pos[move] if __name__ == "__main__": display = GameDisplay((800, 800)) graph = Graph() ply = Player('Test', (int(20 - 8 / 2), int(400 - 8 / 2)), 20) map1 = GameMap(4, (800, 800), 40, True) p = Path(map1, graph, ply) game = Game(map1, p, ply) display.run_game(game)