Monday 7 December 2015

Pygame: Handling key press and release events

The event queue gets pygame.KEYDOWN and pygame.KEYUP events when the keyboard buttons are pressed and released.

pygame_hello.py
#import pygame
import pygame

#initialize game engine
pygame.init()

#Open a window
size = (800, 600)
screen = pygame.display.set_mode(size)

#Set title to the window
pygame.display.set_caption("Hello World")

dead=False

while(dead==False):
  for event in pygame.event.get(): 
    if event.type == pygame.QUIT:
      dead = True
    elif event.type == pygame.KEYDOWN:
      print("User pressed a key.")
    elif event.type == pygame.KEYUP:
      print("User released the key.")
      
#Shutdown display module
pygame.display.quit()


Run above program and type some keys, you will get following kind of output.
$ python3 pygame_hello.py 
User pressed a key.
User released the key.
User pressed a key.
User pressed a key.
User released the key.
User pressed a key.
User released the key.
User pressed a key.
User pressed a key.
User released the key.
User released the key.
User pressed a key.
User pressed a key.
User released the key.
User released the key.
User pressed a key.
User released the key.
User released the key.


References




Previous                                                 Next                                                 Home

No comments:

Post a Comment