gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:59:55 24 4
gpt4 key购买 nike

我不知道如何正确跟踪 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com