So far, we have learned how to open a window and draw static scenes with geometric shapes and colors. However, what sets a game apart from an animation is interactivity: the ability to respond to player actions in real time.
In this third part, we will focus on the update() function. You will learn how to capture keyboard and mouse input, move elements while respecting screen boundaries, and structure your code using Object-Oriented Programming to avoid the mess of global variables.
Capturing Keyboard Input: btn vs btnp
To check if the player has pressed a key, Pyxel offers three main functions. Understanding the difference between them prevents many bugs right from the start:
-
pyxel.btn(key): returnsTruewhile the key is being held down.- When to use: continuous actions, such as walking left or accelerating a car.
-
pyxel.btnp(key)(button pressed): returnsTrueonly on the exact frame the key was pressed. Even if the player keeps holding the button, it will not trigger again until they release and press it again.- When to use: one-off actions, such as jumping, shooting an arrow, pausing the game, or navigating a menu.
-
pyxel.btnr(key)(button released): returnsTrueon the exact frame the key is released.- When to use: mechanics like "charging" an attack or jump while holding the button and firing upon release.
Keys are represented by intuitive constants starting with pyxel.KEY_, such as pyxel.KEY_LEFT, pyxel.KEY_RIGHT, pyxel.KEY_UP, pyxel.KEY_DOWN, pyxel.KEY_SPACE, or letters like pyxel.KEY_W, pyxel.KEY_A, pyxel.KEY_S, and pyxel.KEY_D.
Check the Pyxel API Reference for the complete list of key constants.
Capturing Mouse Input
In addition to the keyboard, Pyxel also easily reads mouse position and clicks:
-
pyxel.mouse_xandpyxel.mouse_y: properties that store the current coordinates of the cursor inside the game window. -
pyxel.btn(pyxel.MOUSE_BUTTON_LEFT)(orbtnp): checks for left-button clicks (MOUSE_BUTTON_RIGHTandMOUSE_BUTTON_MIDDLEare also available).
Important tip: By default, Pyxel hides the operating system cursor when the mouse hovers over the game window. If you want to display the library's default retro cursor, simply add
pyxel.mouse(True)right afterpyxel.init().
Movement and Screen Boundaries
In Pyxel, moving an object is nothing more than changing its x and y coordinates inside update() every frame.
If a character starts at x = 80 and we add 2 every frame (at 30 FPS), it will move 60 pixels to the right every second. However, if we don't create a boundary rule, it will keep walking off the window until it disappears.
To prevent a square of width size from leaving the screen, Pyxel provides its own utility function called pyxel.clamp(val, lower, upper), which "clamps" a number within a minimum and maximum range:
# Ensures x stays between 0 (left edge) and pyxel.width - self.size (right edge) self.x = pyxel.clamp(x=self.x, lower=0, upper=pyxel.width - self.size) self.y = pyxel.clamp(x=self.y, lower=0, upper=pyxel.height - self.size) This approach handles blocking at all four walls of the window without needing to write several chained if statements or nest functions like min() and max().
Why Use Object-Oriented Programming (class App)?
In the previous articles, we wrote standalone functions (update and draw). When we want to store data that changes over time — such as the player's x and y position — using only standalone functions in Python, we are forced to use the global keyword:
# Problematic approach as the project grows x = 80 y = 60 def update(): global x, y # We need to declare global in every function that modifies the data if pyxel.btn(pyxel.KEY_RIGHT): x += 2 In a real game, you will have player position, speed, score, lives, a list of enemies, and time. Managing dozens of global variables makes the code fragile and hard to read.
The standard solution in the Pyxel community is to encapsulate the game state inside a class (usually called App). This way, all variables belong to self and are accessible in both update and draw without needing global variables.
Putting It All Into Practice
Let's combine keyboard, mouse, screen boundaries, and Object-Oriented Programming into a complete example. In this program, you control an orange character with the arrow keys (or WASD), change its color by pressing SPACE, and can teleport it by clicking anywhere on the screen with the mouse.
Create the file movement.py and run it with pyxel run movement.py:
import pyxel class App: def __init__(self): # 1. Initialize the window and enable the mouse cursor pyxel.init(width=160, height=120, title="Movement and Controls") pyxel.mouse(visible=True) # 2. Initial player state self.size = 10 self.x = (pyxel.width - self.size) // 2 self.y = (pyxel.height - self.size) // 2 self.speed = 2 self.color = pyxel.COLOR_ORANGE # 3. Start the loop passing the class's own methods pyxel.run(self.update, self.draw) def update(self): # Quit the game with Q if pyxel.btnp(pyxel.KEY_Q): pyxel.quit() # Continuous movement with keyboard (arrow keys or WASD) if pyxel.btn(pyxel.KEY_LEFT) or pyxel.btn(pyxel.KEY_A): self.x -= self.speed if pyxel.btn(pyxel.KEY_RIGHT) or pyxel.btn(pyxel.KEY_D): self.x += self.speed if pyxel.btn(pyxel.KEY_UP) or pyxel.btn(pyxel.KEY_W): self.y -= self.speed if pyxel.btn(pyxel.KEY_DOWN) or pyxel.btn(pyxel.KEY_S): self.y += self.speed # One-off action: toggle color when pressing SPACE (btnp) if pyxel.btnp(pyxel.KEY_SPACE): if self.color == pyxel.COLOR_ORANGE: self.color = pyxel.COLOR_CYAN else: self.color = pyxel.COLOR_ORANGE # Mouse click: teleport the center of the player to the cursor if pyxel.btnp(pyxel.MOUSE_BUTTON_LEFT): self.x = pyxel.mouse_x - (self.size // 2) self.y = pyxel.mouse_y - (self.size // 2) # Keep the player within the window boundaries self.x = pyxel.clamp(x=self.x, lower=0, upper=pyxel.width - self.size) self.y = pyxel.clamp(x=self.y, lower=0, upper=pyxel.height - self.size) def draw(self): pyxel.cls(pyxel.COLOR_BLACK) # Draw the player at the current position pyxel.rect(x=self.x, y=self.y, w=self.size, h=self.size, col=self.color) # Display real-time coordinates at the top of the screen info = f"X:{self.x} Y:{self.y}" pyxel.text(x=4, y=4, s=info, col=pyxel.COLOR_WHITE) if __name__ == "__main__": App() Final result:
Notice how Pyxel's convention remains intact: update handles exclusively the math and rules, while draw only reads self.x, self.y, and self.color to paint the screen.
Practical Challenge
To reinforce what we covered today, try implementing two improvements to the code above:
- Add a "sprint" button: while the player holds the
SHIFTkey (pyxel.KEY_SHIFT), the speed increases from2to4. - Make the character appear on the opposite side of the screen when crossing an edge (Pac-Man or Asteroids style), using the modulo operator
%(e.g.,self.x = self.x % pyxel.width).
Next Steps
Now we have a truly interactive game, well-structured in classes and responding to player commands. However, our characters are still just colored squares.
In the next article in the series, we will open Pyxel's Native Editor (pyxel edit): you will learn how to draw pixel art, build complete scenes with tilemaps, and compose retro sound effects and music to import directly into your code!

