def run_ui(): libtcod.console_is_window_closed()
def main_menu(): img = libtcod.image_load(b'img/backgrounds/menu_background.png') 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 libtcod.console_set_default_foreground(0, libtcod.light_yellow) libtcod.console_set_alignment(0, libtcod.CENTER) libtcod.console_print(0, int(round(SCREEN_WIDTH / 2)), int(round(SCREEN_HEIGHT / 2 - 4)), 'THE LEGEND OF THARSA') libtcod.console_print(0, int(round(SCREEN_WIDTH / 2)), int(round(SCREEN_HEIGHT - 2)), 'By Athemis') # Show the options and wait for the player's choice choice = menu('', ['Play a new game', 'Continue last game', 'Quit'], 24) if choice == 0: # New game new_game() play_game() elif choice == 1: # Load last game try: load_game() except: msgbox('\n No saved game to load. \n', 24) continue play_game() elif choice == 2: # Quit break
def play_game(): global key, mouse, game_state, game_msgs, map_state, inventory game_state = 'playing' map_state = 'map' game_msgs = [] inventory = [] equipment_component = Equipment(slot = 'right hand', add_equipment_skill = ('shot', 'reload')) gun = Object(1, 1, '/', 'gun', libtcod.sky, equipment = equipment_component) inventory.append(gun) # initialize the mouse and key with libtcod libaray mouse = libtcod.Mouse() key = libtcod.Key() while not libtcod.console_is_window_closed(): #check the input from the keyboard or mouse libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE, key, mouse) #display all (include the tile and objects) render_all() libtcod.console_flush() #handle the keyboard or mouse input player_action = handle_keys() if player_action == 'exit': break if game_state == 'playing' and player_action != 'didnt-take-turn': for object in objects: if object.ai: object.ai.take_turn()
def storyScreen(console): libtcod.console_set_default_background(console, STORY_BACKGROUND_COLOUR1) libtcod.console_clear(console) done = False counter = 0 blinkOn = True blinkSpeed = 10 while not done and not libtcod.console_is_window_closed(): key = libtcod.console_check_for_keypress(True) if not key.vk == libtcod.KEY_NONE: done = True #print the story message libtcod.console_set_default_foreground(console, STORY_FOREGROUND_COLOUR1) libtcod.console_print_rect(console, 1, 3, SCREEN_WIDTH, SCREEN_HEIGHT, STORY_TEXT1) if(blinkOn): libtcod.console_set_default_foreground(console, SPLASH_FOREGROUND_COLOUR3) libtcod.console_print_rect(console, 16, 22, SCREEN_WIDTH, SCREEN_HEIGHT, "press any key") # blit the panel to the screen libtcod.console_blit(console, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-(2*1), 0, 0, 1) libtcod.console_flush() counter += 1 if counter >= blinkSpeed: counter = 0 blinkOn = not blinkOn libtcod.console_clear(console) libtcod.console_clear(console)
def play_game(): player_action = None while not libtcod.console_is_window_closed(): # Render the screen render_all() libtcod.console_flush() check_level_up() # Erease all objects at their old locations, befor they move for object in objects: object.clear() # Handle keys and exit if needed player_action = handle_keys() if player_action == 'exit': save_game() # Save the current game before exit break # Let the monsters take their turn if game_state == 'playing': for object in objects: if object.ai: # Don't take a turn yet if still waiting if object.wait > 0: object.wait -= 1 else: object.ai.take_turn()
def main_menu(): while not libtcod.console_is_window_closed(): libtcod.console_disable_keyboard_repeat() libtcod.console_set_default_background(0, libtcod.black) libtcod.console_set_default_foreground(0, libtcod.black) libtcod.console_clear(0) # Show the game's title, and some credits! libtcod.console_set_default_foreground(0, libtcod.light_yellow) libtcod.console_print_ex(0, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 4, libtcod.BKGND_NONE, libtcod.CENTER, 'BALL LABYRINTH') libtcod.console_print_ex(0, SCREEN_WIDTH / 2, SCREEN_HEIGHT - 2, libtcod.BKGND_NONE, libtcod.CENTER, 'By Eric Williams') # Show options and wait for the player's choice. choice = menu('', ['Play a new game', 'Load saved game', 'Play custom level', 'Quit'], 24) if choice == 0: # New game. new_game() libtcod.console_set_keyboard_repeat(5, 5) play_game() elif choice == 1: # Load saved game. loaded = load_game() if loaded: libtcod.console_set_keyboard_repeat(5, 5) play_game() elif choice == 2: # Open the test arena level. custom = new_custom_game() if custom: libtcod.console_set_keyboard_repeat(5, 5) play_game() elif choice == 3: # Quit. break
def showDebugScreen(self): # store the current view behind_window = libtcod.console_new(SCREEN_WIDTH, SCREEN_HEIGHT) libtcod.console_blit(0, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, behind_window, 0, 0, 1.0, 1.0) # show the background image, at twice the regular console resolution img = libtcod.image_load("./media/menu_debug.png") libtcod.image_blit_2x(img, 0, 0, 0) while not libtcod.console_is_window_closed(): # show options and wait for the player's choice choice = self.showMenu( "Select debug option:", ["Run some test code!", "Show me some game stuff!", "Back"], # Choice 0 # Choice 1 # Choice 2 36, ) # interpret choice if choice is None: continue if choice == 0: print "Running some test code!" self.runTestCode() self.showMessage("Test code complete!", "There might be some output in the console...", 36) continue elif choice == 1: print "Showing some game stuff!" self.newGame() self.showGameScreen() elif choice == 2: # quit print "Back" break # Clean up (restore whatever was behind this window) libtcod.console_blit(behind_window, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0, 1.0, 1.0) libtcod.console_flush()
def story_slide(): img = libtcod.image_load('menu_background2.png') if dungeon_level == 0: level_subtitle = 'LEVEL 0' elif dungeon_level == 1: level_subtitle = 'LEVEL 1' elif dungeon_level == 2: level_subtitle = 'BEFORE THE STARDUST FADES' elif dungeon_level == 3: level_subtitle = 'WISH UPON THE DIAMOND DUST' 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_WIDTH/2, SCREEN_HEIGHT/2-6, libtcod.BKGND_NONE, libtcod.CENTER, 'CHAPTER '+str(dungeon_level)) libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2-4, libtcod.BKGND_NONE, libtcod.CENTER, level_subtitle) libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT-2-2, libtcod.BKGND_NONE, libtcod.CENTER, '- w5748 -') #show options and wait for the player's choice choice = menu('', ['PROCEED'], 11) if choice == 0: #PROCEED PATH, THINK ABOUT A save_game() ROUTE break elif choice == 1: break
def play_game(): player_action = None while not libtcod.console_is_window_closed(): # Render the screen. render_all() libtcod.console_flush() # Clean the console. libtcod.console_clear(con) # Handle keys and exit game if needed. player_action = handle_keys() if player_action == 'exit': break # Let the monsters take their turn. if game_state == 'playing' or game_state == 'custom playing': for object in objects: if object.ai: if object.wait > 0: object.wait -= 1 else: object.ai.take_turn() object.wait = object.speed
def play_game(): global key, mouse player_action = None mouse = libtcod.Mouse() key = libtcod.Key() #main loop while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) #render the screen render_all() libtcod.console_flush() #level up if needed check_level_up() #erase all objects at their old locations, before they move for object in objects: object.clear() #handle keys and exit game if needed player_action = handle_keys() if player_action == 'exit': save_game() break #let monsters take their turn if game_state == 'playing' and player_action != 'didnt-take-turn': for object in objects: if object.ai: object.ai.take_turn()
def main_menu(): img = libtcod.image_load('menu_background.png') 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_red) libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2-8, libtcod.BKGND_NONE, libtcod.CENTER, 'R- U- N-') libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2-6, libtcod.BKGND_NONE, libtcod.CENTER, 'Something cool') libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT-2-2, libtcod.BKGND_NONE, libtcod.CENTER, '- w5748 -') #show options and wait for the player's choice choice = menu('', ['New Game', 'Load File', 'Quit'], 24) if choice == 0: #new game new_game() play_game() if choice == 1: #load last game try: load_game() except: msgbox('\n No saved game to load.\n', 24) continue play_game() elif choice == 2: #quit break
def play_game(self): """Where's the game @.""" #Start main loop while not libtcod.console_is_window_closed(): self.player_action = None render_all() #render stuff libtcod.console_flush() #refresh the console #erase before move for ent in self.entities: ent.clear() #import keys handling self.player_action = handle_keys() if self.player_action == None: self.player_action = 'didnt-take-turn' if self.player_action == 'exit': #if pressing a key returns 'exit' - close the window break #'AI' takes turns if self.gamestate == 'playing' and self.player_action != 'didnt-take-turn' or Game.gamemode == 'RT': for ent in self.entities: if ent.ai: ent.ai.take_turn() if ent.killer and ent.x == self.player.x and ent.y == self.player.y: player_death() elif ent.point and ent.x == self.player.x and ent.y == self.player.y: self.score += 1 ent.clear() Game.entities.remove(ent) spawn_points()
def play_game(): global key, mouse, game_state player_action = None mouse = libtcod.Mouse() key = libtcod.Key() while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE, key, mouse) render_all() libtcod.console_flush() player.player.check_level_up() for object in objects: object.clear() if game_state == 'playing-waiting-for-input' or game_state == 'dead': player_action = handle_keys() #print "player_action: %s" % player_action if player_action == 'exit': save_game() break elif player_action is None: game_state = 'playing' if game_state == 'playing': scheduler.tick()
def main_menu(): img = libtcod.image_load('rltutBackdrop.png') while not libtcod.console_is_window_closed(): #libtcod.image_blit(img, 0, 0, 0) #show the background image at twice the regular console resolution libtcod.image_blit_2x(img, 0, 0, 0) #show game's title and some credits libtcod.console_set_default_foreground(0, libtcod.light_yellow) libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2-4, libtcod.BKGND_NONE, libtcod.CENTER, MAIN_TITLE) libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT-2, libtcod.BKGND_NONE, libtcod.CENTER, 'by Austin McGee') #print controls libtcod.console_print_ex(0, 1, 1, libtcod.BKGND_NONE, libtcod.LEFT, CONTROLS_TEXT) #show options and wait for the player's choice choice = menu('', ['Play a new game', 'Continue last game', 'Quit'], 24) if choice == 0: #new game new_game() play_game() if choice == 1: #load last game try: load_game() except: msgbox('\n No saved game to load.\n', 24) continue play_game() elif choice == 2: #quit break
def main_menu(self): """THE main menu, no other.""" LIMIT_FPS = 20 libtcod.sys_set_fps(LIMIT_FPS) img = libtcod.image_load('main/lazor.png') 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 credits libtcod.console_set_default_foreground(0, color_menu_text) libtcod.console_print_ex(0, SCREEN_WIDTH/2, 1, libtcod.BKGND_NONE, libtcod.CENTER, 'Laz0r Dodging Game') libtcod.console_print_ex(0, SCREEN_WIDTH/2, 2, libtcod.BKGND_NONE, libtcod.CENTER, 'by magikmw') #show options and wait for the player's choice choice = menu('Choose an option:\n', ['Real-Time', 'Turn-Based', 'Highscores', 'Help', 'Quit.'], 18, -10) if choice == 0: #new game self.new_game('RT') if choice == 1: self.new_game('TB') if choice == 2: #TODO the highscore function call here pass if choice == 3: #TODO help screen funcion call here pass if choice == 4: #quit break
def main_menu(): img = libtcod.image_load('menu_background.png') 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_WIDTH/2, SCREEN_HEIGHT/2-4, libtcod.BKGND_NONE, libtcod.CENTER, 'TOMBS OF THE ANCIENT KINGS') libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT-2, libtcod.BKGND_NONE, libtcod.CENTER, 'By Jotaf') #show options and wait for the player's choice choice = menu('', ['Play a new game', 'Continue last game', 'Quit'], 24) if choice == 0: #new game new_game() play_game() if choice == 1: #load last game try: load_game() except: msgbox('\n No saved game to load.\n', 24) continue play_game() elif choice == 2: #quit break
def play_game(): global key, mouse player_action = None mouse = libtcod.Mouse() key = libtcod.Key() #main loop while not libtcod.console_is_window_closed(): #print to screen zero is the console to be printed to #libtcod.console_set_default_foreground(0, libtcod.crimson) #print character #libtcod.console_put_char(con,playerx,playery, '@', libtcod.BKGND_NONE) libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE,key, mouse) render_all() #flush console(present changes to console) libtcod.console_flush() #check for player level up check_level_up() for object in objects: object.clear() #handle keys and exit game if needed player_action = handle_keys() if player_action == 'exit': save_game() break #let monsters take their turn if game_state == 'playing' and player_action != 'turnNotTaken': for object in objects: if object.ai: object.ai.take_turn()
def main_menu(): img = libtcod.image_load('menu_background.png') while not libtcod.console_is_window_closed(): #show the menu image in a terrible way libtcod.image_blit_2x(img, 0, 0, 0) #fancy main menu title and crediting libtcod.console_set_default_foreground(0, libtcod.white) libtcod.console_set_default_background(0, libtcod.black) libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2-4, libtcod.BKGND_ALPHA(0.7), libtcod.CENTER, 'JOTAF\'S COMPLETE ROGUELIKE TUTORIAL,') libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2-3, libtcod.BKGND_ALPHA(0.7), libtcod.CENTER, 'USING PYTHON+LIBTCOD') #libtcod.console_print_ex(0, SCREEN_WIDTH/2, SCREEN_HEIGHT-2, libtcod.BKGND_ALPHA(0.7), libtcod.CENTER, 'Implemented By') #show main menu optionss and request selection choice = menu('', ['Play a new game', 'Continue last game', 'Quit'], 24) #fullscreen toggle needs to work in main menu too #if key.vk == libtcod.KEY_ENTER and key.lalt: # libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) if choice == 0: #new game new_game() play_game() elif choice == 1: #load game try: load_game() except: msgbox('\n No saved game to load.\n', 24) continue play_game() elif choice == 2: #quit break
def main_menu(): img = libtcod.image_load('img/menu_background1.png') while not libtcod.console_is_window_closed(): Renderer.render_main_screen(img) choice = Renderer.menu('', ['Play a new game', 'Continue current game', 'Quit'], 24, 0) if choice == 0: Renderer.render_main_screen(img) races = race_decoder.decode_all_races() race = Renderer.menu('Pick a race', races, 15, 0) if race is None: continue Renderer.render_main_screen(img) jobs = job_decoder.decode_all_jobs() job = Renderer.menu('Pick a job', jobs, 15, 0) if job is None: continue Game.new_game(races[race].lower(), jobs[job].lower()) Game.run() elif choice == 1: try: Game.run() except: Game.msgbox('\n No saved game to load.\n', 24) continue elif choice == 2: break
def main_menu(): #Set up the main menu, which is presented to the player when they first load the game img = libtcod.image_load('images/menu_background1.png') while not libtcod.console_is_window_closed(): #Show the image at twice its usual resolution of the console libtcod.image_blit_2x(img, 0, SCREEN_WIDTH / 6, SCREEN_HEIGHT / 6) #Show the games title, and some credits libtcod.console_set_default_foreground(0, libtcod.light_yellow) libtcod.console_print_ex(0, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 4, libtcod.BKGND_NONE, libtcod.CENTER, 'DUNGEONCRAWLER') libtcod.console_print_ex(0, SCREEN_WIDTH / 2, SCREEN_HEIGHT - 2, libtcod.BKGND_NONE, libtcod.CENTER, 'By Jeremy Cerise') #Show menu options and wait for the players choice choice = menu('', ['Play a new game', 'Continue last game', 'Quit'], 24) if choice == 0: #Start a new game #Clear the base conosle, so the menu image and options don't show up under the rest of the UI libtcod.console_set_default_background(0, libtcod.brass) libtcod.console_clear(0) new_game() play_game() elif choice == 1: try: libtcod.console_set_default_background(0, libtcod.brass) libtcod.console_clear(0) load_game() except: msgbox('\n No saved game to load!\n', 24) elif choice == 2: #Exit the program break;
def play_game(): global key, mouse player_action = None mouse = libtcod.Mouse() key = libtcod.Key() while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE,key,mouse) render_all() libtcod.console_flush() #check for player level up now, while objects are visible behind the menu check_level_up() #erase all objects after render in case they move before next flush for object in objects: object.clear() #handle player input and exit game if appropriate player_action = handle_keys() if player_action == 'exit': save_game() break #give monsters 1 turn for all player turns taken if game_state == 'playing' and player_action != 'didnt-take-turn': for object in objects: if object.ai: object.ai.take_turn()
def main_menu(): main_init() while not libtcod.console_is_window_closed(): #now show the imageAt twice the size. libtcod.console_set_default_foreground(0, libtcod.light_yellow) libtcod.console_print_ex(0, R.SCREEN_WIDTH / 2, R.SCREEN_HEIGHT / 2 - 4, libtcod.BKGND_NONE, libtcod.CENTER, 'Trader-RL') libtcod.console_print_ex(0, R.SCREEN_WIDTH / 2, R.SCREEN_HEIGHT - 2, libtcod.BKGND_NONE, libtcod.CENTER, 'By Lemmily') choice = R.ui.menu("", ["Play a new game", "Continue last game", "Quit"], 24) if choice == 0: #new game #game_screen_init() new_game() play_game() #msgbox("Hey there") elif choice == 1: try: load_game() except: R.ui.msgbox("\n No saved game to load. \n", 24) continue play_game() elif choice == 2: break
def play_game(): settings.player_action = None settings.mouse = libtcod.Mouse() settings.key = libtcod.Key() while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, settings.key, settings.mouse) render_all() libtcod.console_flush() check_level_up() for object in settings.objects: object.clear() settings.player_action = handle_keys() if settings.player_action == 'exit': save_game() break if settings.game_state == 'playing' and \ settings.player_action != 'didnt-take-turn': for object in settings.objects: if object.ai: object.ai.take_turn()
def play_game(): global fov_recompute player_action = None while not libtcod.console_is_window_closed(): # render the screen render_all() libtcod.console_flush() # level up if needed check_level_up() # erase all objects at their old locations, before they move for object in objects: object.clear() # handle keys and exit game if needed player_action = handle_keys() if player_action == 'exit': save_game() break # let monsters take their turn if game_state == 'playing' and player_action != 'didnt-take-turn': for object in objects: if object.ai: object.ai.take_turn() generate_mana(5) fov_recompute = True
def main_menu(): img = libtcod.image_load('title.png') 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.black) libtcod.console_print_ex(0, SCREEN_WIDTH / 2, int(SCREEN_HEIGHT * .75), libtcod.BKGND_NONE, libtcod.CENTER, 'WizRL') libtcod.console_print_ex(0, SCREEN_WIDTH / 2, int(SCREEN_HEIGHT * .75) + 2, libtcod.BKGND_NONE, libtcod.CENTER, 'By Dragyn') # show options and wait for the player's choice choice = menu('', ['Play a new game', 'Continue last game', 'Quit'], 24) if choice == 0: # new game libtcod.console_clear(0) new_game() play_game() if choice == 1: # load last game try: load_game() except: msgbox('\n No saved game to load.\n', 24) continue play_game() elif choice == 2: # quit break
def main_menu(): img = libtcod.image_load('menu_background1.png') 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_foreground_color(0, libtcod.black) libtcod.console_print_center(0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2-4, libtcod.BKGND_NONE, 'P U R G A T O R I O') libtcod.console_set_foreground_color(0, libtcod.white) libtcod.console_print_center(0, SCREEN_WIDTH/2, SCREEN_HEIGHT-2, libtcod.BKGND_NONE, 'By CitizenArcane') #show options and wait for the player's choice choice = menu(' ', ['Play a new game', 'Continue last game', 'Quit'], 24) if choice == 0: #new game new_game() play_game() elif choice == 1: #load last game try: load_game() except: msgbox('\n No saved game to load. \n', 24) continue play_game() elif choice == 2: #quit break
def main_menu(new_game, play_game, load_game): """ Prompt the player to start a new game, continue playing the last game, or exit. """ img = libtcod.image_load('menu_background.png') 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) libtcod.console_set_default_foreground(0, libtcod.light_yellow) libtcod.console_print_ex( 0, config.SCREEN_WIDTH/2, config.SCREEN_HEIGHT/2-4, libtcod.BKGND_NONE, libtcod.CENTER, 'TOMBS OF THE ANCIENT KINGS') libtcod.console_print_ex( 0, config.SCREEN_WIDTH/2, config.SCREEN_HEIGHT-2, libtcod.BKGND_NONE, libtcod.CENTER, 'By Jotaf') (char, choice) = menu('', ['Play a new game', 'Continue last game', 'Quit'], 24) if choice == 0: play_game(new_game()) if choice == 1: try: player = load_game() except: msgbox('\n No saved game to load.\n', 24) continue play_game(player) elif choice == 2: break
def play_game(): global key, mouse player_action = None while not libtcod.console_is_window_closed(): #render the screen libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE, key, mouse) render_all() libtcod.console_flush() #level up if needed check_level_up() #erase all objects at their old locations before they move for object in objects: object.clear() #handle keys and exit game if needed player_action = handle_keys() if player_action == 'exit': save_game() break #let monsters take their turn if game_state == 'playing': for object in objects: if object.ai: if object.wait > 0: #don't take a turn if still waiting object.wait -= 1 else: object.ai.take_turn()
def play_game(): player_action = None # Main loop while not libtcod.console_is_window_closed(): # draw render_all() # flush data to screen libtcod.console_flush() # clear all objects for object in objects: object.clear() # handle keys and exit game if needed player_action = handle_keys() if player_action == 'exit': save_game() break # let monsters take their turn if game_state == 'playing' and player_action != 'didnt-take-turn': for object in objects: if object.ai: object.ai.take_turn()
def main_menu(): img = libtcod.image_load('menu_background.png') 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_foreground_color(0, libtcod.light_yellow) libtcod.console_print_center(0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2-4, libtcod.BKGND_NONE, 'Rogue-LIKE!') libtcod.console_print_center(0, SCREEN_WIDTH/2, SCREEN_HEIGHT-2, libtcod.BKGND_NONE, 'By RobBbot') #show options and wait for the player's choice choice = menu('', ['Play a new game', 'Continue last game', 'Controls', 'Quit'], 24) if choice == 0: #new game new_game() play_game() if choice == 1: #load last game try: load_game() except: msgbox('\n No saved game to load.\n', 24) continue play_game() elif choice == 2: msgbox('\n "g" will pickup items\n\n "i" will bring up your inventory \n\n "d" will drop an item on the ground\n\n Arrow keys move the @ around\n\n Casting Spells requires you to click on the\n mob you want to target after selecting \n the scroll from your inventory') elif choice == 3: #quit break
def menu(header, options, width, numbers=False): if numbers: if len(options) > 9: raise ValueError('Cannot have a menu with more than 9 options.') else: if len(options) > 26: raise ValueError('Cannot have a menu with more than 26 options.') #calculate total height for the header (after auto-wrap) and one line per option header_height = libtcod.console_get_height_rect(cfg.con, 0, 0, width, cfg.SCREEN_HEIGHT, header) if header == '': header_height = 0 height = len(options) + header_height #create an off-screen console that represents the menu's window window = libtcod.console_new(width, height) #print the header, with auto-wrap libtcod.console_set_default_foreground(window, libtcod.white) libtcod.console_print_rect_ex(window, 0, 0, width, height, libtcod.BKGND_NONE, libtcod.LEFT, header) #print all the options y = header_height if numbers: letter_index = ord('1') else: letter_index = ord('a') for option_text in options: text = '(' + chr(letter_index) + ') ' + option_text libtcod.console_print_ex(window, 0, y, libtcod.BKGND_NONE, libtcod.LEFT, text) y += 1 letter_index += 1 #blit the contents of "window" to the root console x = cfg.SCREEN_WIDTH / 2 - width / 2 y = cfg.SCREEN_HEIGHT / 2 - height / 2 libtcod.console_blit(window, 0, 0, width, height, 0, x, y, 1.0, 0.85) #compute x and y offsets to convert console position to menu position x_offset = x #x is the left edge of the menu y_offset = y + header_height #subtract the height of the header from the top edge of the menu while True: #present the root console to the player and check for input libtcod.console_flush() libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, cfg.key, cfg.mouse) if (cfg.mouse.lbutton_pressed): (menu_x, menu_y) = (cfg.mouse.cx - x_offset, cfg.mouse.cy - y_offset) #check if click is within the menu and on a choice if menu_x >= 0 and menu_x < width and menu_y >= 0 and menu_y < height - header_height: return menu_y if cfg.mouse.rbutton_pressed or cfg.key.vk == libtcod.KEY_ESCAPE: return None #cancel if the player right-clicked or pressed Escape if cfg.key.vk == libtcod.KEY_ENTER and cfg.key.lalt: #Alt+Enter: toggle fullscreen libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) #convert the ASCII code to an index; if it corresponds to an option, return it if numbers: index = cfg.key.c - ord('1') else: index = cfg.key.c - ord('a') if index >= 0 and index < len(options): return index #if they pressed a letter that is not an option, return None #also return none if the window gets closed if cfg.key.c >= 7 or libtcod.console_is_window_closed(): return None
def main(): # Screen settings screen_width = 80 screen_height = 45 # Map creation settings map_width = 80 map_height = 45 # Room creation settings room_max_size = 10 room_min_size = 6 max_rooms = 30 # FOV settings - passed to libtcod library fov_algorithm = 0 fov_light_walls = True fov_radius = 10 # Color Dictionary for entities colors = { 'dark_wall': libtcod.Color(0, 0, 100), 'dark_ground': libtcod.Color(50, 50, 150), 'light_wall': libtcod.Color(130, 110, 50), 'light_ground': libtcod.Color(200, 180, 50) } # Create player entity and entities list - monsters appended at map creation max_monsters_per_room = 3 player = Entity(0, 0, '@', libtcod.white, 'my dude', blocks=True) entities = [player] # Console settings and initialisation libtcod.console_set_custom_font( 'arial10x10.png', libtcod.FONT_TYPE_GRAYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(screen_width, screen_height, 'libtcod tutorial revised', False) # Set up the console con = libtcod.console_new(screen_width, screen_height) # Create the map object and trigger dungeon creation game_map = GameMap(map_width, map_height) game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities, max_monsters_per_room) fov_recompute = True fov_map = initialize_fov(game_map) # Controller mappings key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYERS_TURN # Main Loop while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse) if fov_recompute: recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) render_all(con, entities, game_map, fov_map, fov_recompute, screen_width, screen_height, colors) # TODO - wouldn't it make more sense to move this under recompute_fov() call? fov_recompute = False libtcod.console_flush() clear_all(con, entities) action = handle_keys(key) move = action.get('move') exit = action.get('exit') fullscreen = action.get('fullscreen') if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: print('You kick the ' + target.name + ' squarely in the nards, much to its dismay') else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN if exit: return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen) if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity != player: print('The ' + entity.name + ' scratches itself in an unpleasant fashion.') game_state = GameStates.PLAYERS_TURN
def main(): # Initial Game Settings screen_width = 80 screen_height = 50 # Map size map_width = 80 map_height = 45 # Field-Of-View settings fov_radius = 10 # Display-field colors colors = { 'dark_wall': libtcod.Color(0, 0, 100), 'dark_ground': libtcod.Color(50, 50, 150), 'light_wall': libtcod.Color(130, 110, 50), 'light_ground': libtcod.Color(200, 180, 50) } # Setup libtcod output console libtcod.console_set_custom_font( 'arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(screen_width, screen_height, 'Warrens', False) con = libtcod.console_new(screen_width, screen_height) # Initialize and generate game map game_map = GameMap(map_width, map_height, initialize_tiles) game_map = make_map(game_map, 5, 10, 20) seed_ore(game_map, iron_ore) # Field-of-view setup fov_recompute = True fov_map = ShadowcastMap(game_map) # Initialize Player player = Entity(game_map.player_start_x, game_map.player_start_y, '@', libtcod.white, "Player", blocks=True, render_order=RenderOrder.ACTOR) player.add_component(Creature(25, 5, 5, 0)) player.add_component(Storage('Inventory', 100)) # Add starting entities to map game_map.entities.append(player) key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYER_TURN # Main game loop while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse) if fov_recompute: fov_map.recalculate_fov(player.x, player.y, fov_radius) render_all(con, game_map.entities, game_map, fov_map, fov_recompute, screen_width, screen_height, colors) libtcod.console_flush() clear_all(con, game_map.entities) libtcod.console_put_char(con, player.x, player.y, ' ', libtcod.BKGND_NONE) action = handle_keys(key) move = action.get('move') esc = action.get('esc') fullscreen = action.get('fullscreen') resources = None if move and game_state == GameStates.PLAYER_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if game_map.point_in_map(destination_x, destination_y): if game_map.is_blocked(destination_x, destination_y): resources = game_map.dig(player.x + dx, player.y + dy) else: target = game_map.get_blocking_entities_at_location( destination_x, destination_y) if target: print('You kick the {0} in the shin.'.format( target.name)) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN if resources: for resource in resources: status_list = player.components['Inventory'].add_resource( resource) for status in status_list: if status.get('item_status', 'none') == 'rejected': resource_drop = Entity(player.x, player.y, '$', libtcod.white, "Player", resource=resource) game_map.entities.append(resource_drop) if esc: return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) if game_state == GameStates.ENEMY_TURN: for entity in game_map.entities: if entity != player: print('The {0} waits...'.format(entity.name)) game_state = GameStates.PLAYER_TURN
def main(): screen_width = 80 screen_height = 50 bar_width = 20 panel_height = 7 panel_y = screen_height - panel_height message_x = bar_width + 2 message_width = screen_width - bar_width - 2 message_height = panel_height - 1 map_width = 80 map_height = 43 room_max_size = 10 room_min_size = 6 max_rooms = 30 fov_algorithm = 0 fov_light_walls = True fov_radius = 10 max_monsters_per_room = 3 max_items_per_room = 2 colors = { 'dark wall': libtcod.Color(0, 0, 100), 'dark ground': libtcod.Color(50, 50, 150), 'light wall': libtcod.Color(130, 110, 50), 'light ground': libtcod.Color(200, 180, 50) } 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] libtcod.console_set_custom_font( 'arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(screen_width, screen_height, 'Progue', False) con = libtcod.console_new(screen_width, screen_height) panel = libtcod.console_new(screen_width, panel_height) game_map = GameMap(map_width, map_height) game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities, max_monsters_per_room, max_items_per_room) fov_recompute = True fov_map = initialize_fov(game_map) message_log = MessageLog(message_x, message_width, message_height) key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYERS_TURN previous_game_state = game_state # Game Loop while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) if fov_recompute: recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, screen_width, screen_height, bar_width, panel_height, panel_y, mouse, colors, game_state) fov_recompute = False libtcod.console_flush() clear_all(con, entities) action = handle_keys(key, game_state) move = action.get('move') pickup = action.get('pickup') show_inventory = action.get('show_inventory') drop_inventory = action.get('drop_inventory') inventory_index = action.get('inventory_index') exit = action.get('exit') fullscreen = action.get('fullscreen') player_turn_results = [] if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: attack_results = player.fighter.attack(target) player_turn_results.extend(attack_results) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN elif pickup and game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.item and entity.x == player.x and entity.y == player.y: pickup_results = player.inventory.add_item(entity) player_turn_results.extend(pickup_results) break else: message_log.add_message( Message('There is nothing here to pick up.', libtcod.yellow)) if show_inventory: previous_game_state = game_state game_state = GameStates.SHOW_INVENTORY if drop_inventory: previous_game_state = game_state game_state = GameStates.DROP_INVENTORY if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len( player.inventory.items): item = player.inventory.items[inventory_index] if game_state == GameStates.SHOW_INVENTORY: player_turn_results.extend(player.inventory.use(item)) elif game_state == GameStates.DROP_INVENTORY: player_turn_results.extend(player.inventory.drop_item(item)) if exit: if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY): game_state = previous_game_state else: return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') item_added = player_turn_result.get('item_added') item_consumed = player_turn_result.get('consumed') item_dropped = player_turn_result.get('item dropped') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if item_added: entities.remove(item_added) game_state = GameStates.ENEMY_TURN if item_consumed: game_state = GameStates.ENEMY_TURN if item_dropped: entities.append(item_dropped) game_state = GameStates.ENEMY_TURN if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn( player, fov_map, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYERS_TURN
def main(): # Variables that define the screen size. screen_width = 80 screen_height = 50 bar_width = 20 panel_height = 7 panel_y = screen_height - panel_height message_x = bar_width + 2 message_width = screen_width - bar_width - 2 message_height = panel_height - 1 map_width = 80 map_height = 43 room_max_size = 10 room_min_size = 6 max_rooms = 30 fov_algorithm = 0 fov_light_walls = True fov_radius = 10 max_monsters_per_room = 3 colors = { 'dark_wall': libtcod.Color(0, 0, 100), 'dark_ground': libtcod.Color(50, 50, 150), 'light_wall': libtcod.Color(130, 110, 50), 'light_ground': libtcod.Color(200, 180, 50) } fighter_component = Fighter(hp=30, defense=2, power=5) # Keeps track of the player's position at all times. player = Entity(0, 0, '@', libtcod.white, 'Player', blocks=True, render_order=RenderOrder.ACTOR, fighter=fighter_component) entities = [player] # Tells libtcod which font to use. libtcod.console_set_custom_font( 'arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) # Creates the screen with a title. libtcod.console_init_root(screen_width, screen_height, 'AngrealRL version T0.01', False) con = libtcod.console_new(screen_width, screen_height) panel = libtcod.console_new(screen_width, panel_height) game_map = GameMap(map_width, map_height) game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities, max_monsters_per_room) fov_recompute = True fov_map = initialize_fov(game_map) message_log = MessageLog(message_x, message_width, message_height) # Variables that hold the keyboard and mouse inputs. key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYER_TURN # Game loop that will only end if the screen is closed. while not libtcod.console_is_window_closed(): # Captures new 'events' (user inputs). libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse) if fov_recompute: recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) # Print the '@' symbol, set it to the position set by two parameters and set the backgroung to 'none'. render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, screen_width, screen_height, bar_width, panel_height, panel_y, mouse, colors) fov_recompute = False libtcod.console_flush() clear_all(con, entities) # Allow the game to be 'gracefully' closed by hitting the ESC key. action = handle_keys(key) move = action.get('move') exit = action.get('exit') fullscreen = action.get('fullscreen') player_turn_results = [] if move and game_state == GameStates.PLAYER_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: attack_results = player.fighter.attack(target) player_turn_results = player.fighter.attack(target) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN if exit: return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn( player, fov_map, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') # If the entity dies, changes the enemy status to 'dead' dead_entity = enemy_turn_result.get('dead') if message: print(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) print(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYER_TURN
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 fov_algorithm = 0 fov_light_walls = True fov_radius = 10 max_monsters_per_room = 3 colors = { 'dark_wall': libtcod.Color(0, 0, 100), 'dark_ground': libtcod.Color(50, 50, 150), 'light_wall': libtcod.Color(130, 110, 50), 'light_ground': libtcod.Color(200, 180, 50) } player = Entity(0, 0, '@', libtcod.white, 'Player', blocks=True) entities = [player] libtcod.console_set_custom_font( 'arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(screen_width, screen_height, 'First RL', False) con = libtcod.console_new(screen_width, screen_height) game_map = GameMap(map_width, map_height) game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities, max_monsters_per_room) fov_recompute = True fov_map = initialize_fov(game_map) key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYERS_TURN while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse) if fov_recompute: recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) render_all(con, entities, game_map, fov_map, fov_recompute, screen_width, screen_height, colors) fov_recompute = False libtcod.console_flush() clear_all(con, entities) action = handle_keys(key) move = action.get('move') exit = action.get('exit') fullscreen = action.get('fullscreen') if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: print('You kick the ' + target.name + ' in the shins, much to its annoyance!') else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN if exit: return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity != player: print('The ' + entity.name + ' ponders the meaning of its existence.') game_state = GameStates.PLAYERS_TURN
def main(renderer, game_map, player, logger, turn_based=True): # Game state and player's last action game_state = PLAYING player_action = None # Track mouse and keys mouse = tcod.Mouse() key = tcod.Key() # Game loop while not tcod.console_is_window_closed(): # check for events tcod.sys_check_for_event(tcod.EVENT_KEY_PRESS | tcod.EVENT_MOUSE, key, mouse) # sort objects in level to draw first corpses game_map.level_objects = [ o for o in game_map.level_objects if o.fighter is None ] + [ o for o in game_map.level_objects if o.fighter is not None ] objects = game_map.level_objects + [player] # key = get_key_event(turn_based) player_action = player.handle_keys(game_map, game_state, key) if player_action == SHOW_INVENTORY: chosen_item = renderer.render_inventory_menu( 'Press the key next to an item to use it, or any other to cancel.\n', player.inventory ) if chosen_item is not None: # player = kwargs['player'] # game_map = kwargs['game_map'] # renderer = kwargs['renderer'] # names_under_mouse = kwargs['names_under_mouse'] # show_map_chars = kwargs['show_map_chars'] # mouse = kwargs['mouse'] # key = kwargs['key'] chosen_item.use( player.inventory, player=player, game_map=game_map, mouse=mouse, renderer=renderer, key=key, names_under_mouse=get_names_under_mouse(mouse, game_map), show_map_chars=False ) elif player_action == DROP_ITEM: # show the inventory; if an item is selected, drop it chosen_item = renderer.render_inventory_menu( 'Press the key next to an item to drop it, or any other to cancel.\n', player.inventory ) if chosen_item is not None: chosen_item.drop(player.inventory, game_map, player) elif player_action == SHOW_STATUS: level_up_xp = LEVEL_UP_BASE + player.level * LEVEL_UP_FACTOR renderer.msgbox('Character Information\n\nLevel: ' + str(player.level) + '\nExperience: ' + str(player.fighter.xp) + '\nExperience to level up: ' + str(level_up_xp) + '\n\nMaximum HP: ' + str(player.fighter.max_hp) + '\nAttack: ' + str(player.fighter.power) + '\nDefense: ' + str(player.fighter.defense), CHARACTER_SCREEN_WIDTH) if key.vk == tcod.KEY_ENTER and key.lalt: #Alt+Enter: toggle fullscreen tcod.console_set_fullscreen(not tcod.console_is_fullscreen()) elif key.vk == tcod.KEY_ESCAPE: # go to main menu choice = renderer.render_main_menu() if choice == NEW_GAME: logger.clear_messages() game_map, player = new_game(logger, renderer) game_state = PLAYING player_action = None names_under_mouse = get_names_under_mouse(mouse, game_map) game_map.level_objects = [ o for o in game_map.level_objects if o.fighter is None ] + [ o for o in game_map.level_objects if o.fighter is not None ] renderer.render_all(game_map.level_objects + [player], game_map, names_under_mouse, show_map_chars=False) elif choice == LOAD_GAME: try: player, game_state = load_game(game_map, logger) renderer.render_all(game_map.level_objects + [player], game_map, names_under_mouse, show_map_chars=False) except: renderer.msgbox('\n No saved game to load.\n', 24) elif choice == EXIT_GAME: break # let monsters take their turn if the player did if game_state == PLAYING and player_action != DIDNT_TAKE_TURN: for o in objects: if o != player and o.ai: o.ai.take_turn(game_map, player) # Update game state with player death game_state = player.state names_under_mouse = get_names_under_mouse(mouse, game_map) renderer.render_all(objects, game_map, names_under_mouse, show_map_chars=False) # check level up if player.check_level_up(): renderer.render_level_up(player) save_game(game_map, game_state, player, logger)
def play_game(player, entities, game_map, message_log, game_state, con, panel, constants): fov_recompute = True fov_map = initialize_fov(game_map) key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYERS_TURN previous_game_state = game_state targeting_item = None while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) if fov_recompute: recompute_fov(fov_map, player.x, player.y, constants['fov_radius'], constants['fov_light_walls'], constants['fov_algorithm']) render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], constants['bar_width'], constants['panel_height'], constants['panel_y'], mouse, constants['colors'], game_state) fov_recompute = False libtcod.console_flush() clear_all(con, entities) action = handle_keys(key, game_state) mouse_action = handle_mouse(mouse) move = action.get('move') wait = action.get('wait') pickup = action.get('pickup') show_inventory = action.get('show_inventory') drop_inventory = action.get('drop_inventory') inventory_index = action.get('inventory_index') level_up = action.get('level_up') show_character_screen = action.get('show_character_screen') exit = action.get('exit') take_stairs = action.get('take_stairs') fullscreen = action.get('fullscreen') left_click = mouse_action.get('left_click') right_click = mouse_action.get('right_click') player_turn_results = [] if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location(entities, destination_x, destination_y) if target: attack_results = player.fighter.attack(target) player_turn_results.extend(attack_results) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN elif wait: game_state = GameStates.ENEMY_TURN elif pickup and game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.item and entity.x == player.x and entity.y == player.y: pickup_results = player.inventory.add_item(entity) player_turn_results.extend(pickup_results) break else: message_log.add_message(Message('There is nothing here to pick up.', libtcod.yellow)) if show_inventory: previous_game_state = game_state game_state = GameStates.SHOW_INVENTORY if drop_inventory: previous_game_state = game_state game_state = GameStates.DROP_INVENTORY if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len(player.inventory.items): item = player.inventory.items[inventory_index] if game_state == GameStates.SHOW_INVENTORY: player_turn_results.extend(player.inventory.use(item, entities=entities, fov_map=fov_map)) elif game_state == GameStates.DROP_INVENTORY: player_turn_results.extend(player.inventory.drop_item(item)) if take_stairs and game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.stairs and entity.x == player.x and entity.y == player.y: entities = game_map.next_floor(player, message_log, constants) fov_map = initialize_fov(game_map) fov_recompute = True libtcod.console_clear(con) break else: message_log.add_message(Message('There are no stairs here.', libtcod.yellow)) if level_up: if level_up == 'hp': player.fighter.base_max_hp += 20 player.fighter.hp += 20 elif level_up == 'str': player.fighter.base_power += 1 elif level_up == 'def': player.fighter.base_defense += 1 game_state = previous_game_state if show_character_screen: previous_game_state = game_state game_state = GameStates.CHARACTER_SCREEN if game_state == GameStates.TARGETING: if left_click: target_x, target_y = left_click item_use_results = player.inventory.use(targeting_item, entities=entities, fov_map=fov_map, target_x=target_x, target_y=target_y) player_turn_results.extend(item_use_results) elif right_click: player_turn_results.append({'targeting_cancelled': True}) if exit: if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY, GameStates.CHARACTER_SCREEN): game_state = previous_game_state elif game_state == GameStates.TARGETING: player_turn_results.append({'targeting_cancelled': True}) else: save_game(player, entities, game_map, message_log, game_state) return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') item_added = player_turn_result.get('item_added') item_consumed = player_turn_result.get('consumed') item_dropped = player_turn_result.get('item_dropped') equip = player_turn_result.get('equip') targeting = player_turn_result.get('targeting') targeting_cancelled = player_turn_result.get('targeting_cancelled') xp = player_turn_result.get('xp') if message: message_log.add_message(message) if targeting_cancelled: game_state = previous_game_state message_log.add_message(Message('Targeting cancelled')) if xp: leveled_up = player.level.add_xp(xp) message_log.add_message(Message('You gain {0} experience points.'.format(xp))) if leveled_up: message_log.add_message(Message('Your battle skills grow stronger! You reached level {0}'.format(player.level.current_level) + '!', libtcod.yellow)) previous_game_state = game_state game_state = GameStates.LEVEL_UP if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if item_added: entities.remove(item_added) game_state = GameStates.ENEMY_TURN if item_consumed: game_state = GameStates.ENEMY_TURN if targeting: previous_game_state = GameStates.PLAYERS_TURN game_state = GameStates.TARGETING targeting_item = targeting message_log.add_message(targeting_item.item.targeting_message) if item_dropped: entities.append(item_dropped) game_state = GameStates.ENEMY_TURN if equip: equip_results = player.equipment.toggle_equip(equip) for equip_result in equip_results: equipped = equip_result.get('equipped') dequipped = equip_result.get('dequipped') if equipped: message_log.add_message(Message('You equipped the {0}'.format(equipped.name))) if dequipped: message_log.add_message(Message('You dequipped the {0}'.format(dequipped.name))) game_state = GameStates.ENEMY_TURN if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn(player, fov_map, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYERS_TURN
def play_game(): global key, mouse player_action = None mouse = libtcod.Mouse() key = libtcod.Key() questList=[] #Make me a new quest. Very clearly not how we're going to do this for real newWords=['troll'] benefits=questBenefits(1,'Non',newWords) qData = [player, map, objects, inventory,game_msgs] locQuest=reachLocationQuest(qData) #locQuest.randomizeLocation(qData) #This first quest is a "find the ring and escape" quest, hard-coded. So we need to randomly place the escape and the ring item_component = Item() item = Object(player.x+1, player.y, '*', 'Ring', libtcod.violet, item=item_component) itQuest=obtainItemQuest(item,qData) #itQuest.randomizeItemLocation(qData) quest1=subQuest(benefits,locQuest) quest2=subQuest(benefits,itQuest) mainQuest=quest() mainQuest.addQuest(quest1) mainQuest.addQuest(quest2) questList.append(mainQuest) #make the player's dictionary for testing player.fighter.dictionary = ['strong','banish','orc'] #make up some weapons - there are only so many weapons, so they are all global constants. This will be moved away once we get Item moved daggerStats=equipStats(8,0,0) daggerItem_component = Item() daggerItem = Object(player.x+2, player.y, ')', 'Dagger', libtcod.violet, item=daggerItem_component) dagger=weapon(daggerItem,1,daggerStats) inventory.append(dagger.weaponObject) while not libtcod.console_is_window_closed(): #render the screen libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE,key,mouse) render_all(mouse,map,player,objects,fov_recompute,fov_map) libtcod.console_flush() #erase all objects at their old locations, before they move for object in objects: object.clear() #handle keys and exit game if needed player_action = handle_keys(key,objects,player,inventory,game_state) if player_action == 'exit': # save_game() break qData = [player, map, objects, inventory,game_msgs] #upate the quest data #Once the player takes an action, check quests for qu in questList: qu.isComplete(qData) if qu.completed == True: qu.benefits.giveBenefits(player) inx = questList.index(qu) del(questList[inx]) #let monsters take their turn if game_state == 'playing' and player_action != 'didnt-take-turn': for object in objects: if object.ai: object.ai.take_turn(fov_map,player)
def main(): constants = get_constants(); libtcod.console_set_custom_font('arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(constants['screen_width'], constants['screen_height'], constants['window_title'], False) con = libtcod.console_new(constants['screen_width'], constants['screen_height']) panel = libtcod.console_new(constants['screen_width'], constants['panel_height']) player = None entities = [] game_map = None message_log = None game_state = None show_main_menu = True show_load_error_message = False main_menu_background_image = libtcod.image_load('menu_background.png') key = libtcod.Key() mouse = libtcod.Mouse() while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) if show_main_menu: main_menu(con, main_menu_background_image, constants['screen_width'], constants['screen_height']) if show_load_error_message: message_box(con, 'No save game to load', 50, constants['screen_width'], constants['screen_height']) libtcod.console_flush() action = handle_main_menu(key) new_game = action.get('new_game') load_saved_game = action.get('load_game') exit_game = action.get('exit') if show_load_error_message and (new_game or load_saved_game or exit_game): show_load_error_message = False elif new_game: player, entities, game_map, message_log, game_state = get_game_variables(constants) game_state = GameStates.PLAYERS_TURN show_main_menu = False elif load_saved_game: try: player, entities, game_map, message_log, game_state = load_game() show_main_menu = False except FileNotFoundError: show_load_error_message = True elif exit_game: break else: libtcod.console_clear(con) play_game(player, entities, game_map, message_log, game_state, con, panel, constants) show_main_menu = True
def play_game(player, entities, game_map, message_log, game_state, con, panel, constants): # Calculate the Fog of War on the map fov_recompute = True fov_map = initialize_fov(game_map) # Set variables to receive both keypresses and mouse movements key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYERS_TURN previous_game_state = game_state targeting_item = None # The Main game loop while not libtcod.console_is_window_closed(): # Wait until a key is pressed libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) # Recalculate the field of vision from player coordinates. Only happens when player moves if fov_recompute: recompute_fov(fov_map, player.x, player.y, constants['fov_radius'], constants['fov_light_walls'], constants['fov_algorithm']) # Draw everything on screen render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], constants['bar_width'], constants['panel_height'], constants['panel_y'], mouse, constants['colors'], game_state) fov_recompute = False libtcod.console_flush() clear_all(con, entities) # Define actions action = handle_keys(key, game_state) mouse_action = handle_mouse(mouse) move = action.get('move') pickup = action.get('pickup') show_inventory = action.get('show_inventory') drop_inventory = action.get('drop_inventory') inventory_index = action.get('inventory_index') take_stairs = action.get('take_stairs') level_up = action.get('level_up') show_character_screen = action.get('show_character_screen') exit = action.get('exit') wait = action.get('wait') fullscreen = action.get('fullscreen') left_click = mouse_action.get('left_click') right_click = mouse_action.get('right_click') player_turn_results = [] # Move the player character if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location( entities, destination_x, destination_y) # If the square contained an enemy, attack it if target: attack_results = player.fighter.attack(target) player_turn_results.extend(attack_results) # Otherwise, move into the square and recalculate Field of Vision else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN # Player tries to pick up an item elif pickup and game_state == GameStates.PLAYERS_TURN: for entity in entities: # If there is an item at the coordinates, try to add it to inventory. If full, fail at that if entity.item and entity.x == player.x and entity.y == player.y: pickup_results = player.inventory.add_item(entity) player_turn_results.extend(pickup_results) break # Player tried to pick up empty space else: if random.randint(0, 100) >= 99: message_log.add_message( Message( 'You daintly pick up a handful of musty air and stuff it in your pocket.', libtcod.yellow)) else: message_log.add_message( Message('There is nothing here to pick up.', libtcod.yellow)) # If the player hits wait, move straight to the enemy turn elif wait and game_state == GameStates.PLAYERS_TURN: game_state = GameStates.ENEMY_TURN # Show the inventory if show_inventory: previous_game_state = game_state game_state = GameStates.SHOW_INVENTORY # Show the inventory for dropping items if drop_inventory: previous_game_state = game_state game_state = GameStates.DROP_INVENTORY # Select an item from the inventory if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len( player.inventory.items): item = player.inventory.items[inventory_index] if game_state == GameStates.SHOW_INVENTORY: player_turn_results.extend( player.inventory.use(item, entities=entities, fov_map=fov_map)) elif game_state == GameStates.DROP_INVENTORY: player_turn_results.extend(player.inventory.drop_item(item)) """ Player takes the stairs to the next level generate a new level, reset the map and seen squares, and clear the console """ if take_stairs and game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.stairs and entity.x == player.x and entity.y == player.y: entities = game_map.next_floor(player, message_log, constants) fov_map = initialize_fov(game_map) fov_recompute = True libtcod.console_clear(con) break else: message_log.add_message( Message('There are no stairs here.', libtcod.yellow)) # When player goes up a level, they get to choose a stat to upgrade and then we return to previous game state if level_up: if level_up == 'hp': player.fighter.base_max_hp += 20 player.fighter.hp += 20 elif level_up == 'str': player.fighter.base_power += 1 elif level_up == 'def': player.fighter.base_defense += 1 game_state = previous_game_state # Showing character screen if show_character_screen: previous_game_state = game_state game_state = GameStates.CHARACTER_SCREEN """ Targeting mode Left-click on mouse sets target coordinates and uses the item Right-click cancels targeting """ if game_state == GameStates.TARGETING: if left_click: target_x, target_y = left_click item_use_results = player.inventory.use(targeting_item, entities=entities, fov_map=fov_map, target_x=target_x, target_y=target_y) player_turn_results.extend(item_use_results) elif right_click: player_turn_results.append({'targeting_cancelled': True}) # Exits from inventory screens, targeting, or the game in general if exit: if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY, GameStates.CHARACTER_SCREEN): game_state = previous_game_state elif game_state == GameStates.TARGETING: player_turn_results.append({'targeting_cancelled': True}) else: save_game(player, entities, game_map, message_log, game_state) return True # Process the results from player turn if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) # Loop that handles all the different player actions for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') item_added = player_turn_result.get('item_added') item_consumed = player_turn_result.get('consumed') item_dropped = player_turn_result.get('item_dropped') equip = player_turn_result.get('equip') targeting = player_turn_result.get('targeting') targeting_cancelled = player_turn_result.get('targeting_cancelled') xp = player_turn_result.get('xp') # If there's a message, add to log if message: message_log.add_message(message) # If something died, put a message to the log and if it was the player, react accordingly if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) # If the player picked up an item, remove it from the world if item_added: entities.remove(item_added) game_state = GameStates.ENEMY_TURN # If player used an item, switch to enemy turn. The item reacts by itself, # this loop only needs to concern itself with the game states if item_consumed: game_state = GameStates.ENEMY_TURN # If an item was dropped, add it to the game world if item_dropped: entities.append(item_dropped) game_state = GameStates.ENEMY_TURN # If player selects equipment from the inventory, equip or dequip it if equip: equip_results = player.equipment.toggle_equip(equip) for equip_result in equip_results: equipped = equip_result.get('equipped') dequipped = equip_result.get('dequipped') if equipped: message_log.add_message( Message('You equipped the {0}'.format( equipped.name))) if dequipped: message_log.add_message( Message('You dequipped the {0}'.format( dequipped.name))) game_state = GameStates.ENEMY_TURN # Item requires targeting, go to targeting mode if targeting: previous_game_state = GameStates.PLAYERS_TURN game_state = GameStates.TARGETING targeting_item = targeting message_log.add_message(targeting_item.item.targeting_message) # Player cancels targeting if targeting_cancelled: game_state = previous_game_state message_log.add_message(Message('Targeting cancelled')) # Getting experience when killing monsters if xp: leveled_up = player.level.add_xp(xp) message_log.add_message( Message('You gain {0} experience points.'.format(xp))) # If the xp goes over the xp_to_next_level threshold, leveled_up will be true and player goes up a level if leveled_up: message_log.add_message( Message( 'Your battle skills grow stronger! You reached level {0}' .format(player.level.current_level) + '!', libtcod.yellow)) previous_game_state = game_state game_state = GameStates.LEVEL_UP # The enemy turn if game_state == GameStates.ENEMY_TURN: # Go through all entities in the list for entity in entities: # If it has an AI, make a move if entity.ai: enemy_turn_results = entity.ai.take_turn( player, fov_map, game_map, entities) # Handle all the messages from entities for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') # If there's a message, log it if message: message_log.add_message(message) # If something died, make that happen if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYERS_TURN
def is_closed(self): """Wrapper around libtcod""" return libtcod.console_is_window_closed()
def play_game(player, entities, game_map, message_log, game_state, con, panel, constants): """Logic for controlling the game itself""" fov_recompute = True # Only need to recompute when we move (and start!) fov_map = initialize_fov(game_map) # Variable that is the fov result message_log = MessageLog(constants['message_x'], constants['message_width'], constants['message_height']) # Input variables and game state key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYERS_TURN previous_game_state = game_state targeting_item = None # ENGINE LOOP while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) if fov_recompute: recompute_fov(fov_map, player.x, player.y, constants['fov_radius'], constants['fov_light_walls'], constants['fov_algorithm']) render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, constants['screen_width'], constants['screen_height'], message_log, constants['bar_width'], constants['panel_height'], constants['panel_y'], mouse, constants['colors'], game_state) fov_recompute = False libtcod.console_flush() # Presents everything on the screen clear_all(con, entities) # Erases the old positions # ACTION HANDLERS action = handle_keys(key, game_state) mouse_action = handle_mouse(mouse) move = action.get('move') wait = action.get('wait') pickup = action.get('pickup') show_inventory = action.get('show_inventory') drop_inventory = action.get('drop_inventory') inventory_index = action.get('inventory_index') take_stairs = action.get('take_stairs') level_up = action.get('level_up') show_character_screen = action.get('show_character_screen') exit = action.get('exit') fullscreen = action.get('fullscreen') left_click = mouse_action.get('left_click') right_click = mouse_action.get('right_click') player_turn_results = [] # GAME STATE SITUATIONS if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: attack_results = player.fighter.attack(target) player_turn_results.extend(attack_results) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN if wait: game_state = GameStates.ENEMY_TURN elif pickup and game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.item and entity.x == player.x and entity.y == player.y: pickup_results = player.inventory.add_item(entity) player_turn_results.extend(pickup_results) break else: # no break message_log.add_message( Message("There is nothing here to pick up.", libtcod.yellow)) if show_inventory: previous_game_state = game_state game_state = GameStates.SHOW_INVENTORY if drop_inventory: previous_game_state = game_state game_state = GameStates.DROP_INVENTORY if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len( player.inventory.items): item = player.inventory.items[inventory_index] if game_state == GameStates.SHOW_INVENTORY: player_turn_results.extend( player.inventory.use(item, entities=entities, fov_map=fov_map)) elif game_state == GameStates.DROP_INVENTORY: player_turn_results.extend(player.inventory.drop_item(item)) if take_stairs and game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.stairs and entity.x == player.x and entity.y == player.y: entities = game_map.next_floor(player, message_log, constants) fov_map = initialize_fov(game_map) fov_recompute = True libtcod.console_clear(con) break else: # No break message_log.add_message( Message("There are no stairs here.", libtcod.yellow)) if level_up: if level_up == 'hp': player.fighter.base_max_hp += 20 player.fighter.hp += 20 elif level_up == 'str': player.fighter.base_power += 1 elif level_up == 'def': player.fighter.base_defense += 1 game_state = previous_game_state if show_character_screen: previous_game_state = game_state game_state = GameStates.CHARACTER_SCREEN if game_state == GameStates.TARGETING: if left_click: target_x, target_y = left_click item_use_results = player.inventory.use(targeting_item, entities=entities, fov_map=fov_map, target_x=target_x, target_y=target_y) player_turn_results.extend(item_use_results) elif right_click: player_turn_results.append({'targeting_cancelled': True}) if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) if exit: if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY, GameStates.CHARACTER_SCREEN): # Return to gameplay state from above states game_state = previous_game_state elif game_state == GameStates.TARGETING: # Return to game from targeting state game_state = previous_game_state player_turn_results.append({'targeting_cancelled': True}) elif game_state == GameStates.PLAYER_DEAD: # Delete a save file if player exits after dying if os.path.isfile('savegame.dat'): os.remove('savegame.dat') return True else: # Create a save file if player exits while alive save_game(player, entities, game_map, message_log, game_state) return True # PLAYER TURN RESULTS for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') item_added = player_turn_result.get('item_added') item_consumed = player_turn_result.get('consumed') item_dropped = player_turn_result.get('item_dropped') equip = player_turn_result.get('equip') targeting = player_turn_result.get('targeting') targeting_cancelled = player_turn_result.get('targeting_cancelled') xp = player_turn_result.get('xp') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if item_added: entities.remove(item_added) game_state = GameStates.ENEMY_TURN if item_consumed: game_state = GameStates.ENEMY_TURN if item_dropped: entities.append(item_dropped) game_state = GameStates.ENEMY_TURN if equip: equip_results = player.equipment.toggle_equip(equip) for equip_result in equip_results: equipped = equip_result.get('equipped') unequipped = equip_result.get('unequiped') if equipped: message_log.add_message( Message("You equipped the {}.".format( equipped.name))) if unequipped: message_log.add_message( Message("You unequipped the {}.".format( unequipped.name))) game_state = GameStates.ENEMY_TURN if targeting: previous_game_state = GameStates.PLAYERS_TURN # Canceling doesn't go to inventory game_state = GameStates.TARGETING targeting_item = targeting message_log.add_message(targeting_item.item.targeting_message) if targeting_cancelled: game_state = previous_game_state message_log.add_message(Message("Targeting cancelled.")) if xp: leveled_up = player.level.add_xp( xp) # Adds the xp and returns boolean re: a level-up message_log.add_message(Message( "You gained {} EXP".format(xp))) if leveled_up: message_log.add_message( Message( "You've grown to level {}!".format( player.level.current_level), libtcod.yellow)) previous_game_state = game_state game_state = GameStates.LEVEL_UP if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn( player, fov_map, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYERS_TURN
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 fov_algorithm = 0 fov_light_walls = True fov_radius = 10 max_monsters_per_room = 3 colors = { 'dark_wall': libtcod.Color(0, 0, 100), 'dark_ground': libtcod.Color(50, 50, 150), 'light_wall': libtcod.Color(130, 110, 50), 'light_ground': libtcod.Color(200, 180, 50) } fighter_component = Fighter(hp=30, defense=2, power=5) player = Entity(0, 0, '@', libtcod.white, 'Player', blocks=True, render_order=RenderOrder.ACTOR, fighter=fighter_component) entities = [player] libtcod.console_set_custom_font( 'arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(screen_width, screen_height, 'The Tombs of Twilight', False) con = libtcod.console_new(screen_width, screen_height) game_map = GameMap(map_width, map_height) game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities, max_monsters_per_room) fov_recompute = True fov_map = initialize_fov(game_map) key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYERS_TURN while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse) if fov_recompute: recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) render_all(con, entities, player, game_map, fov_map, fov_recompute, screen_width, screen_height, colors) fov_recompute = False libtcod.console_flush() clear_all(con, entities) action = handle_keys(key) move = action.get('move') exit = action.get('exit') fullscreen = action.get('fullscreen') player_turn_results = [] if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: attack_results = player.fighter.attack(target) player_turn_results.extend(attack_results) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN if exit: return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') if message: print(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) print(message) if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn( player, fov_map, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') if message: print(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) print(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYERS_TURN
def play_game(self, players, entities, game_map, message_log, game_state, con, panel, constants): # Flags if we need to update FOV fov_recompute = True for player in players: player.vision.fov_map = initialize_fov(game_map) # Holds keyboard and mouse input key = libtcod.Key() mouse = libtcod.Mouse() self.game_state = GameStates.PLAYERS_TURN previous_game_state = self.game_state targeting_item = None self.previous_player = 0 players[self.active_player].color = libtcod.white # Game loop while not libtcod.console_is_window_closed(): # Execute any player command if players[self.active_player].command: command_results = players[self.active_player].command.execute() finish_turn = False for command_result in command_results: finish_command = command_result.get('finish_command') redo_fov = command_result.get('redo_fov') end_turn = command_result.get('end_turn') if finish_command: players[self.active_player].command = None if redo_fov: fov_recompute = True if end_turn: finish_turn = True if finish_turn: self.next_player(players) continue # Enemy Movement if self.game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn( players, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') if message: message_log.add_message(message) if dead_entity: if dead_entity in players: message, self.game_state = kill_player( dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if self.game_state == GameStates.PLAYER_DEAD: break if self.game_state == GameStates.PLAYER_DEAD: break else: self.game_state = GameStates.PLAYERS_TURN continue # Input listener I guess libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) # Update fov if needed if fov_recompute: for player in players: recompute_fov(player.vision.fov_map, player.x, player.y, self.constants['fov_radius'], self.constants['fov_light_walls'], self.constants['fov_algorithm']) # Render all entities render_all( con, panel, entities, players, self.active_player, game_map, fov_recompute, message_log, self.constants['screen_width'], self.constants['screen_height'], self.constants['bar_width'], self.constants['panel_height'], self.constants['panel_y'], mouse, self.constants['colors'], self.game_state) fov_recompute = False # Push frame update libtcod.console_flush() # Clear old entity positions clear_all(con, entities, game_map) # Determine action action = handle_keys(key, self.game_state) mouse_action = handle_mouse(mouse) # Process the action object repeat = action.get('repeat') move = action.get('move') wait = action.get('wait') pickup = action.get('pickup') show_inventory = action.get('show_inventory') drop_inventory = action.get('drop_inventory') inventory_index = action.get('inventory_index') take_stairs = action.get('take_stairs') cancel_follow = action.get('cancel_follow') level_up = action.get('level_up') exit = action.get('exit') show_character_screen = action.get('show_character_screen') fullscreen = action.get('fullscreen') # Handle mouseclicks left_click = mouse_action.get('left_click') right_click = mouse_action.get('right_click') # For the message log player_turn_results = [] # Movement if move and self.game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = players[self.active_player].x + dx destination_y = players[self.active_player].y + dy if not (destination_x < 0 or destination_x >= game_map.width or destination_y < 0 or destination_y >= game_map.height or game_map.is_blocked(destination_x, destination_y)): target = get_blocking_entities_at_location( entities, destination_x, destination_y) # If the way is blocked by a baddie if target: # Don't attack other players if target in players: # follow the player you're bumping into # Only follow if it would not make it so every player is following something # (That would be bad) command_count = 0 for player in players: if player.command: command_count += 1 if command_count < len(players) - 1: players[self.active_player].set_command( FollowCommand(-1, target, entities, game_map)) self.next_player(players) else: # If it would do that, just ignore the input continue # Do attack enemies else: attack_results = players[ self.active_player].fighter.attack(target) player_turn_results.extend(attack_results) # Change active player self.next_player(players) else: # Repeat if needed if repeat: # Dont let all players be repeating command_count = 0 for player in players: if player.command: command_count += 1 if command_count < len(players) - 1: players[self.active_player].set_command( MoveCommand(repeat, dx, dy, entities, game_map)) else: # If it would do that, just ignore the input continue else: players[self.active_player].set_command( MoveCommand(1, dx, dy, entities, game_map)) if wait: if repeat: # Dont let all players be repeating command_count = 0 for player in players: if player.command: command_count += 1 if command_count < len(players) - 1: # We wait by moving nowhere. This may need to become a WaitCommand eventually players[self.active_player].set_command( MoveCommand(repeat, 0, 0, entities, game_map)) else: # If it would make all players repeat, just ignore the input continue else: # Change active player players[self.active_player].set_command( MoveCommand(1, 0, 0, entities, game_map)) # Picking up an item elif pickup and self.game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.item and entity.x == players[ self.active_player].x and entity.y == players[ self.active_player].y: pickup_results = players[ self.active_player].inventory.add_item(entity) player_turn_results.extend(pickup_results) break else: message_log.add_message( Message('There is nothing here to pick up.', libtcod.yellow)) # Show inventory menu if show_inventory: previous_game_state = self.game_state self.game_state = GameStates.SHOW_INVENTORY # Drop inventory if drop_inventory: previous_game_state = self.game_state self.game_state = GameStates.DROP_INVENTORY # Choose inventory item if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len( players[self.active_player].inventory.items): item = players[ self.active_player].inventory.items[inventory_index] if self.game_state == GameStates.SHOW_INVENTORY: player_turn_results.extend( players[self.active_player].inventory.use( item, entities=entities, fov_map=players[ self.active_player].vision.fov_map)) elif self.game_state == GameStates.DROP_INVENTORY: player_turn_results.extend( players[self.active_player].inventory.drop_item(item)) # Take stairs if take_stairs and self.game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.stairs and entity.x == players[ self.active_player].x and entity.y == players[ self.active_player].y: entities = game_map.next_floor(players, message_log, self.constants) for player in players: player.vision.fov_map = initialize_fov(game_map) fov_recompute = True libtcod.console_clear(con) break else: message_log.add_message( Message('There are no stairs here.', libtcod.yellow)) # Cancel follow if cancel_follow: for player in players: player.command = None # Level up if level_up: if level_up == 'hp': players[self.active_player].fighter.base_max_hp += 20 players[self.active_player].fighter.hp += 20 elif level_up == 'str': players[self.active_player].fighter.base_power += 1 elif level_up == 'def': players[self.active_player].fighter.base_defense += 1 self.game_state = previous_game_state # Character screen if show_character_screen: previous_game_state = self.game_state self.game_state = GameStates.CHARACTER_SCREEN # Targeting if self.game_state == GameStates.TARGETING: if left_click: target_x, target_y = left_click item_use_results = players[ self.active_player].inventory.use( targeting_item, entities=entities, fov_map=players[self.active_player].vision.fov_map, target_x=target_x, target_y=target_y) player_turn_results.extend(item_use_results) elif right_click: player_turn_results.append({'targeting_cancelled': True}) # Exit on escape if exit: if self.game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY, GameStates.CHARACTER_SCREEN): self.game_state = previous_game_state elif self.game_state == GameStates.TARGETING: player_turn_results.append({'targeting_cancelled': True}) else: save_game(players, entities, game_map, message_log, self.game_state, self.active_player) return True # Toggle fullscreen if fullscreen: libtcod.console_set_fullscreen( not libtcod.console_is_fullscreen()) # Print message results for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') item_added = player_turn_result.get('item_added') item_consumed = player_turn_result.get('consumed') item_dropped = player_turn_result.get('item_dropped') equip = player_turn_result.get('equip') targeting = player_turn_result.get('targeting') targeting_cancelled = player_turn_result.get( 'targeting_cancelled') xp = player_turn_result.get('xp') if message: message_log.add_message(message) if dead_entity: if dead_entity in players: message, self.game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if item_added: entities.remove(item_added) # Change active player self.next_player(players) if item_consumed: # Change active player self.next_player(players) if item_dropped: entities.append(item_dropped) # Change active player self.next_player(players) if equip: equip_results = players[ self.active_player].equipment.toggle_equip(equip) for equip_result in equip_results: equipped = equip_result.get('equipped') dequipped = equip_result.get('dequipped') if equipped: message_log.add_message( Message('You equipped the {0}'.format( equipped.name))) if dequipped: message_log.add_message( Message('You dequipped the {0}'.format( dequipped.name))) # Change active player self.next_player(players) if targeting: previous_game_state = GameStates.PLAYERS_TURN self.game_state = GameStates.TARGETING targeting_item = targeting message_log.add_message( targeting_item.item.targeting_message) if targeting_cancelled: self.game_state = previous_game_state message_log.add_message(Message('Targeting cancelled')) if xp: leveled_up = players[self.active_player].level.add_xp(xp) message_log.add_message( Message('You gain {0} experience point.'.format(xp))) if leveled_up: message_log.add_message( Message( 'Your battle skills grow stronger! You reached level {0}' .format(players[ self.active_player].level.current_level) + '!', libtcod.yellow)) previous_game_state = self.game_state self.game_state = GameStates.LEVEL_UP
def main(argv=None): """ Entry-point into program.""" settings, args = process_command_line(argv) # Initialise libtcod libtcod.console_set_custom_font( 'arial12x12.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, PROGRAM_NAME, False) libtcod.sys_set_fps(10) libtcod.console_set_background_flag(0, libtcod.BKGND_SET) # Create a map and add starting entities. map = Map(maps.ground_control.level_1_raw) player = Human("Bob Smith", "male", 15, 30) player.report = ReportType.PLAYER map.add_entity(map.entry_point[0], map.entry_point[1], player) # Ghost is used to move around map for viewing ghost = Human("Ghost", "male", 15, 0) # Set up UI ui.Screens.map = ui.MapScreen(MAP_WINDOW[0], MAP_WINDOW[1], MAP_WINDOW[2], MAP_WINDOW[3]) ui.Screens.msg = ui.MessageScreen(MSG_WINDOW[0], MSG_WINDOW[1], MSG_WINDOW[2], MSG_WINDOW[3]) ui.Screens.inv = ui.InventoryScreen(INVENTORY_WINDOW[0], INVENTORY_WINDOW[1], INVENTORY_WINDOW[2], INVENTORY_WINDOW[3]) ui.Screens.map.show_and_activate() ui.Screens.msg.show_and_activate() ui.Screens.inv.hide_and_deactivate() # Set up main game loop. # turn_taken - did the action actually take a turn - ie do we want to update the simulation now? Initially true, to force a initial render. # input_type - what input state did the action leave us in? Are we expecting the next input to be part of the current action? # delayed_action - if we are in the middle of a multi-stage action, this is the action (closure) to be performed at the end of it. turn_taken = True input_type = InputType.IMMEDIATE delayed_action = None current_turn = 1 # main loop while not libtcod.console_is_window_closed(): libtcod.console_clear(0) libtcod.console_set_default_foreground(0, libtcod.white) # set up render bounds centre_bounds = int(MAP_WINDOW[2] / 2), int( MAP_WINDOW[3] / 2), map.x_max - int( MAP_WINDOW[2] / 2) - 1, map.y_max - int(MAP_WINDOW[3] / 2) - 1 # are we viewing the player or the ghost entity which acts as the automap viewer? view_centre = max(centre_bounds[0], min( player.x, centre_bounds[2])), max(centre_bounds[1], min(player.y, centre_bounds[3])) # Render screens if ui.Screens.map.show: ui.Screens.map.render(map, view_centre, player) if ui.Screens.msg.show: ui.Screens.msg.render() if ui.Screens.inv.show: ui.Screens.inv.render(player) ui.render_entity_info(player, map) libtcod.console_set_default_foreground(0, libtcod.white) libtcod.console_print(0, 0, 0, "Turn: %d" % current_turn) # Blit to console libtcod.console_flush() # Process input player_action = input.handle_input(player, input_type, delayed_action) turn_taken, input_type, delayed_action = player_action[0]( player, map, player_action[1:]) if turn_taken: current_turn += 1 # Quit the loop? if turn_taken is None: break # If we've done something, update world and render if turn_taken: sim.update_world() # Return peacefully return 0
def play_game(player, entities, game_map, message_log, game_state, con, panel, constants): mixer.music.load('Rowan_Box_-_08_-_Drowned_In_Black_Sludge.mp3') mixer.music.play(-1) fov_recompute = True fov_map = initialize_fov(game_map) key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYERS_TURN previous_game_state = game_state targeting_item = None while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) if fov_recompute: recompute_fov(fov_map, player.x, player.y, constants['fov_radius'], constants['fov_light_walls'], constants['fov_algorithm']) render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], constants['bar_width'], constants['panel_height'], constants['panel_y'], mouse, constants['colors'], game_state) fov_recompute = False libtcod.console_flush() clear_all(con, entities) action = handle_keys(key, game_state) mouse_action = handle_mouse(mouse) move = action.get('move') pickup = action.get('pickup') show_inventory = action.get('show_inventory') drop_inventory = action.get('drop_inventory') inventory_index = action.get('inventory_index') exit = action.get('exit') fullscreen = action.get('fullscreen') left_click = mouse_action.get('left_click') right_click = mouse_action.get('right_click') player_turn_results = [] if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location(entities, destination_x, destination_y) if target: attack_results = player.fighter.attack(target) player_turn_results.extend(attack_results) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN elif pickup and game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.item and entity.x == player.x and entity.y == player.y: pickup_results = player.inventory.add_item(entity) player_turn_results.extend(pickup_results) break else: message_log.add_message(Message('There is nothing here to pick up.', libtcod.yellow)) if show_inventory: previous_game_state = game_state game_state = GameStates.SHOW_INVENTORY if drop_inventory: previous_game_state = game_state game_state = GameStates.DROP_INVENTORY if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len( player.inventory.items): item = player.inventory.items[inventory_index] if game_state == GameStates.SHOW_INVENTORY: player_turn_results.extend(player.inventory.use(item, entities=entities, fov_map=fov_map)) elif game_state == GameStates.DROP_INVENTORY: player_turn_results.extend(player.inventory.drop_item(item)) if game_state == GameStates.TARGETING: if left_click: target_x, target_y = left_click item_use_results = player.inventory.use(targeting_item, entities=entities, fov_map=fov_map, target_x=target_x, target_y=target_y) player_turn_results.extend(item_use_results) elif right_click: player_turn_results.append({'targeting_cancelled': True}) if exit: if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY): game_state = previous_game_state elif game_state == GameStates.TARGETING: player_turn_results.append({'targeting_cancelled': True}) else: save_game(player, entities, game_map, message_log, game_state) return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') item_added = player_turn_result.get('item_added') item_consumed = player_turn_result.get('consumed') item_dropped = player_turn_result.get('item_dropped') targeting = player_turn_result.get('targeting') targeting_cancelled = player_turn_result.get('targeting_cancelled') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) monster_death.play() message_log.add_message(message) if item_added: entities.remove(item_added) game_state = GameStates.ENEMY_TURN if item_consumed: game_state = GameStates.ENEMY_TURN if item_dropped: entities.append(item_dropped) game_state = GameStates.ENEMY_TURN if targeting: previous_game_state = GameStates.PLAYERS_TURN game_state = GameStates.TARGETING targeting_item = targeting message_log.add_message(targeting_item.item.targeting_message) if targeting_cancelled: game_state = previous_game_state message_log.add_message(Message('Targeting cancelled')) if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn(player, fov_map, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) monster_death.play() message_log.add_message(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYERS_TURN
def main(self): # Set font libtcod.console_set_custom_font( 'dejavu_wide16x16_gs_tc.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) # Create game window libtcod.console_init_root(self.constants['screen_width'], self.constants['screen_height'], self.constants['window_title'], False) # Create a console (Drawing Layer?) con = libtcod.console_new(self.constants['screen_width'], self.constants['screen_height']) panel = libtcod.console_new(self.constants['screen_width'], self.constants['panel_height']) players = [] entity = [] game_map = None message_log = None self.game_state = None self.active_player = 0 show_main_menu = True show_load_error_message = False main_menu_background_image = libtcod.image_load('menu_background.png') # Holds keyboard and mouse input key = libtcod.Key() mouse = libtcod.Mouse() # Menu loop while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) if show_main_menu: main_menu(con, main_menu_background_image, self.constants['screen_width'], self.constants['screen_height']) if show_load_error_message: message_box(con, 'No save game to load', 50, self.constants['screen_width'], self.constants['screen_height']) libtcod.console_flush() action = handle_main_menu(key) new_game = action.get('new_game') load_saved_game = action.get('load_game') exit_game = action.get('exit') if show_load_error_message and (new_game or load_saved_game or exit_game): show_load_error_message = False elif new_game: players, entities, game_map, message_log, self.game_state = get_game_variables( self.constants) self.game_state = GameStates.PLAYERS_TURN show_main_menu = False elif load_saved_game: try: players, entities, game_map, message_log, self.game_state, self.active_player = load_game( self.constants['player_count']) self.game_state = GameStates.PLAYERS_TURN show_main_menu = False except FileNotFoundError: show_load_error_message = True elif exit_game: break else: libtcod.console_clear(con) self.play_game(players, entities, game_map, message_log, self.game_state, con, panel, self.constants) show_main_menu = True
def gameLoop(): while not libtcod.console_is_window_closed() and gameState != "gameDone": gEngine.drawFrame() key = libtcod.console_check_for_keypress(libtcod.KEY_PRESSED) handleInput(key)
def main(): # Screen size screen_width = 80 screen_height = 50 # Map parameters map_width = 80 map_height = 45 max_rooms = 30 room_min_size = 6 room_max_size = 10 max_monsters_per_room = 3 # Field of view parameters fov_algorithm = 0 fov_light_walls = True fov_radius = 10 # Colors for blocked and non-blocked tiles colors = { 'dark_wall': libtcod.Color(0, 0, 100), 'dark_ground': libtcod.Color(50, 50, 150), 'light_wall': libtcod.Color(130, 110, 50), 'light_ground': libtcod.Color(200, 180, 50) } # Player data, a white @ in the middle of the screen # Position needs to be forcefully cast to int player = Entity(int(screen_width / 2), int(screen_height / 2), '@', libtcod.white, 'Player', blocks=True) # Entity array entities = [player] # Loads greyscale TCOD-mapping Arial 10x10 font libtcod.console_set_custom_font( 'arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) # Creates the screen. Boolean indicates full screen libtcod.console_init_root(screen_width, screen_height, 'NeverDie', False) # Creates a new console con = libtcod.console_new(screen_width, screen_height) # Initialize the map game_map = GameMap(map_width, map_height) game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities, max_monsters_per_room) # Variable to recompute FOV fov_recompute = True # Initialize field of view fov_map = initialize_fov(game_map) # Store keyboard and mouse input key = libtcod.Key() mouse = libtcod.Mouse() # Initiatlize the game state game_state = GameStates.PLAYER_TURN # Main game loop while not libtcod.console_is_window_closed(): # Captures keyboard and mouse input libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse) # Recompute FOV if player has moved if fov_recompute: recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) # Draws entities and map render_all(con, entities, game_map, fov_map, fov_recompute, screen_width, screen_height, colors) fov_recompute = False # Redraws the screen libtcod.console_flush() # Erases old positions of entities clear_all(con, entities) # Leaves a red dot to be drawn next time the @ moves libtcod.console_set_default_foreground(con, libtcod.red) libtcod.console_put_char(con, player.x, player.y, '.', libtcod.BKGND_NONE) # Handles key presses action = handle_keys(key) move = action.get('move') exit = action.get('exit') fullscreen = action.get('fullscreen') # If "move" and is the player's turn, moves the player if move and game_state == GameStates.PLAYER_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy # Check if the space is blocked by a wall before moving if not game_map.is_blocked(destination_x, destination_y): # And if it's blocked by an entity target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: print('You kick the ' + target.name + ' in the shins, ' + 'much to its annoyance!') else: player.move(dx, dy) # Recompute FOV after moving fov_recompute = True # Change to enemy's turn game_state = GameStates.ENEMY_TURN # If it's the enemy's turn, move the enemies if game_state == GameStates.ENEMY_TURN: # Every monster does nothing for entity in entities: if entity != player: print('The ' + entity.name + ' ponders the meaning of ' + 'its existence.') # Change to player's turn game_state = GameStates.PLAYER_TURN if exit: return True # If "fullscreen"", toggles fullscreen if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
def main(): constants = get_constants() # Instantiate main window libtcod.console_set_custom_font( "arial10x10.png", libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(constants["screen_width"], constants["screen_height"], constants["window_title"], False) # Instantiate offscreen window for drawing window_main = libtcod.console_new(constants["screen_width"], constants["screen_height"]) # Instantiate UI window ui_panel = libtcod.console_new(constants["screen_width"], constants["ui_panel_height"]) player = None entities = [] game_map = None message_log = None game_state = None show_main_menu = True show_load_error_message = False main_menu_background_image = libtcod.image_load( "ainsley.png") #("menu_background.png") key = libtcod.Key() mouse = libtcod.Mouse() while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) if show_main_menu: action_keyboard = handle_main_menu_keys(key) # .get() returns None if not found new_game = bool(action_keyboard.get("new_game")) load_saved_game = bool(action_keyboard.get("load_game")) exit_game = bool(action_keyboard.get("exit")) menu_click_results = main_menu(window_main, main_menu_background_image, constants["screen_width"], constants["screen_height"], mouse) # Handle results of mouse click on menu item for result in menu_click_results: item_clicked = chr(result.get("item_clicked")) if item_clicked: action_mouse = get_main_menu_option_from_index( item_clicked) new_game |= bool(action_mouse.get("new_game")) load_saved_game |= bool(action_mouse.get("load_game")) exit_game |= bool(action_mouse.get("exit")) if show_load_error_message: message_box(window_main, "No save game to load", 50, constants["screen_width"], constants["screen_height"]) libtcod.console_flush() if show_load_error_message and (new_game or load_saved_game or exit_game): show_load_error_message = False elif new_game: player, entities, game_map, message_log, game_state = get_game_variables( constants) game_state = GameStates.PLAYER_TURN show_main_menu = False elif load_saved_game: try: player, entities, game_map, message_log, game_state = load_game( ) show_main_menu = False except FileNotFoundError: show_load_error_message = True elif exit_game: break else: libtcod.console_clear(window_main) play_game(player, entities, game_map, message_log, game_state, window_main, ui_panel, constants, key, mouse) show_main_menu = True
def window_is_closed(): return tcod.console_is_window_closed()
def main(): screen_width = 80 screen_height = 50 map_width = 70 map_height = 40 room_max_size = 10 room_min_size = 5 max_rooms = 30 colors = { 'dark_wall': libtcod.Color(0, 0, 100), 'dark_ground': libtcod.Color(50, 50, 150) } player = Entity(int(screen_width / 2), int(screen_height / 2), '@', libtcod.white) npc = Entity(int(screen_width / 2 + 5), int(screen_height / 2), '@', libtcod.yellow) entities = [npc, player] libtcod.console_set_custom_font( 'dejavu_wide16x16_gs_tc.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(screen_width, screen_height, 'Roguelike test', False) con = libtcod.console_new(screen_width, screen_height) game_map = GameMap(map_width, map_height) game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player) key = libtcod.Key() mouse = libtcod.Mouse() while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse) render_all(con, entities, game_map, screen_width, screen_height, colors) libtcod.console_flush() clear_all(con, entities) action = handle_keys(key) move = action.get('move') exit = action.get('exit') fullscreen = action.get('fullscreen') if move: dx, dy = move if not game_map.is_blocked(player.x + dx, player.y + dy): player.move(dx, dy) if exit: return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
def play_game(player, entities, game_map, message_log, game_state, con, panel, animation_console, constants): fov_recompute = True fov_map = initialize_fov(game_map) key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYERS_TURN previous_game_state = game_state camera = Camera( x=0, y=0, width=constants['screen_width'], height=constants['screen_height'], map_width=constants['map_width'], map_height=constants['map_height'], ) camera.update(player) targeting_item = None weapon_target = None while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) x_in_camera, y_in_camera = camera.apply(player.x, player.y) if fov_recompute: recompute_fov(fov_map, player.x, player.y, constants['fov_radius'], constants['fov_light_walls'], constants['fov_algorithm']) render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], constants['bar_width'], constants['panel_height'], constants['panel_y'], mouse, constants['colors'], game_state, camera) fov_recompute = False libtcod.console_flush() clear_all(con, entities, camera) action = handle_keys(key, game_state) mouse_action = handle_mouse(mouse) move = action.get('move') wait = action.get('wait') pickup = action.get('pickup') show_inventory = action.get('show_inventory') drop_inventory = action.get('drop_inventory') inventory_index = action.get('inventory_index') take_stairs = action.get('take_stairs') level_up = action.get('level_up') show_character_screen = action.get('show_character_screen') targeter = action.get('targeter') fire = action.get('fire') exit = action.get('exit') fullscreen = action.get('fullscreen') left_click = mouse_action.get('left_click') right_click = mouse_action.get('right_click') player_turn_results = [] if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: attack_results = player.fighter.attack(target) player_turn_results.extend(attack_results) else: player.move(dx, dy) camera.update(player) fov_recompute = True for entity in entities: if entity != player and entity.x == player.x and entity.y == player.y: see_results = [{ 'message': Message('{0}(이)가 보인다.'.format(entity.name), libtcod.white) }] player_turn_results.extend(see_results) game_state = GameStates.ENEMY_TURN elif wait: game_state = GameStates.ENEMY_TURN elif pickup and game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.item and entity.x == player.x and entity.y == player.y: pickup_results = player.inventory.add_item(entity) player_turn_results.extend(pickup_results) break else: message_log.add_message( Message('여기에는 주울 수 있는 것이 없다.', libtcod.yellow)) if targeter: previous_game_state = GameStates.PLAYERS_TURN testfunc() game_state = GameStates.WEAPON_TARGETING if show_inventory: previous_game_state = game_state game_state = GameStates.SHOW_INVENTORY if drop_inventory: previous_game_state = game_state game_state = GameStates.DROP_INVENTORY if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len( player.inventory.items): item = player.inventory.items[inventory_index] if game_state == GameStates.SHOW_INVENTORY: player_turn_results.extend( player.inventory.use(item, entities=entities, fov_map=fov_map)) elif game_state == GameStates.DROP_INVENTORY: player_turn_results.extend(player.inventory.drop_item(item)) if take_stairs and game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.stairs and entity.x == player.x and entity.y == player.y: entities = game_map.next_floor(player, message_log, constants) fov_map = initialize_fov(game_map) fov_recompute = True camera.update(player) libtcod.console_clear(con) break else: message_log.add_message(Message('여기에는 계단이 없다.', libtcod.yellow)) if level_up: if level_up == 'hp': player.fighter.base_max_hp += 20 player.fighter.hp += 20 elif level_up == 'str': player.fighter.base_power += 1 elif level_up == 'def': player.fighter.base_ += 1 game_state = previous_game_state if show_character_screen: previous_game_state = game_state game_state = GameStates.CHARACTER_SCREEN if game_state == GameStates.CHARACTER_SCREEN: x, y = get_mouse_movement(mouse) get_player_tooltip(animation_console, x, y, mouse, constants['screen_width'], constants['screen_height']) if left_click: game_state = previous_game_state if game_state == GameStates.WEAPON_TARGETING: wx, wy = get_mouse_movement(mouse) get_targeting_radius( con, panel, wx, wy, entities, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], constants['bar_width'], constants['panel_height'], constants['panel_y'], mouse, constants['colors'], game_state, camera, left_click, right_click, animation_console) if left_click: weapon_target_x, weapon_target_y = left_click weapon_target_x -= camera.x weapon_target_y -= camera.y if not libtcod.map_is_in_fov(fov_map, weapon_target_x, weapon_target_y): message_log.add_message(Message('시야 밖의 적을 목표로 지정할 수는 없다.')) for entity in entities: if entity.distance( weapon_target_x, weapon_target_y) == 0 and entity.name == 'Player': message_log.add_message( Message('자기 자신을 목표로 지정할 수는 없다.')) elif entity.distance( weapon_target_x, weapon_target_y) == 0 and entity.fighter: player_turn_results.append({'wep_targetted': True}) weapon_target = entity elif right_click: player_turn_results.append({'targeting_cancelled': True}) if fire: #수동으로 타겟을 잡았거나, 자동 발사로 타겟이 잡혔을 때 #원거리 무기 미장비시 if not player.equipment.main_hand: message_log.add_message(Message('발사할 수 있는 것을 장비하고 있지 않다.')) #원거리 무기 장비시 elif player.equipment.main_hand.equippable.ranged_weapon == True: #타겟이 지정되었을 때 if weapon_target is not None: print(weapon_target) message_log.add_message( Message('당신은 {0}을(를) 발사한다! '.format( player.equipment.main_hand.name))) attack_results = player.fighter.attack(weapon_target) player_turn_results.extend(attack_results) if weapon_target.fighter.hp <= 0: weapon_target = None game_state = GameStates.ENEMY_TURN #타겟이 지정되지 않았을 때 자동 발사 else: closest_distance = 10 + 1 for entity in entities: if entity.fighter and libtcod.map_is_in_fov( fov_map, entity.x, entity.y ) and entity.name != 'Player' and entity.blocks == True: distance = player.distance_to(entity) if distance < closest_distance: weapon_target = entity closest_distance = distance #자동 발사 대상 지정 후 발사, 타겟 지정 if weapon_target: message_log.add_message( Message('당신은 {0}을(를) 발사한다! '.format( player.equipment.main_hand.name))) attack_results = player.fighter.attack(weapon_target) player_turn_results.extend(attack_results) if weapon_target.fighter.hp <= 0: weapon_target = None game_state = GameStates.ENEMY_TURN #타겟이 지정되지 않았고 적이 Fov 외에 있을 때 else: message_log.add_message( Message('사격할 수 있는 대상이 보이지 않는다.')) weapon_target = None game_state = GameStates.ENEMY_TURN else: message_log.add_message(Message('발사할 수 있는 것을 장비하고 있지 않다.')) if game_state == GameStates.TARGETING: x, y = get_mouse_movement(mouse) get_targeting_radius( con, panel, x, y, entities, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], constants['bar_width'], constants['panel_height'], constants['panel_y'], mouse, constants['colors'], game_state, camera, left_click, right_click, animation_console) if left_click: target_x, target_y = left_click target_x -= camera.x target_y -= camera.y item_use_results = player.inventory.use(targeting_item, entities=entities, fov_map=fov_map, target_x=target_x, target_y=target_y) player_turn_results.extend(item_use_results) elif right_click: player_turn_results.append({'targeting_cancelled': True}) if exit: if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY, GameStates.CHARACTER_SCREEN): game_state = previous_game_state elif game_state == GameStates.LEVEL_UP: level_up_menu(con, 'Level up! Choose a stat to raise:', player, 40, constants['screen_width'], constants['screen_height']) elif game_state == GameStates.CHARACTER_SCREEN: character_screen(player, 30, 10, constants['screen_width'], constants['screen_height']) elif game_state == GameStates.TARGETING: player_turn_results.append({'targeting_cancelled': True}) else: save_game(player, entities, game_map, message_log, game_state) return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') item_added = player_turn_result.get('item_added') item_consumed = player_turn_result.get('consumed') item_dropped = player_turn_result.get('item_dropped') equip = player_turn_result.get('equip') targeting = player_turn_result.get('targeting') targeting_cancelled = player_turn_result.get('targeting_cancelled') wep_targetted = player_turn_result.get('wep_targetted') xp = player_turn_result.get('xp') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: victim_cord_x, victim_cord_y = get_victim_cord(dead_entity) explosion(con, panel, victim_cord_x, victim_cord_y, entities, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], mouse, constants['colors'], camera, animation_console) blood_splatter(con, game_map, victim_cord_x, victim_cord_y, constants['colors']) libtcod.console_clear(con) fov_recompute = True message = kill_monster(dead_entity) pass message_log.add_message(message) if item_added: entities.remove(item_added) game_state = GameStates.ENEMY_TURN if item_consumed: game_state = GameStates.ENEMY_TURN if item_dropped: entities.append(item_dropped) game_state = GameStates.ENEMY_TURN if equip: equip_results = player.equipment.toggle_equip(equip) for equip_result in equip_results: equipped = equip_result.get('equipped') dequipped = equip_result.get('dequipped') if equipped: message_log.add_message( Message('{0}(을)를 장비했다.'.format(equipped.name))) if dequipped: message_log.add_message( Message('{0}(을)를 해제했다.'.format(dequipped.name))) game_state = GameStates.ENEMY_TURN if wep_targetted: game_state = previous_game_state message_log.add_message(Message('당신은 목표를 조준한다.')) if targeting: previous_game_state = GameStates.PLAYERS_TURN game_state = GameStates.TARGETING targeting_item = targeting message_log.add_message(targeting_item.item.targeting_message) if targeting_cancelled: game_state = previous_game_state message_log.add_message(Message('목표 지정을 취소하였다.')) if xp: leveled_up = player.level.add_xp(xp) message_log.add_message( Message('당신은 {0}의 경험치를 얻었다..'.format(xp))) if leveled_up: message_log.add_message( Message( '레벨 {0}에 도달하였다!'.format(player.level.current_level) + '!', libtcod.yellow)) previous_game_state = game_state game_state = GameStates.LEVEL_UP if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn( player, fov_map, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYERS_TURN
def play_game(player, entities, game_map, message_log, game_state, con, panel, cursor, levellist, floorentities, dstairxy, ustairxy, floor, highest_floor, constants): debug = False key = libtcod.Key() mouse = libtcod.Mouse() hasorb = False previous_game_state = game_state levelstodrain = math.floor(constants['top_level'] / constants['start_level']) fov_recompute = True fov_map = initialize_fov(game_map) targeting_item = None targeting_with_item = False while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) if fov_recompute: recompute_fov(fov_map, player.x, player.y, constants['fov_radius'], constants['fov_light_walls'], constants['fov_algorithim']) render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], constants['bar_width'], constants['panel_height'], constants['panel_y'], mouse, constants['colors'], game_state) libtcod.console_flush() clear_all(con, entities) action = handle_keys(key, game_state) move = action.get('move') wait = action.get('wait') pickup = action.get('pickup') show_inventory = action.get('show_inventory') inventory_index = action.get('inventory_index') spell_index = action.get('spell_index') drop_inventory = action.get('drop_inventory') stairs_up = action.get('stairs_up') stairs_down = action.get('stairs_down') show_character_screen = action.get('show_character_screen') exit = action.get('exit') targeted = action.get('targeted') cast_spell = action.get('cast_spell') fullscreen = action.get('fullscreen') player_turn_results = [] if show_character_screen: previous_game_state = game_state game_state = GameStates.CHARACTER_SCREEN if game_state == GameStates.TARGETING: if move: dx, dy = move cursor.move(dx, dy) if targeted: if (targeting_with_item == True): targeting_results = player.inventory.use(targeting_item, entities=entities, fov_map=fov_map, target_x=cursor.x, target_y=cursor.y) else: targeting_results = player.spellcaster.cast( targeting_spell, entities=entities, fov_map=fov_map, target_x=cursor.x, target_y=cursor.y) player_turn_results.extend(targeting_results) targeting_with_item = False player_turn_results.append({'targeting_over': True}) if game_state == GameStates.PLAYERS_TURN: if stairs_up: for entity in entities: if entity.stairs and entity.x == player.x and entity.y == player.y and entity.downstairs == False: if floor == highest_floor: levellist[floor] = copy.deepcopy(game_map) floorentities[floor] = entities ustairxy[floor] = [player.x, player.y] floor = floor + 1 highest_floor = highest_floor + 1 entities = game_map.next_floor( player, cursor, message_log, constants) fov_map = initialize_fov(game_map) fov_recompute = True dstairxy[floor] = [player.x, player.y] libtcod.console_clear(con) if ((floor % levelstodrain) == 0) and (player.level.current_level > 1): #if True: #test code obviously player.level.add_xp( -1 * player.level.experiance_to_previous_level) message_log.add_message( Message( 'You grow weaker as you approach the Orb of Undeath. You are now level {0}' .format(player.level.current_level) + '.', libtcod.red)) if (debug == True): message_log.add_message( Message( 'Did I mention debug mode was on?', libtcod.red)) player.fighter.base_max_hp -= constants[ 'hp_per_level'] if (player.fighter.hp > constants['hp_per_level']): player.fighter.hp -= constants[ 'hp_per_level'] else: player.fighter.hp = 1 player.spellcaster.delevel( constants['mp_per_level']) player.fighter.base_power -= constants[ 'power_per_level'] else: levellist[floor] = copy.deepcopy(game_map) floorentities[floor] = entities floor = floor + 1 game_map = levellist[floor] playerindex = entities.index(player) cursorindex = entities.index(cursor) entities = floorentities[floor] player = entities[playerindex] cursor = entities[cursorindex] xyref = dstairxy[floor] player.x = xyref[0] player.y = xyref[1] fov_map = initialize_fov(game_map) fov_recompute = True libtcod.console_clear(con) break else: message_log.add_message( Message('There are no stairs here.', libtcod.white)) if stairs_down: for entity in entities: if entity.stairs and entity.x == player.x and entity.y == player.y and entity.downstairs == True: for item in player.inventory.items: if item.name == "Orb of Undeath": hasorb = True if floor == highest_floor: levellist[floor] = copy.deepcopy(game_map) floorentities[floor] = entities floor = floor - 1 else: levellist[floor] = copy.deepcopy(game_map) floorentities[floor] = entities floor = floor - 1 game_map = levellist[floor] playerindex = entities.index(player) cursorindex = entities.index(cursor) entities = floorentities[floor] entities[playerindex] = player entities[cursorindex] = cursor xyref = ustairxy[floor] player.x = xyref[0] player.y = xyref[1] fov_map = initialize_fov(game_map) fov_recompute = True libtcod.console_clear(con) messageresult = animate_all(entities=entities, number=5, player=player) message_log.add_message( messageresult[0].get('message')) break elif entity.x == player.x and entity.y == player.y: for item in player.inventory.items: if item.name == "Orb of Undeath": hasorb = True if hasorb == False and entity.name == 'exit': message_log.add_message( Message( 'You can not leave without the Orb! The fate of the world depends on it!.', libtcod.white)) break elif hasorb == True and entity.name == 'exit': message_log.add_message( Message( 'You escape with the Orb of Undeath! You win!', libtcod.purple)) return 1 else: message_log.add_message( Message('There are no stairs here.', libtcod.white)) if move: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: attack_results = player.fighter.attack(target) player_turn_results.extend(attack_results) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN elif wait: game_state = GameStates.ENEMY_TURN elif pickup: for entity in entities: if sametile(player, entity): if entity.render_order == RenderOrder.ITEM: if entity.name == "Orb of Undeath": hasorb = True pickup_results = player.inventory.add_item(entity) player_turn_results.extend(pickup_results) break else: message_log.add_message( Message('You pick up a large handful of air.')) if show_inventory: previous_game_state = game_state game_state = GameStates.SHOW_INVENTORY if cast_spell: previous_game_state = game_state game_state = GameStates.CAST_SPELL if drop_inventory: previous_game_state = game_state game_state = GameStates.DROP_INVENTORY if spell_index is not None and spell_index < ( player.spellcaster.spell_number): player_turn_results.extend( player.spellcaster.cast(spell_index + 1, entities=entities, fov_map=fov_map)) if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len( player.inventory.items): item = player.inventory.items[inventory_index] if game_state == GameStates.SHOW_INVENTORY: player_turn_results.extend( player.inventory.use(item, entities=entities, fov_map=fov_map)) elif game_state == GameStates.DROP_INVENTORY: player_turn_results.extend(player.inventory.drop_item(item)) if exit: if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY, GameStates.CHARACTER_SCREEN, GameStates.CAST_SPELL): game_state = previous_game_state elif game_state == GameStates.TARGETING: player_turn_results.append({'targeting_cancelled': True}) else: save_game(player, entities, game_map, message_log, game_state, cursor, levellist, floorentities, dstairxy, ustairxy, floor, highest_floor) return 0 if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) for player_turn_result in player_turn_results: #checking through results of the player's turn message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') item_added = player_turn_result.get('item_added') item_consumed = player_turn_result.get('consumed') player_cast_spell = player_turn_result.get('player_cast_spell') item_dropped = player_turn_result.get('item_dropped') targeting_from_item = player_turn_result.get('targeting_item') targeting_from_spell = player_turn_result.get('targeting_spell') targeting_cancelled = player_turn_result.get('targeting_cancelled') targeting_over = player_turn_result.get('targeting_over') xp = player_turn_result.get('xp') equip = player_turn_result.get('equip') itemdestroyed = player_turn_result.get('itemdestroyed') if message: message_log.add_message(message) if targeting_from_item: targeting_with_item = True previous_game_state = GameStates.PLAYERS_TURN game_state = GameStates.TARGETING targeting_item = targeting_from_item cursor.x = player.x cursor.y = player.y cursor.visible = True message_log.add_message(Message('Press g to select target.')) if targeting_from_spell: previous_game_state = GameStates.PLAYERS_TURN game_state = GameStates.TARGETING targeting_spell = targeting_from_spell cursor.x = player.x cursor.y = player.y cursor.visible = True message_log.add_message(Message('Press g to select target.')) if dead_entity: if dead_entity == player: if debug == False: render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], constants['bar_width'], constants['panel_height'], constants['panel_y'], mouse, constants['colors'], game_state) return 2 else: player.fighter.hp = player.fighter.max_hp message = Message('You get better.', libtcod.red) else: message = death(dead_entity) message_log.add_message(message) if itemdestroyed: player.inventory.drop_item(itemdestroyed) message = destroy_item(itemdestroyed) message_log.add_message(message) end_item(itemdestroyed) if item_added: previous_game_state = GameStates.ENEMY_TURN entities.remove(item_added) game_state = GameStates.ENEMY_TURN if item_consumed: previous_game_state = GameStates.ENEMY_TURN game_state = GameStates.ENEMY_TURN if item_dropped: entities.append(item_dropped) previous_game_state = GameStates.ENEMY_TURN game_state = GameStates.ENEMY_TURN if equip: if (player.fighter.hp > player.fighter.max_hp): player.fighter.hp = player.fighter.max_hp equip_results = player.equipment.toggle_equip(equip) for equip_result in equip_results: equipped = equip_result.get('equipped') dequipped = equip_result.get('dequipped') if equipped: message_log.add_message( Message('You equipped the {0}'.format( equipped.name))) if dequipped: message_log.add_message( Message('You removed the {0}'.format( dequipped.name))) game_state = GameStates.ENEMY_TURN if targeting_cancelled: message_log.add_message(Message('Targetting cancelled')) if targeting_cancelled or targeting_over: cursor.visible = False game_state = previous_game_state if player_cast_spell: previous_game_state = GameStates.ENEMY_TURN game_state = GameStates.ENEMY_TURN if xp: leveled_up = player.level.add_xp(xp) if (xp < 0): message_log.add_message( Message('You lose {0} XP'.format(abs(xp)))) else: message_log.add_message( Message('You gain {0} XP'.format(abs(xp)))) if leveled_up == 1: message_log.add_message( Message( 'You grow stronger! You reached level {0}'.format( player.level.current_level) + '!', libtcod.yellow)) player.fighter.base_max_hp += constants['hp_per_level'] player.fighter.hp += constants['hp_per_level'] player.fighter.base_power += constants['power_per_level'] player.spellcaster.levelup(constants['mp_per_level']) elif leveled_up == 2: if player.level.current_level > 0: message_log.add_message( Message( 'You grow weaker. You are now level {0}'. format(player.level.current_level) + '.', libtcod.red)) player.fighter.base_max_hp -= constants['hp_per_level'] if (player.fighter.hp > constants['hp_per_level']): player.fighter.hp -= constants['hp_per_level'] else: player.fighter.hp = 1 player.fighter.base_power -= constants[ 'power_per_level'] player.spellcaster.delevel(constants['mp_per_level']) else: player.level.current_level = 1 message_log.add_message( Message( 'You can grow no weaker. You stay level {0}'. format(player.level.current_level) + '.', libtcod.red)) if game_state == GameStates.ENEMY_TURN: #enemy turn for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn( player, fov_map, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') itemdestroyed = enemy_turn_result.get('itemdestroyed') if message: message_log.add_message(message) if itemdestroyed: player.inventory.drop_item(itemdestroyed) message = destroy_item(itemdestroyed) message_log.add_message(message) end_item(itemdestroyed) if dead_entity: if dead_entity == player: if debug == False: render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], constants['bar_width'], constants['panel_height'], constants['panel_y'], mouse, constants['colors'], game_state) return 2 else: player.fighter.hp = player.fighter.max_hp message = Message('You get better.', libtcod.red) else: message = death(dead_entity) message_log.add_message(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYERS_TURN
def play_game(player, entities, game_map, message_log, game_state, window_main, ui_panel, constants, key, mouse): prev_game_state = game_state targeting_item = None # Keep track of item requiring targeting that player attempts to use # Instantiate FOV variables fov_recompute = True fov_map = initialize_fov(game_map) # Make sure it's the player's turn before starting game_state = GameStates.PLAYER_TURN # Main game loop while not libtcod.console_is_window_closed(): # Check for player input libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) # Get player FOV if fov_recompute: recompute_fov(fov_map, player.x, player.y, constants["fov_radius"], constants["fov_light_walls"], constants["fov_algorithm"]) # Render map, entities, player FOV menu_click_results = render_all( window_main, ui_panel, entities, game_map, fov_map, fov_recompute, message_log, constants["screen_width"], constants["screen_height"], constants["ui_panel_width"], constants["ui_panel_height"], constants["ui_panel_y"], mouse, constants["colors"], game_state) fov_recompute = False # Display rendered content libtcod.console_flush() # Clear entities for sake of updating positions. clear_all(window_main, entities) # Get user input and parse/handle it action = handle_keys(key, game_state) mouse_action = handle_mouse(mouse) move = action.get("move") # player move fullscreen_key_pressed = action.get("fullscreen") wait = action.get("wait") # don't move during turn pickup = action.get("pickup") # pick up item show_inventory = action.get("show_inventory") inventory_index = action.get("inventory_index") drop_inventory = action.get("drop_inventory") take_stairs = action.get("take_stairs") level_up = action.get("level_up") show_character_screen = action.get("show_character_screen") exit_key_pressed = action.get("exit") left_click = mouse_action.get("left_click") right_click = mouse_action.get("right_click") # Handle results of inventory item click for result in menu_click_results: item_clicked = result.get("item_clicked") if item_clicked: option = get_inventory_option_from_index(item_clicked) option = dict(option, **get_level_up_option_from_index( item_clicked)) # extend dictionary inventory_index = option.get("inventory_index") level_up = option.get("level_up") # Handle player actions if it's their turn player_turn_results = [ ] # To store messages for results of player actions if move and game_state == GameStates.PLAYER_TURN: # Update player position dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_tile_blocked(destination_x, destination_y): # If monster is blocking target tile, attack it. # Otherwise, move to target tile. target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: player_turn_results.extend(player.fighter.attack(target)) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN # End player's turn # Player waiting elif wait and game_state == GameStates.PLAYER_TURN: game_state = GameStates.ENEMY_TURN message_log.add_message(Message("You wait.", libtcod.white)) # Player picks up item elif pickup and game_state == GameStates.PLAYER_TURN: for entity in entities: if entity.item and entity.x == player.x and entity.y == player.y: pickup_results = player.inventory.add_item(entity) player_turn_results.extend(pickup_results) break else: message_log.add_message( Message("There is nothing here to pick up.", libtcod.yellow)) if show_inventory: prev_game_state = game_state game_state = GameStates.SHOW_INVENTORY if drop_inventory: prev_game_state = game_state game_state = GameStates.DROP_INVENTORY # Handle using/dropping items in inventory if inventory_index is not None and \ prev_game_state != GameStates.PLAYER_DEAD and \ inventory_index < len(player.inventory.items): item = player.inventory.items[inventory_index] if game_state == GameStates.SHOW_INVENTORY: player_turn_results.extend( player.inventory.use_item(item, entities=entities, fov_map=fov_map)) elif game_state == GameStates.DROP_INVENTORY: player_turn_results.extend(player.inventory.drop_item(item)) # Handle player taking stairs down if take_stairs and game_state == GameStates.PLAYER_TURN: for entity in entities: if entity.stairs and entity.x == player.x and entity.y == player.y: entities = game_map.next_floor(player, message_log, constants) fov_map = initialize_fov(game_map) fov_recompute = True libtcod.console_clear(window_main) break else: message_log.add_message( Message("There are no stairs here.", libtcod.yellow)) if level_up: if level_up == "hp": player.fighter.base_max_hp += 20 player.fighter.hp += 20 elif level_up == "str": player.fighter.base_power += 1 elif level_up == "def": player.fighter.base_defense += 1 game_state = prev_game_state if show_character_screen: prev_game_state = game_state game_state = GameStates.CHARACTER_SCREEN # Targeting mode for item. # Left click selects target tile, right click cancels targeting. if game_state == GameStates.TARGETING: if left_click: target_x, target_y = left_click item_use_results = player.inventory.use_item(targeting_item, entities=entities, fov_map=fov_map, target_x=target_x, target_y=target_y) player_turn_results.extend(item_use_results) elif right_click: player_turn_results.append({"targeting_cancelled": True}) # Enter fullscreen mode if fullscreen_key_pressed: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) # Exit events if exit_key_pressed: # Exit menu if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY, GameStates.CHARACTER_SCREEN): game_state = prev_game_state # Exit targeting mode elif game_state == GameStates.TARGETING: player_turn_results.append({"targeting_cancelled": True}) # Exit game else: # Save before exiting save_game(player, entities, game_map, message_log, game_state) return True # Handle results of player's turn # (!) Must go after all changes to player_turn_results for result in player_turn_results: message = result.get("message") dead_entity = result.get("dead") item_added = result.get("item_added") item_consumed = result.get("item_consumed") item_dropped = result.get("item_dropped") equip = result.get("equip") targeting = result.get("targeting") targeting_cancelled = result.get("targeting_cancelled") xp = result.get("xp") if message: message_log.add_message(message) # Handle player death and/or monster death if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) # If player picks up item, remove it from entity list and end player turn if item_added: entities.remove(item_added) game_state = GameStates.ENEMY_TURN # If player drops item, end turn if item_dropped: print("item dropped") entities.append(item_dropped) game_state = GameStates.ENEMY_TURN if equip: equip_results = player.equipment.toggle_equip(equip) for equip_result in equip_results: equipped = equip_result.get("equipped") unequipped = equip_result.get("unequipped") if equipped: message_log.add_message( Message("You equipped the {0}.".format( equipped.name))) if unequipped: message_log.add_message( Message("You unequipped the {0}.".format( unequipped.name))) game_state = GameStates.ENEMY_TURN # If player uses an item, end turn if item_consumed: game_state = GameStates.ENEMY_TURN if targeting_cancelled: game_state = prev_game_state prev_game_state = GameStates.PLAYER_TURN message_log.add_message(Message("Targeting cancelled.")) if targeting: prev_game_state = game_state game_state = GameStates.TARGETING targeting_item = targeting message_log.add_message(targeting_item.item.targeting_message) if xp: leveled_up = player.level.add_xp(xp) message_log.add_message( Message("You gain {0} experience points!".format(xp))) if leveled_up: message_log.add_message( Message( "You feel power surge through you! Welcome to level {0}." .format(player.level.current_level) + '!', libtcod.yellow)) prev_game_state = game_state game_state = GameStates.LEVEL_UP # Handle enemy actions if it's their turn if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: # Filters out player since player doesn't have AI component # Do A* pathing towards player if monster is within player FOV enemy_turn_results = entity.ai.take_turn( player, fov_map, game_map, entities) # Handle results of enemy action for result in enemy_turn_results: message = result.get("message") dead_entity = result.get("dead") if message: message_log.add_message(message) # Handle player death and/or monster death if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) # Stop handling enemy turns if player has died. if game_state == GameStates.PLAYER_DEAD: break # Skip setting turn back to player if player is dead if game_state == GameStates.PLAYER_DEAD: break # End enemy turns else: game_state = GameStates.PLAYER_TURN
def main(): screen_width = 80 screen_height = 50 map_width = 80 map_height = 45 max_monsters_per_room = 3 room_max_size = 10 room_min_size = 6 max_rooms = 30 fov_algorithm = 0 fov_light_walls = True fov_radius = 10 colors = { 'dark_wall': libtcod.Color(0, 0, 100), 'dark_ground': libtcod.Color(50, 50, 150), 'light_wall': libtcod.Color(130, 110, 50), 'light_ground': libtcod.Color(200, 180, 50) } fov_recompute = True key = libtcod.Key() mouse = libtcod.Mouse() game_state = GameStates.PLAYERS_TURN fighter_component = Fighter(hp=30, defense=2, power=5) player = Entity(30, 30, '@', libtcod.white, 'Player', blocks=True, fighter=fighter_component) entities = [player] npc = Entity(int(screen_width / 2 - 5), int(screen_height / 2), '@', libtcod.yellow, 'NPC', blocks=True) entities = [npc, player] libtcod.console_set_custom_font( 'arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(screen_width, screen_height, 'libtcod tutorial revised', False) con = libtcod.console_new(screen_width, screen_height) game_map = GameMap(map_width, map_height) game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities, max_monsters_per_room) fov_map = initialize_fov(game_map) while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse) if fov_recompute: recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) render_all(con, entities, game_map, fov_map, fov_recompute, screen_width, screen_height, colors) fov_recompute = False libtcod.console_flush() clear_all(con, entities) action = handle_keys(key) move = action.get('move') exit = action.get('exit') fullscreen = action.get('fullscreen') if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: player.fighter.attack(target) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN print(game_map.is_blocked(player.x + dx, player.y + dy)) if exit: return True if fullscreen: libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: entity.ai.take_turn(player, fov_map, game_map, entities) game_state = GameStates.PLAYERS_TURN
def main(): constants = get_constants() libtcod.console_set_custom_font( 'terminal8x12_gs_ro.png', libtcod.FONT_TYPE_GRAYSCALE | libtcod.FONT_LAYOUT_ASCII_INROW) libtcod.console_init_root(constants['screen_width'], constants['screen_height'], constants['window_title'], False) con = libtcod.console_new(constants['screen_width'], constants['screen_height']) panel = libtcod.console_new(constants['screen_width'], constants['panel_height']) player = None entities = [] game_map = None game_state = None show_main_menu = 0 show_load_error_message = False key = libtcod.Key() mouse = libtcod.Mouse() while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event( libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse) if show_main_menu == 0: main_menu(con, constants['screen_width'], constants['screen_height']) if show_load_error_message: message_box(con, 'Save game not found', 50, constants['screen_width'], constants['screen_height']) libtcod.console_flush() action = handle_main_menu(key) new_game = action.get('new_game') load_saved_game = action.get('load_game') exit_game = action.get('exit') if show_load_error_message and (new_game or load_saved_game or exit_game): show_load_error_message = False elif new_game: if not os.path.isfile('savegame.dat'): player, entities, game_map, message_log, game_state, cursor, levellist, floorentities, dstairxy, ustairxy, floor, highest_floor = get_game_variables( constants) game_state = GameStates.PLAYERS_TURN show_main_menu = 3 else: show_main_menu = 4 elif load_saved_game: try: player, entities, game_map, message_log, game_state, cursor, levellist, floorentities, dstairxy, ustairxy, floor, highest_floor = load_game( ) show_main_menu = 3 except FileNotFoundError: show_load_error_message = True elif exit_game: break elif show_main_menu == 1 or show_main_menu == 2: try: os.remove('savegame.dat') except FileNotFoundError: filedeleted = True if show_main_menu == 1: victory_screen(con, constants['screen_width'], constants['screen_height']) else: game_over(con, constants['screen_width'], constants['screen_height']) libtcod.console_flush() action = handle_death(key) new_game = action.get('new_game') exit_game = action.get('exit') if show_load_error_message and (new_game or load_saved_game or exit_game): show_load_error_message = False elif new_game: player, entities, game_map, message_log, game_state, cursor, levellist, floorentities, dstairxy, ustairxy, floor, highest_floor = get_game_variables( constants) game_state = GameStates.PLAYERS_TURN show_main_menu = 3 elif exit_game: break elif show_main_menu == 4: #checking to see if player is sure areyousure(con, constants['screen_width'], constants['screen_height']) libtcod.console_flush() action = handle_sure(key) issure = action.get('sure') notsure = action.get('exit') if issure: player, entities, game_map, message_log, game_state, cursor, levellist, floorentities, dstairxy, ustairxy, floor, highest_floor = get_game_variables( constants) game_state = GameStates.PLAYERS_TURN show_main_menu = 3 if notsure: show_main_menu = 0 else: libtcod.console_clear(con) show_main_menu = play_game(player, entities, game_map, message_log, game_state, con, panel, cursor, levellist, floorentities, dstairxy, ustairxy, floor, highest_floor, constants)
import libtcodpy as tcod import settings from menu import menu from menu import msgbox from new_game import new_game from play_game import play_game settings.init() if __name__ == "__main__": img = tcod.image_load('assets/images/menu_background1.png') while not tcod.console_is_window_closed(): tcod.image_blit_2x(img, 0, 0, 0) tcod.console_set_default_foreground(0, tcod.light_yellow) tcod.console_print_ex(0, settings.SCREEN_WIDTH // 2, settings.SCREEN_HEIGHT // 2 - 4, tcod.BKGND_NONE, tcod.CENTER, 'Legend of the Boner Dome') tcod.console_print_ex(0, settings.SCREEN_WIDTH // 2, settings.SCREEN_HEIGHT - 2, tcod.BKGND_NONE, tcod.CENTER, 'By Jack Chick') choice = menu('', ['Play a new game', 'Continue last game', 'Quit'], 24, new_game=True) if choice == 0: game = new_game() if game is not None: play_game()
def main(): player = Object(1, 1, '@', libtcod.red) libtcod.console_set_custom_font( 'arial12x12.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) # specify screen size, title and whether or not fullscreen for root console libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'maze game', False) # off-screen console for the map con = libtcod.console_new(MAP_WIDTH, MAP_HEIGHT) # off-screen console for display panel panel = libtcod.console_new(SCREEN_WIDTH, PANEL_HEIGHT) # Only for real time, Frames per second libtcod.sys_set_fps(LIMIT_FPS) fov_map = libtcod.map_new(MAP_WIDTH, MAP_HEIGHT) global compute_fov compute_fov = False cells = [[Cell() for y in range(MAP_COLS)] for x in range(MAP_ROWS)] make_map(cells) msgs = [] choice = 0 global move_count move_count = 0 while True: msgs.append(("Which algorithm would you like to generate the maze?", libtcod.white)) msgs.append(("[1]. Kruskal's algorithm", libtcod.white)) msgs.append(("[2]. Prim's algorithm", libtcod.white)) msgs.append(("[3]. Binary tree method", libtcod.white)) msgs.append(("[4]. Random method", libtcod.white)) render_all(player, con, panel, fov_map, True, msgs) libtcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0) libtcod.console_flush() msgs = [] form_messages = [ ("Maze has been formed by Kruskal's method", libtcod.green), ("Maze has been formed by Prim's method", libtcod.green), ("Maze has been formed by Binary tree method", libtcod.green) ] key = libtcod.console_wait_for_keypress(True) if key.vk == libtcod.KEY_1: choice = 1 if key.vk == libtcod.KEY_2: choice = 2 if key.vk == libtcod.KEY_3: choice = 3 if key.vk == libtcod.KEY_4: choice = random.randint(0, 3) if choice in [1, 2, 3]: print "User's choice for maze generation is " + str(choice) msgs.append(form_messages[choice - 1]) break else: msgs.append(("Sorry that is not an option!", libtcod.red)) msgs.append(("", libtcod.red)) if choice == 1: (edges, cell_set, cell_list, cells) = kruskal.init_variables(MAP_ROWS, MAP_COLS) while cell_set.size() != 1: cells = kruskal.generate_maze(edges, cell_set, cell_list, cells) if choice == 2: (wall_set, cells_finished, cells) = prim.init_variables(MAP_ROWS, MAP_COLS) while len(cells_finished) != MAP_ROWS * MAP_COLS: cells = prim.generate_maze(wall_set, cells_finished, cells, MAP_ROWS, MAP_COLS) if choice == 3: (cells) = bt.init_variables(MAP_ROWS, MAP_COLS) for x in range(MAP_ROWS - 1, -1, -1): for y in range(MAP_COLS): cells = bt.generate_maze(cells, x, y, MAP_ROWS, MAP_COLS) make_map(cells) msgs = in_game_messages(msgs) for y in xrange(MAP_HEIGHT): for x in xrange(MAP_WIDTH): libtcod.map_set_properties(fov_map, x, y, not map[x][y].wall, not map[x][y].wall) render_all(player, con, panel, fov_map, True, msgs) libtcod.console_blit(con, 0, 0, MAP_WIDTH, MAP_HEIGHT, 0, 0, 0) libtcod.console_flush() global fog_of_war fog_of_war = True while not libtcod.console_is_window_closed(): if player.x == MAP_WIDTH - 2 and player.y == MAP_HEIGHT - 2: msgs = [] msgs.append( ("Congratulations! You have won the game", libtcod.purple)) msgs.append(("", libtcod.white)) msgs.append( ("Displaying player's route in green", libtcod.light_green)) msgs.append(("", libtcod.white)) msgs.append(("Press any key to exit game now", libtcod.white)) render_all(player, con, panel, fov_map, False, msgs) render_travelled(con) libtcod.console_put_char_ex(con, 1, 1, 'S', libtcod.pink, libtcod.black) player.draw(con) libtcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0) libtcod.console_flush() key = libtcod.console_wait_for_keypress(True) break render_all(player, con, panel, fov_map, fog_of_war, msgs) libtcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0) libtcod.console_flush() player.erase(con) quit = keyboard_input(player, con) if quit: quit_msgs = [] quit_msgs.append(("Are you sure you want to quit?", libtcod.red)) quit_msgs.append(("", libtcod.red)) quit_msgs.append(("Enter Esc again to display solution and exit", libtcod.white)) quit_msgs.append(("Enter any other key otherwise", libtcod.white)) render_all(player, con, panel, fov_map, True, quit_msgs) libtcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0) libtcod.console_flush() key = libtcod.console_wait_for_keypress(True) if key.vk == libtcod.KEY_ESCAPE: quit_msgs = [] quit_msgs.append(("Displaying solution in blue", libtcod.sky)) quit_msgs.append(("", libtcod.green)) quit_msgs.append(( "Displaying player's route (not overlapping with solution) in green", libtcod.light_green)) quit_msgs.append(("", libtcod.green)) quit_msgs.append( ("Press any key to exit game now", libtcod.white)) render_all(player, con, panel, fov_map, False, quit_msgs) render_travelled(con) render_solution(cells, con) player.draw(con) libtcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0) libtcod.console_flush() key = libtcod.console_wait_for_keypress(True) break