类型错误:'function'对象在将一些已经工作的 pygame 代码包装到函数中时没有属性'__getitem__'



我正在尝试制作代码,以检查用户按下的字母是否是使用pygame列表中任何单词的第一个字母,该列表是由urrlib生成的网页然后我有以下代码检查 pygame.init(( pygame.display.set_mode(((100,100((

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if x[str(event.key)] in [i[0] for i in final]:
                return('Forward')
            else:
                return 'nope', final

但是,当我运行代码时,它只会打印" nope"和一个空列表,我尝试将其包装在功能中并随后调用,但我得到了错误 TypeError:"函数"对象没有属性getItem

注意:最终是单词列表,x是自事件以来每个字母的值。

event.key s只是整数,如果将它们转换为字符串,则只会得到诸如'97''115'之类的字符串。

如果需要实际字母,则应使用event.unicode属性。然后,您可以使用any函数并传递此发电机表达式,any(word.lower().startswith(event.unicode) for word in strings)以查看一个单词是否以输入字母开头。

import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
strings = ['some', 'Random', 'words']
done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            print(event.unicode)
            if any(word.lower().startswith(event.unicode) for word in strings):
                print('Forward')
            else:
                print('nope')
    screen.fill(BG_COLOR)
    pg.display.flip()
    clock.tick(30)
pg.quit()

最新更新