[Tutor] Event loop logic question
Phil
phillor9 at gmail.com
Sat Jun 18 01:04:50 EDT 2022
Thank you for reading this.
What I'm trying to achieve here is have the word 'stop' printed once
whenever no keys are pressed and 'forward' printed once even when the up
arrow key is held down.
I don't think this question needs any knowledge of Pygame Zero to solve
and it's quite likely that I've misunderstood the logic required. The
following code is my most recent version which seems to work the first
time through the loop but fails after subsequent 'up' key presses.
Debugging the event loop is difficult.
Any hints or alternative methods will be, as always, greatly appreciated.
By the way, this project sends commands to a controller which is easily
overwhelmed if too many commands are received per second.
import pgzrun
WIDTH = 20
HEIGHT = 20
direction = 'stop'
stop_flag = True
forward_flag = True
def on_key_down(key):
global direction
if key == keys.UP:
print('up pressed')
direction = 'forward'
forward_flag = True
print('forward_flag ', forward_flag)
elif key == keys.SPACE:
direction = 'quit'
def on_key_up(key):
global direction
#print('stop')
direction = 'stop'
stop_flag = True
def update():
global direction, stop_flag, forward_flag
if direction == 'stop' and stop_flag:
print('stop')
stop_flag = False
elif direction == 'forward' and forward_flag:
print('forward')
forward_flag = False
stop_flag = True
elif direction == 'quit':
quit()
pgzrun.go()
--
Regards,
Phil
More information about the Tutor
mailing list