Python PyGame Zero中的重复密钥检测

Python PyGame Zero中的重复密钥检测,python,pgzero,Python,Pgzero,我的pgzero按键事件处理程序只识别一次按键(直到释放),但如果按键一直按下,则不支持重复按键事件 我怎样才能做到这一点 PS:由于pgzero是使用pygame实现的,也许pygame解决方案可以工作 import pgzrun counter = 1 def on_key_down(key): global counter if key == keys.SPACE: print("Space key pressed...") counte

我的pgzero按键事件处理程序只识别一次按键(直到释放),但如果按键一直按下,则不支持重复按键事件

我怎样才能做到这一点

PS:由于
pgzero
是使用
pygame
实现的,也许
pygame
解决方案可以工作

import pgzrun

counter = 1

def on_key_down(key):
    global counter
    if key == keys.SPACE:
        print("Space key pressed...")
        counter = counter + 1

def draw():
    screen.clear()
    screen.draw.text("Space key pressed counter: " + str(counter), (10, 10))

pgzrun.go()

当按键时,该事件仅触发一次。您必须使用状态变量
space\u pressed
,该变量在按键时说明(在
on\u key\u down()
)并在按键释放时重置(在
on\u key\u up()
)。根据按下的变量的状态,在
update()
中递增计数器:

导入pgzrun
计数器=1
空格=假
def on_键按下(键):
全球空间
如果key==keys.SPACE:
打印(“按空格键…”)
空格=真
def接通钥匙(钥匙):
全球空间
如果key==keys.SPACE:
打印(“释放空格键…”)
空格=假
def update():
全局计数器
如果按下空格键:
计数器=计数器+1
def draw():
screen.clear()
screen.draw.text(“空格键按下计数器:+str(计数器),(10,10))
pgzrun.go()

受@furas评论的启发,我[发现->]实施了一个不需要使用全局变量来管理密钥状态的进一步解决方案:

import pgzrun

counter = 1

# game tick rate is 60 times per second
def update():
    global counter    
    if keyboard[keys.SPACE]:  # query the current "key pressed" state
        counter = counter + 1

def draw():
    screen.clear()
    screen.draw.text("Space key pressed counter: " + str(counter), (10, 10))

pgzrun.go()

若你们一直按,那个么它就不能被重复——系统并没有这个事件。您只能在
上下键
中设置一些值为True,在
上上键
中设置一些值为False,然后使用计时器检查此值是否仍然为True,并将其重复计数。您也可以使用
键盘[keys.SPACE]
来实现此目的。@furas谢谢,这确实更直观(无需额外的按键变量)完美!我甚至可以通过使用自己的基于计时器的游戏计时功能来控制重复率(
update
被称为每秒60次AFAIK,这对我来说太快了)