我正在尝试制作一个基本的roguelike并遵循本教程:https://www.microchip.com/development-tools/downloads-archive 我尝试使用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()函数,但它在启动时崩溃了。
答案 0 :(得分: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