gpt4 book ai didi

python - 如何让Pygame以不同的速度不断响应不同的按键?

转载 作者:太空宇宙 更新时间:2023-11-03 20:27:15 24 4
gpt4 key购买 nike

我正在制作一个射击游戏,其中包含一个可以射击“子弹”的“玩家”。按“WASD”可以控制玩家的移动,按“Space”可以让“玩家”射击。现在我希望Pygame能够以不同的速度响应长按的按键。例如,每 10 毫秒响应一次“WASD”,每 1000 毫秒响应一次“空格”。我该怎么办?

我尝试过 pygame.key.set_repeat() ,每个键都会以相同的速度响应。

最佳答案

pygame.key.set_repeat() 设置整个键盘的延迟,它无法区分按键。您需要在您的程序中执行此操作。

一个可能的解决方案是使用 set_repeat 将重复事件之间的延迟设置为您希望在游戏中拥有的最短间隔。对于需要较长间隔的按键,您需要自行检查是否有足够的时间来“接受”事件并允许执行相应的操作。

这个示例代码应该能让您了解我的意思。

import sys
import pygame

#the action you want to perform when the key is pressed. Here simply print the event key
#in a real game situation, this action would differ according to the key value
def onkeypress(event):
print(event.key)

#dict of key constants for which you want a longer delay and their tracking time
#in ms, initialized to 0. Here only the spacebar
repeat1000 = {pygame.K_SPACE : 0}

pygame.init()
screen = pygame.display.set_mode((500, 500))

#sets repeat interval to 10 milliseconds for all keys
pygame.key.set_repeat(10)

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
current_time = pygame.time.get_ticks()
if event.key in repeat1000.keys():
if current_time - repeat1000[event.key] > 1000:
repeat1000[event.key] = current_time
onkeypress(event)
elif event.key in [pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d]:
onkeypress(event)

如果您尝试上面的代码,您将看到如果您按住空格键,每秒都会打印空格键(在我的系统上为 32)。如果您按 W A S D 之一,则每 0.01 秒打印一次相应的键(在我的系统上为 119、97、115、100)。

关于python - 如何让Pygame以不同的速度不断响应不同的按键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57737870/

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