简体   繁体   中英

Libtcod python 3 crashing when trying to move character?

I'm trying to make a basic roguelike and following this tutorial: http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python3%2Blibtcod,_part_1 I tried to make a character respond to mouse movements using libtcod. I followed the tutorial and all was going well, my character appeared on the screen, but for some reason the program crashes when I try to execute a movement command. For reference, my code is here:

import libtcodpy as tcod

SCREEN_WIDTH = 80
SCREEN_HEIGHT = 50
LIMIT_FPS = 20

font_path = 'arial10x10.png'  # this will look in the same folder as this script
font_flags = tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD  # the layout may need to change with a different font file
tcod.console_set_custom_font(font_path, font_flags)

window_title = 'Python 3 libtcod tutorial'
fullscreen = False
tcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, window_title, fullscreen)


playerx = SCREEN_WIDTH // 2
playery = SCREEN_HEIGHT // 2


def handle_keys():

    # movement keys
 key = tcod.console_check_for_keypress()
if tcod.console_is_key_pressed(tcod.KEY_UP):
    playery = playery - 1

elif tcod.console_is_key_pressed(tcod.KEY_DOWN):
    playery = playery + 1

elif tcod.console_is_key_pressed(tcod.KEY_LEFT):
    playerx = playerx - 1

elif tcod.console_is_key_pressed(tcod.KEY_RIGHT):
    playerx = playerx + 1

while not tcod.console_is_window_closed():

   tcod.console_set_default_foreground(0, tcod.white)
   tcod.console_put_char(0, playerx, playery, '@', tcod.BKGND_NONE)

   tcod.console_flush()

   exit = handle_keys()
   if exit:
        break    

I posted the question to another forum and they said I should define playerx and playery as global, so I added that to the handle_keys() function but then it just crashes on startup.

Here is the fix, in the handle_keys function:

You were missing a global assignment as well, and using an incorrect check for key values

def handle_keys():
    global playerx, playery

    # movement keys
    key = tcod.console_check_for_keypress()

    if key.vk == tcod.KEY_UP:
        playery = playery - 1

    elif key.vk == tcod.KEY_DOWN:
        playery = playery + 1

    elif key.vk == tcod.KEY_LEFT:
        playerx = playerx - 1

    elif key.vk == tcod.KEY_RIGHT:
        playerx = playerx + 1

By the way, there is now an updated python3 tutorial here: http://rogueliketutorials.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM