我正在尝试为我的角色移动时创建一个程序。这是我的代码
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if(event.key == K_RIGHT):
playerPos[0] +=1
if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
playerPos[0] =+ 1
这是错误
Traceback (most recent call last):
File "H:\python things\firstgame.py", line 90, in <module>
if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
AttributeError: 'Event' object has no attribute 'key'
答案 0 :(得分:2)
如果有人遇到这个帖子并遇到同样的问题,我修复了我的错误并最终得到了这个。添加评论以帮助其他人理解
while True:
#get all the user events
for event in pygame.event.get():
#if user wants to quit
if event.type == pygame.locals.QUIT:
#and the game close the window
pygame.quit()
sys.exit()
#if a key is pressed
elif event.type == pygame.locals.KEYDOWN:
#if right arrow is pressed
if event.key == K_RIGHT and playerPos[0] < MAPWIDTH - 1:
#change player's x postion
playerPos[0] +=1
if event.key == K_LEFT and playerPos[0] > 0:
#change player x position
playerPos[0] -=1
if event.key == K_UP and playerPos[0] > 0:
#change players x position
playerPos[1] -=1
if event.key == K_DOWN and playerPos[1] < MAPHEIGHT -1:
#change player x position
playerPos[1] += 1
答案 1 :(得分:0)
我认为问题是if (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
在forloop之外,所以事件没有关键属性。
forloop中的事件有一个关键属性,因为pygame.event.get():
移动了forloop中的那一行,这应该可以解决你的问题。
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if(event.key == K_RIGHT):
playerPos[0] +=1
elif (event.key == K_RIGHT) and playerPos[0] < MAPWIDTH -1:
playerPos[0] =+ 1
我还建议你将第87和88行合并为一个这样的
elif(event.type == KEYDOWN) and (event.key == K_RIGHT):
我希望这会有所帮助。
答案 2 :(得分:0)
首先,您必须检查事件的类型。在pygame中,只有KEYDOWN
和KEYUP
事件具有key属性。因此,如果您这样做,它将起作用:
if event.type == event.KEYDOWN:
if event.key == event.K_RIGHT:
playerPos[0] += 1