[Tutor] Event loop logic question
avi.e.gross at gmail.com
avi.e.gross at gmail.com
Sat Jun 18 01:22:57 EDT 2022
Phil,
I am not familiar with the package you are using and have to assume you have some code somewhere not shown that binds your functions to the task as event handlers.
But can multiple functions be called and active at the same time. I do not see any kind of lock in place such as a semaphore that stops two or more changes to the global variables as might happen if an arrow key is held down or whatever.
And your on_key_up() function does not make stop_flag global and so any changes it makes are to a local variable that immediately disappears.
It is not my place to mention that this may be an advanced question and someone may want to direct you to resources showing the care that must be taken when a global variable is being handled by multiple threads. Ditto for forward_flag in on_key_down()
-----Original Message-----
From: Tutor <tutor-bounces+avi.e.gross=gmail.com at python.org> On Behalf Of Phil
Sent: Saturday, June 18, 2022 1:05 AM
To: tutor at python.org
Subject: [Tutor] Event loop logic question
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
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list