296. Main keyboard mapping definition

Define keyboard-to-NES-button mapping for main_only_background.py.

Lesson 296 of 356 · tests/chapter_08_manual_main/test_296_main_keyboard_mapping_definition.py

File to update

main_only_background.py

Why this step exists

main_only_background.py is the historical background-only visual pygame runner. To make the ROM interactive, it needs a small mapping from NES controller button names to pygame key constants.

This first keyboard step only defines the mapping dictionary. The next test covers the helper that applies key events to Controller button booleans and wires it into the pygame event loop.

Suggested implementation example

import pygame


KEYS = {
    "a": pygame.K_z,
    "b": pygame.K_x,
    "select": pygame.K_RSHIFT,
    "start": pygame.K_RETURN,
    "up": pygame.K_UP,
    "down": pygame.K_DOWN,
    "left": pygame.K_LEFT,
    "right": pygame.K_RIGHT,
}

Why this direction?

This dictionary answers the question

"Which keyboard key controls this NES button?"

For example, in the next test we will do

KEYS["a"] == pygame.K_z

means keyboard Z controls NES A.

Out of scope

  • handling KEYDOWN / KEYUP events
  • pygame joystick/gamepad support
  • remapping UI
  • controller port 2

Run this lesson

uv run pytest tests/chapter_08_manual_main/test_296_main_keyboard_mapping_definition.py -v