Cómo crear un juego básico con Pyxel en Python

DJC > Tutorial

Pyxel es una librería retro para crear videojuegos estilo pixel-art. Es ligera, sencilla y perfecta para aprender.


1. Instalación de Pyxel

Asegúrate de tener Python 3.7+ instalado, luego ejecuta:

pip install pyxel

Pyxel - github ↗


2. Estructura mínima de un juego con Pyxel

Todo juego en Pyxel necesita tres partes:

  1. init() → Inicializa variables del juego
  2. update() → Se ejecuta 60 veces por segundo (lógica)
  3. draw() → Dibuja en pantalla cada frame

3. Primer juego: mover un cuadrado con el teclado

Este juego muestra cómo mover un personaje simple usando las teclas de flechas.

Código completo

import pyxel

class Game:
    def __init__(self):
        pyxel.init(160, 120, title="Juego Básico Pyxel")

        # Posición inicial del jugador
        self.x = 70
        self.y = 50

        pyxel.run(self.update, self.draw)

    def update(self):
        # Movimiento con flechas
        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

        # Mantener dentro de la pantalla
        self.x = max(0, min(self.x, 160 - 8))
        self.y = max(0, min(self.y, 120 - 8))

    def draw(self):
        pyxel.cls(0)  # Limpia la pantalla con color negro
        pyxel.rect(self.x, self.y, 8, 8, 11)  # Dibujar jugador (cuadrado celeste)


Game()

4. Explicación del código

pyxel.init(ancho, alto, title)

Crea una ventana de juego.

pyxel.run(update, draw)

Comienza el bucle del juego.

Movimiento

pyxel.btn() detecta si la tecla está presionada.

Dibujo

pyxel.rect(x, y, ancho, alto, color) dibuja un rectángulo.


5. Agregar un enemigo que se mueve solo

Aquí agregamos algo más dinámico.

import pyxel

class Game:
    def __init__(self):
        pyxel.init(160, 120, title="Juego con Enemigo")

        self.x = 70
        self.y = 50

        # Enemigo
        self.ex = 0
        self.ey = 30
        self.enemy_dir = 1

        pyxel.run(self.update, self.draw)

    def update(self):
        # Movimiento del jugador
        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

        # Movimiento del enemigo (horizontal)
        self.ex += self.enemy_dir

        # Rebote del enemigo
        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)  # jugador
        pyxel.rect(self.ex, self.ey, 8, 8, 8)  # enemigo

6. Detección de colisiones

def colision(a_x, a_y, b_x, b_y, size=8):
    return abs(a_x - b_x) < size and abs(a_y - b_y) < size

Ejemplo de uso en update():

if colision(self.x, self.y, self.ex, self.ey):
    print("¡Colisión!")

7. Agregar sonido simple

pyxel.sound(0).set("c2e2g2c3", "p", "7", "f", 10)
pyxel.play(0, 0)

8. Compilar a ejecutable (opcional)

En Windows puedes usar:

pyxel package . juego.py
pyxel app ejemplo.pyxapp

DJC > Tutorial