Pygame: Responding to keyboard input Cheat Sheet

Responding to key presses

Pygame’s main event loop registers a KEYDOWN event any time a key is pressed. When this happens, you can check for specific keys.

for event in pg.event.get():
    if event.type == pg.KEYDOWN:
         if event.key == pg.K_RIGHT:
               ship_rect.x += 1
         elif event.key == pg.K_LEFT:
               ship_rect.x -= 1
         elif event.key == pg.K_SPACE:
               ship.fire_bullet()
         elif event.key == pg.K_q:
               sys.exit()

Responding to released keys

When the user releases a key, a KEYUP event is triggered.

if event.type == pg.KEYUP:
    if event.key == pg.K_RIGHT:
        ship.moving_right = False

Leave a Reply

Your email address will not be published. Required fields are marked *