Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 41 ยท Sound and Input

Input Maps, Held Keys and Mouse Dragging in Pygame

Go beyond basic input in Pygame: events versus held-key polling, key bindings in a dictionary for remapping, mouse wheel and button events, and drag and drop with offsets.

You already know how to read a key press and a mouse click. Real games need a little more structure: a clear rule for when to use events and when to poll the keyboard, a single place where key bindings live so players can remap them, and mouse interactions such as dragging a piece across the board. This lesson builds those three pieces.

Because a browser page has no window to give Pygame, the code that talks to the real input system is shown read-only. Each idea has a runnable stand-in that uses plain Python and the headless pygame.Rect, so you can feel the logic.

Events versus polling

Question Use Example
"Did the player just press jump?" event KEYDOWN jump, shoot, open menu
"Is the player holding left?" pygame.key.get_pressed() walking, steering
"Did the player click this button?" event MOUSEBUTTONDOWN UI
"Where is the cursor now?" pygame.mouse.get_pos() aiming

A press that lasts a single frame is easy to miss with polling (you might check just after the key came up), so one-time actions belong to events. A walking character should move on every frame the key is held, which events alone cannot tell you without extra bookkeeping.

Python
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
        player.jump()                          # one-shot: event
    elif event.type == pygame.KEYUP and event.key == pygame.K_SPACE:
        player.release_jump()                  # variable jump height

keys = pygame.key.get_pressed()                # continuous: polling
dx = (keys[pygame.K_RIGHT] or keys[pygame.K_d]) - (keys[pygame.K_LEFT] or keys[pygame.K_a])
dy = (keys[pygame.K_DOWN]  or keys[pygame.K_s]) - (keys[pygame.K_UP]   or keys[pygame.K_w])
player.x += dx * speed * dt

Subtracting booleans gives -1, 0 or +1 and replaces a pile of if statements. Remember to call pygame.event.get() (or pump()) every frame, otherwise the state is never refreshed.

Python Events versus held keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

x keeps changing in frames 2 and 3, when no event arrived, because RIGHT is still in the held set. That is what get_pressed() provides.

Mouse events in detail

Python
if event.type == pygame.MOUSEBUTTONDOWN:
    if event.button == 1:        # 1 left, 2 middle, 3 right
        shoot(event.pos)
elif event.type == pygame.MOUSEWHEEL:
    zoom += event.y * 0.1        # positive when scrolling up
elif event.type == pygame.MOUSEMOTION:
    cursor = event.pos           # event.rel = movement, event.buttons = held buttons

Prefer MOUSEWHEEL over the legacy buttons 4 and 5. For polling there is pygame.mouse.get_pos(), get_pressed() (three booleans) and get_rel() (movement since the last call). pygame.mouse.set_visible(False) hides the system cursor when you draw your own.

Drag and drop with a small state machine

Dragging has three phases: press on the object, move while holding, release. The detail beginners forget is the offset: remember where inside the object you grabbed it, otherwise it jumps so that its top-left corner sticks to the cursor.

Python Dragging a rectangle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real game you would keep a list of draggable objects and, on MOUSEBUTTONDOWN, loop through it in reverse drawing order so the top-most one is picked. Add a drop target by testing target.colliderect(box) on release, and snap the piece to a grid cell with integer division.

Building an input map

Hard-coding K_SPACE all over the code makes remapping and gamepad support painful. Put the keys in one dictionary and ask for actions:

Python
BINDINGS = {
    "left":  [pygame.K_LEFT, pygame.K_a],
    "right": [pygame.K_RIGHT, pygame.K_d],
    "jump":  [pygame.K_SPACE, pygame.K_UP, pygame.K_w],
}

def action_held(keys, action):
    return any(keys[k] for k in BINDINGS[action])

def action_pressed(event, action):
    return event.type == pygame.KEYDOWN and event.key in BINDINGS[action]

The game now asks action_held(keys, "jump"), and a settings screen can rewrite the dictionary at runtime (wait for the next KEYDOWN, store event.key, save it with JSON). The gamepad lesson adds a controller to the same idea.

Python Remapping at runtime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Using KEYDOWN for walking. The player must keep tapping. Use get_pressed().
  • Using get_pressed() for shooting. One tap fires many bullets, because the key stays down for several frames. Use KEYDOWN or a cooldown timer.
  • Forgetting the event pump. The window freezes and the input state goes stale.
  • No offset when dragging. The object snaps to the cursor corner.
  • Diagonal speed. Normalize the direction, as explained in Vectors and Angles.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which input style suits a one-time action like opening the inventory?

    A KEYDOWN event fires once per press. Polling would report 'pressed' for every frame the key is held.
  2. 2. What does keys[pygame.K_RIGHT] - keys[pygame.K_LEFT] evaluate to when only RIGHT is held?

    Booleans act like 1 and 0 in arithmetic, so 1 - 0 is 1.
  3. 3. Why store an offset when dragging an object with the mouse?

    The offset keeps the point you grabbed under the cursor.
  4. 4. What is the main benefit of an input map?

    Actions decouple gameplay from physical keys, which enables remapping and extra devices.

Summary

  • Events tell you what just happened; polling tells you the current state. Use events for one-shot actions and polling for continuous movement.
  • MOUSEBUTTONDOWN, MOUSEMOTION and MOUSEWHEEL carry positions, buttons and scroll amounts.
  • Dragging needs press, move and release handling plus a grab offset.
  • Keep key bindings in a dictionary of actions so remapping and gamepads are easy to add.

Next: Gamepad and Touch Input