I've read similar questions to this on Stack Overflow but they have not helped. Here is my code:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Hello World')
pygame.mouse.set_visible(1)
done = False
clock = pygame.time.Clock()
while not done:
clock.tick(60)
keyState = pygame.key.get_pressed()
if keyState[pygame.K_ESCAPE]:
print('\nGame Shuting Down!')
done = True
Pressing escape
does not exit the game or print a message. Is this a bug? If I print the value for keyState[pygame.K_ESCAPE], it is always zero.
May I suggest using an event que instead? It's probably a better idea:
The problem is that you don't process pygame's event queue. You should simple call
pygame.event.pump()
at the end of your loop and then your code works fine:From the docs (emphasis mine):
Note that you don't have to do this if you just call
pygame.event.get()
anywhere in your main-loop; if you do not, you should probably callpygame.event.clear()
so the event queue will not fill up.do something like this:
you dont need the
pygame.
on the if statment and also you should callpygame.display.flip()
so it properly shows the window then you need an event loop to exit the programYou should provide the version of
pygame
andpython
.I met the similar issue when I use
pygame 1.9.4dev
andpython 3.6.5
I fix this problem after I downgrade
pygame
and reinstallpython
.NOTE: If you use
pyenv
, you must make sure--enable-framework
option is set when installing python.Use the following code to check whether it is work.