Pygame mainloop qiuting exception handling - python

Hi I am writing a simple chess program, unfortunately I have run in some unexpected problems, namely. After I added a list which keeps track of all the figures positions, I cannot close the window using the method which I till now used. which was:
for event in pygame.event.get():
# print(event)
# Checking if the user clicks the red quit cross
if event.type == pygame.QUIT:
# run control the mainloop, wheather True or not
run = False
After adding the list, this stopped working, so I use now:
for event in pygame.event.get():
# print(event)
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
I tried to add some exception handling:
try:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
except pygame.error():
print('Program closed')
However the except statement is not reached and an error is printed: (pygame.error: video system not initialized)
Can You please tell me how to handle this exception properly, or suggest a different way of braking the mainloop.

remove the () from the exception catching, namely:
except pygame.error instead of except pygame.error()

I acctually figured it out on my own, so just in case someone is looking for the anwser. The issue was that I was trying to call the redraw function after pygame.display.quit(). Thus after moving both the redraw call and the keys = pygame.key.get_pressed() [wich also utilises the module pygame] the program terminates without any error call. The code should look as follows:
while run:
pygame.time.delay(100)
window_redrawing()
# Gathering user keyboard input
keys = pygame.key.get_pressed()
# making sure the window can be closed
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
run = False
fig_pos.clear()

Related

PYGame - How to stop and close window by pressing a Key?

I have created a script using PYGAME to animate a pendulum motion simulation. I want to press a "q" key to stop the simulation and close the window. I tryed many different codes but all return some error. The lest version of the event part of the code was:
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == KEYDOWN:
if event.key == K_t:
is_tracing = not(is_tracing)
if event.key == K_c:
trace.fill(WHITE)
if event.key == K_q:
done = True
break
The "c" and "t" events are running fina and the "q" idead stops the simulation, but the simulation window frezes and I need to reestart the kernel do make it run again. Any idea of how to make it close the window without Killing the kernel?
I am runing the code at Jupter Notebook 6.1.4 from Anaconda Navigator 1.10 and Python 3.8.5
Any idea of how to make it close the window without Killing the kernel?
Try using pygame.quit(). From pygame FAQ
Make sure, you invoke pygame.quit() on exiting your application or game.
# ... running = True
while running:
event = pygame.event.wait ()
if event.type == pygame.QUIT:
running = False # Be IDLE friendly
pygame.quit ()

Pygame clock and event loops

i am new to pygame and i was wondering what an event loop is and what clock does in this situation, like what is clock.tick(60)? I don't understand any explanations online
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time.
That meas that the loop:
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
runs 60 times per second.
for event in pygame.event.get() handles the internal events an retrieves a list of external events (the events are removed from the internal event queue).
If you press the close button of the window, than the causes the QUIT event and you'll get the event by for event in pygame.event.get(). See pygame.event for the different event types. e.g. KEYDOWN occurs once when a key is pressed.
e.g. The following loop prints the names of the a key once it it pressed:
run = True
while run:
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
print(pygame.key.name(event.key))

How to close the pygame window without using quit()/sys.exit() so that I don't quit the loop outside of the game?

I am creating a chat system and want to insert a game made with Pygame. In the state_machine file of the chat system, I set a state of the client as S_GAMING. When the client type "game" in the S_LOGGEDIN state, the state will be changed into S_GAMING and when the game is over, the user can quit the game either by clicking the "x" button or by waiting for 3 seconds.
I have some trouble closing the game window without exiting the chat system.
when I used pygame.quit(), the window will froze.
When I tried pygame.quit() and sys.exit() or quit(), I exited the chat system as well.
This is a part of the game.py file:
run = True
gameOver = False
timer = 0
while run:
clock.tick(27)
#check events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if not gameOver:
drawWindow()
for each in barriers:
if each.isHit:
gameOver = True
else:
if timer < 81:
win.blit(game_over,(0,0))
timer +=1
pygame.display.update()
else:
run = False
pygame.display.quit()
pygame.quit()
This is a part of the chat_state_machine file:
elif self.state == S_GAMING:
import game
self.state = S_LOGGEDIN
I know this is a specific question and I can provide more code if the above is not clear.
Hopefully, I can get an answer. I am all ears.
Here is a simple solution: Once you exit pygame the code should throw an exception, in that case you can switch run to False and start a new loop
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
clock = pygame.time.Clock()
run = True
while run:
try:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
clock.tick(120)
pygame.display.update()
except:
run = False
while not run:
#Your other code here
pass

