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.
pygame.key.get_pressed. — get the state of all keyboard buttons.
Detecting if a key is pressed: KEYDOWN and pygame. KEYUP events respectively. For example, if we want to detect if a key was pressed, we will track if any event of pygame. KEYDOWN occurred or not and, accordingly, we will get to know if any key was pressed or not.
In Python 2, use raw_input() : raw_input("Press Enter to continue") This only waits for the user to press enter though. This should wait for a key press.
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:
...
while not done:
clock.tick(60)
keyState = pygame.key.get_pressed()
if keyState[pygame.K_ESCAPE]:
print('\nGame Shuting Down!')
done = True
pygame.event.pump() # process event queue
From the docs (emphasis mine):
pygame.event.pump()
internally process pygame event handlers
pump() -> None
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system. If you are not using other event functions in your game, you should call pygame.event.pump() to allow pygame to handle internal actions.
This function is not necessary if your program is consistently processing events on the queue through the other pygame.event functions.
There are important things that must be dealt with internally in the event queue. The main window may need to be repainted or respond to the system. If you fail to make a call to the event queue for too long, the system may decide your program has locked up.
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 call pygame.event.clear()
so the event queue will not fill up.
May I suggest using an event que instead? It's probably a better idea:
while True: #game loop
for event in pygame.event.get(): #loop through all the current events, such as key presses.
if event.type == QUIT:
die()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: #it's better to have these as multiple statments in case you want to track more than one type of key press in the future.
pauseGame()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With