is there a "force quit" option for pygame programs? [duplicate] - pygame

This question already has answers here:
What is the difference between .quit and .QUIT in pygame
(2 answers)
Closed 1 year ago.
I have defined a "game loop"
function, (the code below)
but for some reason it doesn't
exit upon trying close the window
(the "quit event")
despite there being code written to break the loop if
you do that.
I have tried handling the event in question
by using a variable to dictate when the loop
should run, as well as handling using a break statement
to close the loop. neither have worked.
##game loop
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == quit:
run = False
draw_all()
if __name__ == "__main__":
main()

Here you compare the event type to the predefined quit function of python. This is obviously never evaluted to True.
Do instead if event.type == pygame.QUIT:.

Related

how to use the recognized text with Google Assistant's hotword.py code

How do I get the spoken text from the hotword.py code & do my own actions on the recognised text rather than Google going off and reacting to the text?
I've installed GA on the Pi3 & after some initial issues with usb mic/analogue audio settings and certain Python files missing this got me going:
When installing Google Assistant, I an error "...googlesamples.assistant' is a package and cannot be directly executed..."
I then followed the Google Next steps : https://developers.google.com/assistant/sdk/prototype/getting-started-pi-python/run-sample and created a new project "myga/" with a hotword.py file that contains:
def process_event(event):
"""Pretty prints events.
Prints all events that occur with two spaces between each new
conversation and a single space between turns of a conversation.
Args:
event(event.Event): The current event to process.
"""
if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
print()
#GPIO.output(25,True) see https://stackoverflow.com/questions/44219740/how-can-i-get-an-led-to-light-on-google-assistant-listening
if event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
print("got some work to do here with the phrase or text spoken!")
print(event)
if (event.type == EventType.ON_CONVERSATION_TURN_FINISHED and
event.args and not event.args['with_follow_on_turn']):
print()
#GPIO.output(25,False) or also see https://blog.arevindh.com/2017/05/20/voice-activated-google-assistant-on-raspberry-pi-with-visual-feedback/
I'd like code to react to the ON_RECOGNIZING_SPEECH_FINISHED event I think and at either do my own action by matching simple requests or if the phrase is not in my list then let Google handle it. How do I do that?
Eventually I'd be asking "OK Google, turn BBC1 on" or "OK Google, play my playlist" or "OK Google, show traffic" and hotword.py would run other applications to do those tasks.
Thanks, Steve
See the documentation here for all available methods -
https://developers.google.com/assistant/sdk/reference/library/python/
You can use the stop_conversation() method to stop Google Assistant handling that request and act on your own.
Here's what you need to do at a high level -
Build your own dictionary of commands that you'd like to handle -
"turn BBC1 on", "play my playlist" etc.
On EventType.ON_RECOGNIZING_SPEECH_FINISHED event check if the
recognized command exists in your dictionary.
If the recognized command exists in your dictionary call the assistant.stop_conversation() method and handle the command on your own. If not do nothing (let google handle it)
pseudo code -
local_commands = ['turnBBCOn', 'playLocalPlaylist']
function turnBBCOn() :
#handle locally
function playLocalPlaylist() :
#handle locally
def process_event(event):
if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
print()
if event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
print(event.args['text'])
if event.args['text'] in local_commands:
assistant.stop_conversation()
if(event.args['text']='turn BBC1 on')
turnBBCOn()
elif(event.args['text']='play my playlist')
playLocalPlaylist()
if (event.type == EventType.ON_CONVERSATION_TURN_FINISHED and
event.args and not event.args['with_follow_on_turn']):
print()
I have recently integrated google assistant SDK with Raspberry Pi 3. I have taken reference from below git repository and created action.py and actionbase.py classes can handle my custom command. I found it very clean and flexible way to create your own custom commands.
You can register your custom command in action.py file like below
actor = actionbase.Actor()
actor.add_keyword(
_('ip address'), SpeakShellCommandOutput(
say, "ip -4 route get 1 | head -1 | cut -d' ' -f8",
_('I do not have an ip address assigned to me.')))
return actor
action.py
Write your custom code in action.py
"""Speaks out the output of a shell command."""
def __init__(self, say, shell_command, failure_text):
self.say = say
self.shell_command = shell_command
self.failure_text = failure_text
def run(self, voice_command):
output = subprocess.check_output(self.shell_command, shell=True).strip()
if output:
self.say(output.decode('utf-8'))
elif self.failure_text:
self.say(self.failure_text)
You can full source code here. https://github.com/aycgit/google-assistant-hotword
The text is contained within the event arguments. By calling event.args you can make use of the text. Here is an example.
https://github.com/shivasiddharth/GassistPi/blob/master/src/main.py