why wont pygame quit?

The game freezes instead of quitting. I have to exit from Idle. Any ideas on what to do?
def quit_game():
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
quit_game()
This is an IDLE bug. I would recommend using a real IDE such as pycharm. However to fix this issue, have a look at the pygame FAQ. They offer this solution:
# ... running = True
while running:
event = pygame.event.wait ()
if event.type == pygame.QUIT:
running = False # Be IDLE friendly
pygame.quit ()
It may work....
def quit_game():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
quit_game()

pygame freezes when I try to exit it after running it from IDLE!

I'm running it through the livewires wrapper which is just training wheels for pygame and other python modules in general; but everytime I run it, it'll execute and when I try to exit, it will not respond and then crash.
Any input on how I could go about fixing this would be great. There isn't any input in my textbook and all google seems to yield are results to this problem using pygame itself.
Apparently pygame and Tkinter seem to conflict?
Thanks in advance!
Addendum - This is the code I was trying to run:
from livewires import games
screen_w = 640
screen_h = 480
my_screen = games.Screen (wid, heit)
my_screen.mainloop()
Similar question: Pygame screen freezes when I close it
There isn't any input in my textbook
and all google seems to yield are
results to this problem using pygame
itself.
Those results probably address the same problem you're having. This is the relevant part of the games.py file from livewires, and nowhere does it call pygame.quit():
def handle_events (self):
"""
If you override this method in a subclass of the Screen
class, you can specify how to handle different kinds of
events. However you must handle the quit condition!
"""
events = pygame.event.get ()
for event in events:
if event.type == QUIT:
self.quit ()
elif event.type == KEYDOWN:
self.keypress (event.key)
elif event.type == MOUSEBUTTONUP:
self.mouse_up (event.pos, event.button-1)
elif event.type == MOUSEBUTTONDOWN:
self.mouse_down (event.pos, event.button-1)
def quit (self):
"""
Calling this method will stop the main loop from running and
make the graphics window disappear.
"""
self._exit = 1
def mainloop (self, fps = 50):
"""
Run the pygame main loop. This will animate the objects on the
screen and call their tick methods every tick.
fps -- target frame rate
"""
self._exit = 0
while not self._exit:
self._wait_frame (fps)
for object in self._objects:
if not object._static:
object._erase ()
object._dirty = 1
# Take a copy of the _objects list as it may get changed in place.
for object in self._objects [:]:
if object._tickable: object._tick ()
self.tick ()
if Screen.got_statics:
for object in self._objects:
if not object._static:
for o in object.overlapping_objects ():
if o._static and not o._dirty:
o._erase ()
o._dirty = 1
for object in self._objects:
if object._dirty:
object._draw ()
object._dirty = 0
self._update_display()
self.handle_events()
# Throw away any pending events.
pygame.event.get()
The QUIT event just sets a flag which drops you out of the while loop in the mainloop function. I'm guessing that if you find this file in your Python directory and stick a pygame.quit() after the last line in mainloop, it will solve your problem.
I agree. you need to put the whole program (the part to be executed, not the definitions and such) into a while loop.The problem is that pygame is not told to close when exited in IDLE, but outside of IDLE the closure of the program overrides the need to close pygame.
here is the loop:
done = False
while done==False:
# ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
#Main program here
pygame.quit()

Categories

Resources