Why doesn't the sys module run in Alien Invasion? [duplicate] - python

I just spent a fair amount of time finding a 64-bit installation of pygame to use with python 3.3, (here) and now am trying to make a window. However, although the window opens up fine it does not close when it hit the x button. In fact, I have to close IDLE to close the window. I am running a 64 bit version of Win 7. Here is my code:
import pygame
import time
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.flip()
pygame.display.set_caption("Hello World")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
When I append
time.sleep(5)
pygame.quit()
It still doesn't close. My only guess would be that pygame.quit might go inside one of the loops, but even if that were resolved I would greatly prefer being able to close the window when I want to.

Most pygame tutorials seem to suggest exiting by calling pygame.quit() and then sys.exit(). I have personally run into problems (was on a unix system though) where this still did not close the window properly. The solution was to add pygame.display.quit() specifically before pygame.quit(). That should not be necessary as far as I can tell, and I'm afraid I don't know why that solved the issue but it did.

if you want to make pygame close when window button x is pressed, put the code like this:
from sys import exit
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
We put exit() after pygame.quit(), because pygame.quit() makes the system exit and exit() closes that window.

Not sure but try this Because you code runs fine on my system after I add pygame.quit() at the end
import pygame
import time
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.flip()
pygame.display.set_caption("Hello World")
running = True
try:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
except SystemExit:
pygame.quit()
Its perhaps because as Idle is made on Tkinter and thus Tkinter and Pygame main loop do not have a mutual understanding.
Your code will run very well on command prompt though.

This was the final code that worked for me on OSX whilst keeping the kernel alive on Jupyter. EDIT - it does still crash the kernel sometimes :-(
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.quit()
pygame.quit()
exit()
Also needed to downgrade ipython to get rid of some magic alias warning messages using:
conda install ipython=7.2.0
apparently that issue is due to be fixed in ipython 7.6.0

Suffered the same issues on Python 3.7.4 while running it from in IDE (Spyder 3.3.6). In my case the pygame.quit() would not completely close the program.
Nonetheless, adding quit() or exit() did the trick for me!

Add this at the top:
import sys
Add this where you need to quit:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

try using the following command:
sys.exit(0)
notice: You will need to import the sys library in order to use it.

The IDE interferes with how pygame runs the code. Try to run it from the commandline or the terminal. The problem should disappear.

To answer the original question: You must call pygame.quit() after breaking the main loop. One elegant solution goes as follows:
def run():
pygame.init()
while True:
# ...
for event in pygame.event.get():
# Handle other events
if event.type == pygame.QUIT:
return pygame.quit()

Related

Pygame window can not be closed on a Mac problem

I have made a python program that uses Pygame. For some reason, I can't close the window when pressing the red cross. I tried using Command+Q but it doesn't work as well. I have to quit idle (my python interpreter) to close the window. Is there any other way to make the window close by pressing the red 'x' at the top right-hand corner?
My code:
import pygame
import sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800,800))
while 1:
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
A pygame window can be closed properly if you use a different python interpreter. Try using pycharm, you can close pygame windows using pycharm.
You should just force quit the window or run another program to close the window. When you run a different program, the window should close.
Try this:
import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800,800))
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

Pygame display not responding

I'm slowly trying to get to know pygame and write my first game in it and honestly, I didn't expect problems so early. So far I've only set a display, that is supposed to be there indefinitely (I just wanted to try it out):
import pygame
pygame.init()
(width, height) = (1000, 700)
screen = pygame.display.set_mode((width, height))
while True:
pygame.display.flip()
But when the window appears it says it's "not responding". I tried deleting the loop so that display would just blink once and vanish, because programm would die immiedately after it's created, but I get the same "not responding" window. I'm using pygame 1.9.2 and python 3.5. I wonder if the trouble may be because of anaconda - the window is opened as subcart for anaconda by default.
Edit: So far I discovered that when I open it not from spyder, but just click on a file it works just fine. Is there any way to make it work by simple run and compile while in spyder or it's just how it's supposed to work?
Add this to your loop. For me the only time it isnt responding is when I click the X and this could be to do with the fact that pygame doesn't know what to do when that happens.
import sys
for evt in pygame.event.get():
if evt.type == pygame.QUIT:
pygame.quit()
sys.exit()
#Try This
import pygame
(width, height) = (1000, 700)
screen=pygame.display.set_mode((width, height))
pygame.display.update()
while True:
for event in pygame.event.get():``
if event.type == pygame.QUIT:
pygame.quit()
quit()

Python video system not intilated

Here it is, I dont know what is wrong, I looked at other answers but I still dont know what is wrong?
import pygame
pygame.init()
gameWindow = pygame.display.set_mode((1000,600));
pygame.display.set_caption("Practice")
#game starts
gameActive = True
while gameActive:
for event in pygame.event.get():
#print event
if event.type == pygame.QUIT:
gameActive = False
pygame.quit()
quit()
You have pygame.quit() in your main loop, so after one iteration through the loop you are calling pygame.quit(), which causes pygame to no longer be initialized which creates the error of not having a display surface.
Moving pygame.quit() out of the main while loop fixes the issue.

Why is this tiny pygame program freezing and doing nothing?

This program infinite loops. Does nothing. Won't take input or print anything. Ideas?
import pygame
pygame.init()
running = 1
while(running):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
print "hi"
running = 0
The problem with your script is solely that there's no window that could capture the events.
You have to create and initialize a window with pygame.display.set_mode first.
import pygame
pygame.init()
# create a window that will capture the events
pygame.display.set_mode((200, 200))
running = 1
while(running):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
print "hi"
running = 0
Try the following:
import pygame, sys
pygame.init()
pygame.mixer.init(22050, -16, 2, 3072)
pygame.mixer.music.load("Kundara_Lake-of-Dust-320.mp3")
pygame.mixer.music.play(1, 0.0)
running = 1
while(running):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.mixer.music.stop()
pygame.quit()
running = 0
From http://www.pygame.org/docs/ref/pygame.html
pygame.quit
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. It is safe to call this function more than once: repeated calls have no effect.
Note, that pygame.quit will not exit your program. Consider letting your program end in the same way a normal python program will end.
You are looping infinitely calling pygame.quit() due to while(1).
You need to update the screen. Try it with
screen = pygame.display.set_mode((640,360),0,32)
and in the loop, write
pygame.dispay.flip()
to close the window completely, you can use
sys.exit()
just be sure to include sys in your imports
pygame does not recognize the term 'input' or 'print'. It would be a lot simpler if it did!! Instead, to get text onto the screen, you must use 'drawText('message',font,surface,(xpos,ypos) putting your own text in 'message', your own surface name in 'surface' and the x and y co-ordinates in 'xpos' and 'ypos'.

Issue with sys.exit() in pygame

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)

Categories