python - 我无法正确跟踪 PyGame 中的 KEYDOWN 事件

标签 python if-statement pygame

我不知道如何正确跟踪 PyGame 中的按键事件。每当我尝试增加玩家的坐标 plxply 时,它都不起作用,并且会一遍又一遍地打印相同的内容!

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

我也尝试过以其他方式设置变量,但仍然无法使其工作。我以前用过一些像这样的基本匹配,所以我不知道该怎么办。如有任何帮助,我们将不胜感激!

最佳答案

检查输出后:-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_LEFTpygame.K_RIGHT是值,因此它们的计算结果为 True每次。检查按下的键的正确条件应该是 event.key == <KEY> .

关于python - 我无法正确跟踪 PyGame 中的 KEYDOWN 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59335457/

相关文章:

c# - 从变量更改 if 语句

python - 属性错误: 'Alien' object has no attribute 'image' (I am calling for a Group object)

python - 如何为pytest传递参数

python - 在 Python 中将 *args 传递给 string.format?

java - 如果在外部使用则内部变量

python - Pygame 全屏放大

python - 如何在 Pygame 中将图像缩放到屏幕大小

python - 如何使属性比较能够在 SQLAlchemy 中编译为 SQL 表达式?

python - 为什么Python中类属性的赋值行为类似于实例变量的赋值?

linux - 如果参数 = x,则终止脚本