gpt4 book ai didi

python-2.7 - Pygame 键被​​按下

转载 作者:行者123 更新时间:2023-12-01 10:36:08 24 4
gpt4 key购买 nike

告诉 pygame 在按下某个键时运行某些东西的惯用方式是什么?使用 pygame.key.get_pressed()[pygame.K_p]==Truepygame.mouse.get_pressed()==(1,0,0) 似乎仅在键或按钮被击中时使用react。例如,是否应该使用 while 循环?

我运行下面的代码,只有在按下键/按钮时我才会在 shell 中打印:

def main():
done = True
while done:
for i in pygame.event.get():
if pygame.key.get_pressed()[pygame.K_a] == 1:
print "Key a is being pressed..."
elif i.type == KEYDOWN and i.key == pygame.K_q:
done = 0
pygame.display.update()
pygame.quit()
main()

最佳答案

事件 KEYDOWN 表示“按键状态从 UP 变为 DOWN”——它并不表示“按键一直被按下”

enter image description here

当您开始按下按键时 - 它会生成事件 KEYDOWN 并且 pygame.event.get() 返回非空列表 - 以及 for 循环可以执行if pygame.event.get()

当您按住按键时 - 它不会生成事件 KEYDOWN - 并且 pygame.event.get() 返回空列表 - 并且 for 循环不执行 if pygame.event.get()

你的代码应该是这样的

running = True
while running:
# check events
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == pygame.K_q:
running = False

# do it outside of `for event` loop
# it is executed many times
if pygame.key.get_pressed()[pygame.K_a]:
print "Key is hold pressed..."

pygame.display.update()

或者 - 当你只需要执行一次时

key_A_pressed = False

running = True
while running:
# check events
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == pygame.K_q:
running = False

elif event.key == pygame.K_a:
key_A_pressed = True

# it is executed only once
print "Key A - start pressing"

if event.type == KEYUP:
if event.key == pygame.K_a:
key_A_pressed = False

# it is executed only once
print "Key A - stop pressing"

# do it only once - outside of `for event` loop
# it is executed many times
#if pygame.key.get_pressed()[pygame.K_a]:
# or
if key_A_pressed:
print "Key A is held pressed..."

pygame.display.update()

关于python-2.7 - Pygame 键被​​按下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35136091/

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