3

My pgzero key press event handler does recognize a pressed key only once (until released) but does not support repeated key press events if the key is kept pressed.

How can I achieve this?

PS: Since pgzero is implemented using pygame perhaps a pygame solution could work...

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()
R Yoda
  • 8,358
  • 2
  • 50
  • 87
  • 1
    if you keep pressed then it can't be repeated - system doesn't have event for this. You can only set some value on True in `on_key_down` and set on False in `on_key_up` and use timer to check if this value is still True and count it as repeated. – furas Aug 20 '19 at 21:36
  • 1
    you can also use `keyboard[keys.SPACE]` for this. – furas Aug 20 '19 at 21:50
  • @furas Thanks, this does work even more intuitively (without an additional key press variable) – R Yoda Aug 20 '19 at 21:55

3 Answers3

2

The event is only triggered once, when the key is pressed. You've to use state variable space_pressed which is stated when the key is pressed (in on_key_down()) and reset when the key is released (in on_key_up()). Increment the counter in update(), dependent on the state of the variable space_pressed:

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()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 2
    Perfect! I can even control the repeat rate by using my own timer-based game tick function (`update` is called 60 times per second AFAIK which is too fast for me) – R Yoda Aug 20 '19 at 21:43
1

Inspired by @furas 's comment I have [found->] implemented a further solution that does not require to use a global variable to manage the key state:

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()
R Yoda
  • 8,358
  • 2
  • 50
  • 87
1

I don't know if you need this anymore since it's two years ago, but there is a simple solution. so in the update function, just add this

if keyboard.a: #or whatever key you want
        do something
Kevin
  • 13
  • 5