我正在尝试制作一个基本的流氓风格,并遵循本教程: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()函数中,但它在启动时就崩溃了。
发布于 2019-10-03 04:07:47
下面是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
https://stackoverflow.com/questions/47851518
复制相似问题