我不知道如何正确跟踪PyGame中的按键事件。每当我尝试增加玩家的坐标plx
或ply
时,它都将无效,并且会一遍又一遍地打印出相同的内容!
import pygame, sys
from pygame.locals import *
global plx
global ply
plx = 0
ply = 0
DISPLAYSURF = pygame.display.set_mode((1, 1))
pygame.display.set_caption('Text Only Jam')
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if pygame.K_LEFT:
plx -= 1
print(plx)
if pygame.K_RIGHT:
plx += 1
print(plx)
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
这是输出:
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
-1
0
-1
0
-1
0
我也尝试过以其他方式设置变量,但仍然无法正常工作。之前我曾经使用过一些基本的比赛,所以我不知道该怎么办。任何帮助表示赞赏!
答案 0 :(得分:4)
检查输出后:-1,然后是0,-1,然后是0;似乎先执行plx -= 1
,然后立即执行plx += 1
。这意味着,这两个语句每次都会执行,表明条件不正确。也就是说,用此代码替换部分代码:
if event.key == pygame.K_LEFT:
plx -= 1
print(plx)
if event.key == pygame.K_RIGHT:
plx += 1
print(plx)
为什么? pygame.K_LEFT
和pygame.K_RIGHT
是值,因此它们每次都求值为True
。检查按键的正确条件应该为event.key == <KEY>
。