I am having trouble trying to grasp a couple of things inside the py game code, firstly why are there two types of quit or are these the same? for example:
pygame.QUIT
pygame.quit()
Also I can't grasp this small piece code fully:
for event in pygame.event.get():
if event.type == pygame.QUIT:
I understand the first line of code, but I don't understand event.type?, is .type a function inside of pygame or python in general? what does it do?
pygame.QUIT
Is an enumeration for an input that signals for the program to quit
pygame.quit()
Is a function call to unload pygame modules. According to the docs it won't actually quit the game:
http://www.pygame.org/docs/ref/pygame.html#pygame.quit
You could use sys.exit(0) for that.
This loop here:
for event in pygame.event.get():
if event.type == pygame.QUIT:
Checks each event, if one of them has the value pygame.QUIT then some exit code should follow.
pygame.QUIT is simply a constant, while pygame.quit() is a function within the pygame module that uninitializes it. The fragment of code:
for event in pygame.event.get():
if event.type == pygame.QUIT:
...
is part of the typical control loop of a pygame program. The method pygame.event.get() returns the next event. If the type of event (an attribute of the event object) is pygame.QUIT then the application should do what is necessary to exit, including possibly calling pygame.quit().
The manual for pygame.quit() says:
Uninitialize all pygame modules that have previously been initialized. When the Python interpreter shuts down, this method is called regardless, so your program should not need it, except when it wants to terminate its pygame resources and continue.
So you should normally call this method yourself.
pygame.QUIT is a so called event type. Pygame uses events to tell you something happened. The code checks each events in the queue and checks if a QUIT event happened.
event.type is something from pygame, and it tells you what type of event it is. By comparing it to pygame.QUIT, you can check if the quit() method has been called, and take steps to shutdown the game.
Related
The following works:
while True:
for event in pygame.event.get():
match (event.type):
case pygame.QUIT:
pygame.quit()
but if I write without "pygame." in the case expression
while True:
for event in pygame.event.get():
match (event.type):
case QUIT:
pygame.quit()
the case catches all the events and not only the QUIT one. Other potential cases are also marked unreachable by python.
Why is that? print(pygame.QUIT) and print(QUIT) both display "256".
You cant use the QUIT keyword if you only had imported pygame, to use only QUIT you need to also import pygame locals:
import pygame # Default
from pygame.locals import * # Optional
Then you can use either pygame.QUIT or QUIT.
Also instead of matching these events you can use:
for event in pygame.event.get(): # Handle events
if event.type == pygame.QUIT: # Check if the X button is clicked
pygame.quit() # Quit pygame
Then you just only need to import pygame
This question already has an answer here:
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Closed 2 years ago.
I'm working on a game where pressing space does something, but a lot of the time, the space key is not registered. I have a main function and I run a while loop where at the end, I have this:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
(do this)
if event.type == pygame.QUIT:
pygame.quit()
quit()
break
else:
pass
(Before this, I have a few hundred lines of code)
But I find that a lot of the time, nothing happens when I press space and it takes a lot of tries (usually 7-10) before the game responds to the spacebar. I have tried removing time.sleep(0.05) after pygame.display.update which has helped a bit. I have also tried making this for loop run more often through my while loop, but it still takes many tries before the game responds to the keypress. What am I doing wrong?
[...] I have also tried making this for loop run more often through my while loop [...]
No, don't do that. pygame.event.get() removes all the pending events from the queue. If you have more than one event loop and you invoke pygame.event.get() multiple times, only one of the loops will receive the events, all other loops will miss them.
Retrieve the list of events once per frame. You can then go through the list several times:
# application loop
while run:
# get the events
events = pygame.event.get()
# handel QUIT event
for event in events:
if evnet.type == pygame.QUIT:
run = false
# [...]
# handle some events
for event in events:
# [...]
# [...]
# handle some other events
for event in events:
# [...]
# [...]
I have just downloaded pygame 1.9.2 for python 3.3 and the keydown function is not working. The IDLE shell keeps telling me the same error:
NameError: name 'KEYDOWN' is not defined
How do I solve this problem? I am kinda new to programming so could you please explain this to me.
NOTE: Sorry for deleting my previous answer but Stack Overflow just randomly posted my answer before I was done.
Well, there could be several things wrong. You could be using pygame.key.keydown(), which is wrong, and you should be using pygame.key.get_pressed().
But what I suspect is wrong with your code is that you're not using pygame.KEYDOWN properly.
If you're trying to do something while a key is being held down, use pygame.key.get_pressed(), and do something like this:
key = pygame.key.get_pressed()
if key[pygame.K_WHATEVER_KEY_YOU_WANT]:
# do code
and just repeat that for every key you want to check.
If you're just trying to check if a key is being pressed, use pygame.KEYDOWN with an if statement, then check if the key you want is being pressed in a nested if statement under the first if statement. Like so:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_WHATEVER_KEY_YOU_WANT:
#do code
I'm assuming you have an event variable your using to iterate over pygame.event.get() function that 'gets' events. If not then here is the code above in a game/window loop:
running = True # variable to control while loop
while running: # while the variable running is equal to true
for event in pygame.event.get(): # use the variable 'event' to iterate over user events
if event.type == pygame.QUIT: # test if the user is trying to close the window
running = False # break the loop if the user is trying to close the window
pygame.quit() # de-initialize pygame module
quit() # quit() the IDE shell
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_WHATEVER_KEY_YOU_WANT:
#do code
This is basically how you use pygame.KEYDOWN. It's probably not the only way however. I recommend (since you're new to programming) to read the pygame docs on their official website for more info about checking key input in pygame. And read some of the answers to this question.
Im running a Pygame window using a GUI. When for example, a user clicks on a button on the GUI, the Pygame window appears. However, when I want to quit the Pygame window, my GUI quits too. Im sure this is beacuse of the following lines of code:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
sys.exit() exits everything, which is why the IDE closes with the Pygame window. But how do I only close the Pygae Window? Ive tried this:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
break
But this doesnt work. Any suggestions?
The GUI im using Pyqt4 with Python 3.
I guess that your code snippet
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
break
is part of your main loop, running in an while loop, like
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
break
The problem is that break will exit the for loop, not the while loop, eventually leading to an exception since you exit pygame but are probably trying to draw an the screen etc. etc.
A simple fix is to use a variable as condition for your while loop, like
quit = False
while not quit:
for event in pygame.event.get():
if event.type==pygame.QUIT:
quit = True
...
or make sure to exit the while loop
while True:
if pygame.event.get(pygame.QUIT): # only check for QUIT event
break
for event in pygame.event.get():
...
I am learning to use Pygame, and when I use sys.exit(), I run into a problem. Here is the code:
import pygame, sys,os
from pygame.locals import *
pygame.init()
window = pygame.display.set_mode((468, 60))
pygame.display.set_caption('Game')
screen = pygame.display.get_surface()
file_name = os.path.join("data","image.bmp")
surface = pygame.image.load(file_name)
screen.blit(surface, (0,0))
pygame.display.flip()
def input(events):
for event in events:
if event.type == QUIT:
sys.exit(0)
else:
print event
while True:
input(pygame.event.get())
It's really just the code from the pygame tutorial. The problem occurs when I actually try to exit, regardless of what event I try to use to sys.exit().
Traceback (most recent call last):
File "C:/Python27/Lib/site-packages/pygame/examples/test.py", line 25, in <module>
input(pygame.event.get())
File "C:/Python27/Lib/site-packages/pygame/examples/test.py", line 20, in input
sys.exit(0)
SystemExit: 0
... And then the program doesn't exit. What am I doing wrong here? Because I did notice that this code was for an antiquated version of Python.
sys.exit()
alone is a bit unholy with pygame.. the proper way to exit a pygame app is to first break out of the mainloop then quit pygame then quit the program. ie.
while running == True:
# catch events
if event_type == quit:
running = False # breaks out of the loop
pygame.quit() # quits pygame
sys.exit()
also it seems to me that you aren't catching the event properly.. it should be
if event.type == pygame.QUIT:
you can read more about events in pygame here.
sys.exit just throws an exception (a SystemExit exception). This has two unusual effects:
It only exits the current thread in a multithreaded application
The exception could have been caught.
I solved this problem and the right code is below:
running = True
while running == True:
for event in pygame.event.get():
if event.type == QUIT:
running = False # Exiting the while loop
screen.blit(background, (0,0))
pygame.display.update()
pygame.quit() # Call the quit() method outside the while loop to end the application.
I have read in some sources there is a conflict between the mainloop() in Tkinter which runs the Python shell and Pygame.init() which the sys.exit() command follows.
The suggestion was to run the game from the command line to get round the problem rather than load the game using run (F5) from the shell.
A good side effect of this was that in my space invaders game, which does a lot of variable updating: 35 times a second, was that the animation ran correctly whereas from the shell it ran poorly and was jerky.
If i use the following code:
if event.type == QUIT:
pygame.quit()
sys.exit()
the game exits correctly but leaves an error message in the shell which has no effect on the game and is largely redundant. It is just a little ugly. This does not happen from the command line.
Summary: try running the game from the command line to avoid Tkinter problems
If you still have the issue, (after breaking the loop) try using sys.exit(0) instead of sys.exit(). Hope it'll help. It worked for me. It seems pygame expects the 'status' argument (i.e. 0 here) to be passed in explicitly.
See the below example:
isRunning = True
while isRunning:
# Catch events
if event.type == pygame.QUIT:
isRunning = False # Breaks the loop
pygame.quit()
sys.exit(0)