pygame gives an error when calling update

I am trying to run some tutorial code on pygame. But when pygame.update I get error: , and nothing else just error: and then python exits.
import pygame
pygame.init()
gameDisplay=pygame.display.set_caption('test')
clock=pygame.time.Clock()
crashed= False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
print(event)
pygame.display.update()
clock.tick(60)
You have not created a window/screen yet, so there's nothing to update.
Put this before your loop and after init:
screen = pygame.display.set_mode((640, 480)) # or whatnot
Also you have some indention errors, but given that this is running I'm assuming that's a typo while indenting the code into the post.
Also, for future reference, it helps people answer faster if you include the actual error message including stack trace.

Pygame Key Listener for Python 3

I want to be able to control some motors that are hooked up to my raspberry pi through keyboard presses. I have code that turns the motors one direction for 5 seconds and then the other direction for 5 seconds before turning them off. I want to use the key listener function of pygame to control the motors through keyboard presses. I am using the following as a test on the keyboard press aspect.
import pygame
pygame.init()
pygame.key.set_repeat(100, 100)
while 1:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
print 'go forward'
if event.key == pygame.K_s:
print 'go backward'
if event.type == pygame.KEYUP:
print 'stop'
When I run this script, I do not get any errors, so I know it runs. However, when I press either the 'w' or 's' key, what displays is either a 'w' or an 's' as if I was just typing. All I want is to be able to execute a function by pressing a key. If there is a different/better way to do it that would be fine.
Pygame KEYDOWN events are looking for key presses in the active window.
You must create a window to tell Pygame where to read events from.
Another solution would be to hook keyboard events from the terminal so you wouldn't have to have a window initialized or in focus, using something like this: Python Key Binding or using the pyHook library to make global keyboard event hooks.
P.S - I realise you solved the problem yourself, I'm including this for completeness.

How to use letter/number combinations in pygame, event.key?

I know that in pygame, for the command:
if event.key==K_r:
That when you press the letter r on the keyboard you get a response. But I would like to increase the complexity to a letter/number combination for a jukebox. So I tried:
if event.key==K_r3:
And I pressed r then I pressed 3. But I get an error: name 'K_r3' is not defined. I'm hoping I don't have to write out a definition for each possible letter/number combination. Any suggestions?
`Don't fret Rico, there is an answer. Try the following:
if event.type == KEYDOWN:
#this says that a key was pressed down
keys = pygame.key.get_pressed()
#this is a list of all the keys that were pressed down. now, if you want to do do multiple keys, the answer is as follows:
if keys[K_3] and keys[K_r]:
(function)
I hope this helps you on your quest to pygame greatness.

Custom Events in pygame

I'm having trouble getting my custom events to fire. My regular events work fine, but I guess I'm doing something wrong. Here is the relevant code:
evt = pygame.event.Event(gui.INFOEVENT, {'time':time,'freq':freq,'db':db})
print "POSTING", evt
pygame.event.post(evt)
.... Later ....
for event in pygame.event.get():
print "GOT", event
if event.type == pygame.QUIT:
sys.exit()
dispatcher.dispatch(event)
gui.INFOEVENT = 101 by the way. The POSTING print statement fires, but the GOT one never shows my event.
Thanks!
From http://www.pygame.org/docs/ref/event.html
All events have a type identifier. This event type is in between the values of NOEVENT and NUMEVENTS. All user defined events can have the value of USEREVENT or higher. It is recommended make sure your event id's follow this system.
My thought is that your event ID is to high.
It seems to work when I changed the code from:
INFOEVENT = 101
to:
INFOEVENT = pygame.USEREVENT+x
where x is some positive integer.