PyGame 零中的重复键检测

Repeated key detection in PyGame Zero

我的 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_pressed,它在按下键时(在 on_key_down() 中)声明,并在释放键时重置(在 on_key_up() 中)。根据变量 space_pressed 的状态增加 update() 中的计数器:

import pgzrun

counter = 1
space_pressed = False

def on_key_down(key):
    global space_pressed
    if key == keys.SPACE:
        print("Space key pressed...")
        space_pressed = True

def on_key_up(key):
    global space_pressed
    if key == keys.SPACE:
        print("Space key released...")
        space_pressed = False

def update():
    global counter
    if space_pressed:
        counter = counter + 1

def draw():
    screen.clear()
    screen.draw.text("Space key pressed counter: " + str(counter), (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()