1

我正在尝试制作一个基本的 roguelike 并遵循本教程:http : //www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python3%2Blibtcod,_part_1 我尝试使用 libtcod 使角色响应鼠标移动。我按照教程进行,一切顺利,我的角色出现在屏幕上,但由于某种原因,当我尝试执行移动命令时程序崩溃了。作为参考,我的代码在这里:

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    

我将问题发布到另一个论坛,他们说我应该将 playerx 和 playery 定义为全局,所以我将其添加到 handle_keys() 函数中,但它只是在启动时崩溃。

4

1 回答 1

0

这是handle_keys函数中的修复:

你也错过了一个全局分配,并且对键值使用了不正确的检查

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

顺便说一句,这里现在有一个更新的 python3 教程:http ://rogueliketutorials.com

于 2019-10-02T20:07:46.553 回答