Every game development tutorial starts the same way: colored rectangles sliding across a gray canvas. That is fine for learning syntax, but it teaches you nothing about how a game engine actually breathes. I wanted out of the rectangle business. I wanted to build something that felt like a real game—a top-down dungeon crawler with movement, combat, a HUD, and sound.

I committed to Phaser v4 and gave myself one hard rule. Zero external assets. No image files, no audio clips, and no build tools like Webpack or Vite. The entire project had to live inside a single HTML file written with plain JavaScript. That constraint was not about minimalism for its own sake. It was about removing every excuse and every black box. When you cannot download a sprite pack to cover up a gap in your knowledge, you are forced to learn how the engine manages textures, animations, audio, and state under the hood.

Drawing the World from Code

In a normal Phaser project, you call this.load.image() inside a preload function and point the engine toward a PNG file. Without that option, you turn to the Graphics object. You instantiate it, draw primitive shapes—rectangles for floor tiles, thicker strokes for walls, maybe a circle for a player token—and then call generateTexture. That method captures the graphics buffer and registers it with Phaser’s texture manager under a key you choose.

From that moment on, the engine treats that generated bitmap exactly like a loaded image file. You can assign it to tilemaps, slice it into sprites, or tint it. For the dungeon crawler, this meant I could procedurally generate a floor grid, stamp down wall segments, and iterate on the color palette without ever leaving my code editor. The practical lesson is that a texture is just a chunk of bitmap data sitting in memory. Phaser does not care whether it arrived via HTTP request or a hand-coded Graphics call.

This approach also makes you think deliberately about draw order and batching. When every wall and floor tile comes from the same family of generated textures, you start paying attention to how Phaser groups render calls. You notice the difference between a static tilemap layer and a spritemap of individual objects because you are manually deciding which deserves to exist as a texture instance.

Animating Without Spritesheets

Static squares grow stale quickly, but Phaser’s animation system expects a spritesheet—usually a single PNG with frames laid out in a grid. I replicated that strip using an offscreen HTML canvas element. For each frame of an animation, I cleared the canvas and drew a new pose: a simple sword swing, a two-step walk cycle, or an enemy idle bob. Once the strip was complete, I registered it with Phaser as a spritesheet, defining the frame width and height so the engine knew where one pose ended and the next began.

Doing this manually reveals exactly what an animation is under the surface: a set of frame boundaries on a shared texture. Phaser’s animation component asks for a start frame, an end frame, and a frame rate. It then advances a pointer through those rectangular slices on each tick of the game clock. You stop thinking of spritesheets as magical assets produced by artists and start seeing them as coordinate math. That perspective is invaluable later when you are slicing real art or debugging why an animation plays frames out of order.

Sound from Nothing

Audio files were banned, so I used the Web Audio API directly. A few lines of JavaScript can create an oscillator node, set it to a square or sine wave, pipe it through a gain node, and schedule a short burst of sound. I wrote tiny helpers for common events: a low-frequency beep for footsteps, a rising chirp for picking up loot, and a harsh square-wave tone for taking damage.

These synthesized sounds are placeholders by design, but they give the game mechanical feedback immediately. You can feel whether the timing is right before you commit to recording or sourcing real audio. The real payoff comes in the architecture. Because you wrapped the sound trigger in a simple function, swapping the synthesized beep for a loaded sound buffer later takes a single line change. The rest of the game—the collision event, the UI flash, the score increment—stays untouched. You prototype the feel first, then upgrade the fidelity.

Managing Multiple Worlds

Un juego real necesita más de una pantalla, así que dividí el proyecto en escenas de Phaser independientes: Menu, Game, UI y Pause. La escena de la UI se ejecuta en paralelo con la escena de Game, lanzándose simultáneamente para que la barra de salud y el contador de puntuación vivan en su propio entorno aislado mientras la exploración de la mazmorra ocurre debajo. Se comunican estrictamente a través de eventos. Cuando el jugador recibe daño, la escena de Game emite un cambio. La escena de UI escucha y actualiza sus objetos de texto. La escena de Game no importa la UI, no llama a sus métodos, ni siquiera comprueba si existe. Simplemente envía datos al vacío. Ese desacoplamiento significa que puedes extraer el HUD para realizar pruebas, o reemplazarlo por completo, sin tocar el bucle principal del juego.

Para la pausa, utilicé una escena de Pause apilada que se sitúa encima de la escena de Game. Crucialmente, llamar a scene.pause() en la escena de Game realmente congela el mundo de la física y detiene los temporizadores. La escena de Game deja de actualizarse, pero la escena de Pause permanece activa para renderizar un menú y esperar una señal de reanudación. Si alguna vez has gestionado los estados de pausa únicamente con una flag booleana dentro de un único y gigante bucle de actualización, esto se siente como descubrir un interruptor de luz. El motor te ofrece un ciclo de vida de pausa real en lugar de obligarte a salpicar tu código con guardias if (isPaused) return.

Lecciones difíciles de errores reales

Trabajar tan cerca del metal me expuso a dos hábitos que necesitaba cambiar.

Primero, intenté usar un método en Phaser v4 que parecía público pero no formaba parte de la API documentada. Cambió entre versiones y rompió mi compilación. Refactoricé para usar getChildren(), que es un método público estable y documentado, y la inestabilidad desapareció. La lección es tajante: si un método no está en la documentación oficial, no construyas tu juego sobre él. Las API internas son internas por una razón. Limítate a la superficie pública y tu proyecto sobrevivirá a las actualizaciones del motor.

Segundo, aprendí a no confiar en los eventos para todo. Los callbacks de eventos funcionan perfectamente para interacciones de bajo riesgo, como recoger una moneda o abrir un cofre. Pero para transiciones de estado críticas —especialmente el Game Over— añadí una comprobación redundante dentro del bucle de actualización principal. Los eventos pueden fallar si se elimina un listener, si una escena se pausa en un microsegundo incómodo o si se cuela una condición de carrera entre la emisión y el manejo. Al comprobar la salud del jugador directamente en el bucle de actualización y forzar el estado de fin de juego si llega a cero, me aseguré de que el juego nunca pudiera quedarse atrapado en un estado de limbo si un evento no llegaba a ejecutarse. Los eventos siguen gestionando los efectos secundarios —sacudida de pantalla, señales de sonido, envío de la puntuación—, pero la lógica de autoridad reside donde reside el reloj del juego.

Por qué deberías probar esto

Si estás aprendiendo desarrollo de videojuegos, impón esta misma restricción a tu próximo proyecto: sin assets externos, un solo archivo HTML. Suena restrictivo, pero elimina cualquier excusa. No necesitas configurar un bundler, luchar con errores de CORS en archivos de audio locales, ni pasar una tarde seleccionando packs de assets gratuitos. Escribes código, refrescas el navegador y ves los resultados.

Más importante aún, entenderás por qué el motor se comporta como lo hace. Sabrás cómo una textura entra en la GPU porque llamaste a generateTexture. Sabrás cómo se indexan los fotogramas de animación porque registraste los límites a mano. Sabrás cómo el audio llega a los altavoces porque conectaste el oscilador. Ese conocimiento se transfiere directamente a proyectos más grandes que sí utilizan assets externos, porque la mecánica subyacente nunca cambia: el motor