How to Create a Basic Game with Pyxel in Python
Pyxel is a retro-style library for creating pixel-art games. It is lightweight, simple, and perfect for learning.
1. Installing Pyxel
Make sure you have Python 3.7+ installed, then run:
pip install pyxel
2. Minimum Structure of a Pyxel Game
Every Pyxel game needs three parts:
- init() → Initializes game variables
- update() → Runs 60 times per second (logic)
- draw() → Draws each frame on the screen
3. First Game: Move a Square with the Keyboard
This game shows how to move a simple character using the arrow keys.
Full Code
import pyxel
class Game:
def __init__(self):
pyxel.init(160, 120, title="Basic Pyxel Game")
# Player initial position
self.x = 70
self.y = 50
pyxel.run(self.update, self.draw)
def update(self):
# Arrow key movement
if pyxel.btn(pyxel.KEY_RIGHT):
self.x += 2
if pyxel.btn(pyxel.KEY_LEFT):
self.x -= 2
if pyxel.btn(pyxel.KEY_UP):
self.y -= 2
if pyxel.btn(pyxel.KEY_DOWN):
self.y += 2
# Keep player inside the screen
self.x = max(0, min(self.x, 160 - 8))
self.y = max(0, min(self.y, 120 - 8))
def draw(self):
pyxel.cls(0) # Clear the screen with black
pyxel.rect(self.x, self.y, 8, 8, 11) # Draw player (light blue square)
Game()
4. Code Explanation
pyxel.init(width, height, title)
Creates a game window.
pyxel.run(update, draw)
Starts the game loop.
Movement
pyxel.btn() detects whether a key is pressed.
Drawing
pyxel.rect(x, y, width, height, color) draws a rectangle.
5. Adding an Enemy That Moves by Itself
Here we add something more dynamic.
import pyxel
class Game:
def __init__(self):
pyxel.init(160, 120, title="Game with Enemy")
self.x = 70
self.y = 50
# Enemy
self.ex = 0
self.ey = 30
self.enemy_dir = 1
pyxel.run(self.update, self.draw)
def update(self):
# Player movement
if pyxel.btn(pyxel.KEY_RIGHT):
self.x += 2
if pyxel.btn(pyxel.KEY_LEFT):
self.x -= 2
if pyxel.btn(pyxel.KEY_UP):
self.y -= 2
if pyxel.btn(pyxel.KEY_DOWN):
self.y += 2
# Enemy movement (horizontal)
self.ex += self.enemy_dir
# Enemy bounce
if self.ex <= 0 or self.ex >= 160 - 8:
self.enemy_dir *= -1
def draw(self):
pyxel.cls(0)
pyxel.rect(self.x, self.y, 8, 8, 11) # player
pyxel.rect(self.ex, self.ey, 8, 8, 8) # enemy
6. Collision Detection
def collision(a_x, a_y, b_x, b_y, size=8):
return abs(a_x - b_x) < size and abs(a_y - b_y) < size
Usage example in update():
if collision(self.x, self.y, self.ex, self.ey):
print("Collision!")
7. Adding Simple Sound
pyxel.sound(0).set("c2e2g2c3", "p", "7", "f", 10)
pyxel.play(0, 0)
8. Compile to an Executable (Optional)
On Windows you can use:
pyxel package . game.py
pyxel app example.pyxapp