Phaser with AI agents, one scene at a time
On this page
If you want a coding agent to make a 2D browser game, Phaser gives it a lot to work with. It’s a free, open-source framework under the MIT license, its npm package ships agent skills for the engine’s major systems, and its README says the API is “well understood by every major frontier LLM” (Phaser README).
Oddly enough, the trouble comes from all the older code out there. Phaser 3 tutorials and examples use APIs that Phaser 4 removed or changed, models still reproduce them, and two of those changes fail silently.
So this guide starts a project from Phaser’s template, gives the agent the skills from that exact release, and builds one scene at a time. If you haven’t set up an agent yet, the Claude Code guide or the Codex guide will get you there.
1. Start from the official template
Phaser 4.2.1 is the current release (release notes), and version 4.0.0 launched in April (release notes). Create the project with Phaser’s own CLI. For a first project its README suggests Web Bundler and then Vite (create-game), and you’ll want TypeScript when it asks.
npm create @phaserjs/game@latest my-game
cd my-game
npm install --save-exact phaser@4.2.1
That last line is there because the Vite TypeScript template on GitHub pins Phaser 4.0.0 (template). --save-exact keeps the version fixed, so the agent always works against the release its skills describe.
It’s also worth telling the agent which dev command to run. The template’s npm run dev and npm run build first run a log.js script that sends the template name, the build type and the Phaser version to a Phaser Studio server. If you’d rather it didn’t, npm run dev-nolog and npm run build-nolog skip it (template README).
The dev server runs on port 8080, and both Vite configs already set base: './', which comes in handy when you upload the build later.
2. Copy skills from the installed package
The skills come with the npm package, so there’s nothing extra to install. After the install above, node_modules/phaser/skills/ holds 28 skill folders, from scenes, physics-arcade and tilemaps to v3-to-v4-migration (package files, repository). Each one is a standard SKILL.md with a name and a description, so Claude Code keeps only those descriptions in context until a task matches one (skills docs).
Copy them from the package rather than from GitHub, so they always match the installed version. This script uses Node’s built-in fs.cpSync, which means it works on Windows too.
// scripts/sync-phaser-skills.mjs: copy the skills of the installed Phaser
import { cpSync } from 'node:fs';
cpSync('node_modules/phaser/skills', '.claude/skills', { recursive: true });
// For Codex, copy to '.agents/skills' instead.
npm pkg set scripts.postinstall="node scripts/sync-phaser-skills.mjs"
npm install
npm pkg set adds the script without you hand-editing package.json, and the bare npm install after it runs the project’s postinstall script (npm scripts).
There’s a little gotcha, though. npm only runs that hook for an install without package names (npm source), so after a targeted upgrade like npm install --save-exact phaser@<version>, you’ll need to run node scripts/sync-phaser-skills.mjs yourself.
Codex reads skills from .agents/skills (Codex docs), and our skills guide lists the folders Cursor and Gemini CLI read.
Each skill names the source files it describes, like src/scene/Scene.js. In your project those live in node_modules/phaser/src/, since the npm package ships the source too (package files). Put that path in your rules file, and the agent can read the real code when a skill isn’t enough.
3. Remove Phaser 3 habits from generated code
Years of Phaser 3 tutorials and examples are full of the patterns below, so it’s no wonder models keep writing them. Every one of them was removed or changed in Phaser 4, according to the migration guide and the 4.2.1 source.
| Phaser 3 code | Phaser 4 code | If it slips in |
|---|---|---|
setTintFill(color) |
setTint(color), then setTintMode() with Phaser.TintModes.FILL |
no tint: the method is now an empty stub that logs a console error |
Math.TAU as a quarter turn |
Math.PI_OVER_2 |
silent: TAU is now a full turn |
Math.PI2 |
Math.TAU |
removed |
Geom.Point |
Math.Vector2 |
the class is gone |
preFX, postFX |
enableFilters(), then filters.internal or filters.external; cameras have filters already |
preFX is undefined |
BitmapMask |
the Mask filter: filters.internal.addMask() |
the class is gone |
setPipeline('Light2D') |
setLighting(true) |
pipelines are gone |
roundPixels on by default |
off by default; pixelArt: true turns it on |
silent: sprites can sit between pixels |
Phaser.Structs.Set |
the native Set |
the class is gone |
Mesh, Plane, Camera3D |
removed; use a 3D library | the classes are gone |
The TAU row is the dangerous one. In Phaser 3.90, Phaser.Math.TAU is π/2 (source), but in the current release it’s 2π (current source). So code that used it still runs, and everything just turns four times too far, which is a pretty nasty bug to chase.
Glow and mask filters also need enableFilters() on a game object first (filters skill).
One line of the migration guide doesn’t actually match the code. It says Phaser.Structs.Map was replaced with the native Map, but 4.2.1 still exports it, contains() included (Structs source), and only Structs.Set is gone.
TypeScript catches most of the table, because Phaser ships its own type definitions (README). TAU and roundPixels sail through any type check, though, so they belong in your rules file by name.
4. Set version rules for the agent
Save these rules as AGENTS.md in the project root. Codex reads it as project guidance (Codex docs), and Claude Code reads it when the project doesn’t have a CLAUDE.md. If you do have a CLAUDE.md, put @AGENTS.md at the top of it (Claude Code docs).
The rules are our conventions for this project, and you’ll find the Phaser facts behind them, with sources, right after the block.
# Game rules: Phaser 4.2.1
- Phaser 4.2.1 from npm, pinned exactly. Vite, TypeScript.
Run npm run dev-nolog and npm run build-nolog.
- Phaser 4 APIs only. Check .claude/skills first; the source of truth is
node_modules/phaser/src. Porting Phaser 3 code? Read v3-to-v4-migration.
- Never use: setTintFill, Geom.Point, BitmapMask, preFX, postFX,
setPipeline, Math.PI2, Structs.Set.
Math.TAU is a full turn (2π). A quarter turn is Math.PI_OVER_2.
- Config: type Phaser.AUTO. Scale.FIT with CENTER_BOTH, base size 960x540.
pixelArt: true for pixel art. input.activePointers: 2.
- Scenes: Boot, Preloader, Game, UI. Launch UI in parallel with Game.
Reset per-run state in init(), never in the constructor.
- Create animations once, in Preloader. They are global.
- Listeners on this.events, this.registry.events, this.game.events,
this.scale, this.sound, window or document need a matching off()
in a SHUTDOWN handler.
- Movement through Arcade Physics velocity, never x += n per frame.
Pickups use overlap; walls use collider. Pool bullets and pickups
in a Group with maxSize.
- Game rules (scoring, lives, waves) live in src/rules/ with no Phaser
import, tested with Vitest.
- Fullscreen requests run on pointerup. No hover-only actions.
- After every change run npm run typecheck, npm test and npm run e2e.
The facts behind them come from Phaser’s own skills and source.
- State and animations. A scene’s constructor runs once, but
init()runs on every start and restart (scenes skill). Animations created withthis.anims.create()are global, and creating them again logs a warning (animations skill). - Physics.
overlapdetects without pushing and suits pickups,collideseparates bodies, and Arcade uses a fixed timestep by default (Arcade skill).group.get()reuses an inactive member before it creates a new one (groups skill). - Renderer.
Phaser.WEBGLhas no Canvas fallback, whileAUTOdoes (config skill), and the migration guide calls the Canvas renderer deprecated (migration guide).
5. Tie listeners to each scene run
Phaser’s own events skill calls listeners that are never removed “the most common source of bugs” (events skill). In a game they show up on the second run, because a listener added in create() gets added again on every restart, so the score counts twice or a sound plays twice.
Luckily, Phaser cleans up part of this for you. When a scene shuts down, its input plugin removes all of its own listeners (InputPlugin.js).
The scene’s own this.events emitter only drops its transition listeners, though (Systems.js), and the registry, the game events, the scale manager and the sound manager are shared by the whole game. Listeners on those pile up with every restart unless you remove them yourself, and you can see how a score ends up counting twice.
create() {
this.events.on('star-caught', this.addScore, this);
this.scale.on('resize', this.layout, this);
this.events.once(Phaser.Scenes.Events.SHUTDOWN, () => {
this.events.off('star-caught', this.addScore, this);
this.scale.off('resize', this.layout, this);
});
}
off() only removes a listener when you pass the same function reference that on() received, and the context is an optional filter that has to match if you give it (EventEmitter.js). Class methods and arrow functions stored in a field both work, but a new inline arrow function in the off() call matches nothing, even though it looks identical.
Phaser’s events skill shows this pattern with an input listener. In 4.2.1 it turns out the input plugin clears those itself, but the same habit still protects you on the emitters that don’t.
6. Build one scene at a time
The example here is pretty small. You catch falling stars in a basket and dodge rocks, with three lives, a score on screen and a restart. Each prompt ends with a check the agent can run, so it knows when it’s done.
First prompt: scenes and movement.
Read AGENTS.md. Set up Boot, Preloader, Game and UI scenes. The basket moves with the arrow keys or A and D on desktop and follows a dragging finger on a phone, inside the screen edges. Use rectangles and circles instead of art for now. Done when npm run typecheck passes and the basket moves in phone emulation too.
Second prompt: one complete run.
Add stars and rocks that fall from random x positions, pooled in two Groups. Catching a star adds 1 to the score; a rock costs a life; the run ends at zero lives with a game over panel and a Restart button. Keep scoring and lives in src/rules/run.ts with Vitest tests. Done when catching one star after five restarts still adds exactly 1.
Third prompt: the phone pass.
Make the game fit any screen with Scale.FIT, add a fullscreen button that requests fullscreen on pointerup, and play a catch sound once audio is unlocked. Done when two fingers work at once in phone emulation and the console stays empty.
When you’re ready for character art, AI sprite animation for games covers Phaser sprite sheets and atlases.
7. Test game rules and browser play separately
Keeping the rules free of Phaser pays off here, because they test in milliseconds with Vitest (npm install --save-dev vitest).
// src/rules/run.test.ts
import { test, expect } from 'vitest';
import { newRun, catchStar, hitRock } from './run';
test('a run ends exactly when the last life is lost', () => {
let run = newRun(); // 3 lives, score 0
run = catchStar(run);
run = hitRock(hitRock(run));
expect(run.over).toBe(false);
run = hitRock(run);
expect(run).toMatchObject({ score: 1, lives: 0, over: true });
expect(catchStar(run).score).toBe(1); // no points after the end
});
Whole-game tests need a clock the agent controls. Phaser’s game.loop.sleep() stops its requestAnimationFrame loop (TimeStep.js), and game.step(time, delta) runs one full update and render of every active scene (Game.js).
Load the hook only with ?test=1, so the test advances by whole frames.
Count frames as integers, too. It’s easy to miss, but a loop that adds 1000/60 to a float until the total reaches one second runs 61 times, not 60.
// src/test-hooks.ts
import Phaser from 'phaser';
type GameScene = Phaser.Scene & { snapshot(): object };
export function installTestHooks(game: Phaser.Game) {
const dt = 1000 / 60;
let now = performance.now();
game.events.once(Phaser.Core.Events.POST_STEP, () => game.loop.sleep());
const advanceFrames = (n: number) => {
for (let i = 0; i < n; i++) game.step((now += dt), dt);
};
const scene = () => game.scene.getScene('Game') as GameScene;
Object.assign(window, {
advanceFrames,
advance: (ms: number) => advanceFrames(Math.round(ms / dt)), // 1000 ms = 60 frames
restart: () => scene().scene.restart(),
catchStar: () => scene().events.emit('star-caught'),
gameState: () => (game.scene.isActive('Game') ? scene().snapshot() : { scene: 'loading' }),
});
}
Call it from src/main.ts when the URL has ?test=1, and have the Game scene’s snapshot() return scene: 'playing', the score, the lives and listeners: this.events.listenerCount('star-caught'). While the loop sleeps, scenes only move when the test steps frames, and that even includes the switch from Preloader to Game.
Point Playwright’s web server option at the template’s dev server, with command: 'npm run dev-nolog' and url: 'http://localhost:8080'. Then this test restarts the run five times and checks for the doubled-listener bug.
// e2e/restart.spec.js
import { test, expect } from '@playwright/test';
test('five restarts leave one listener and one point per star', async ({ page }) => {
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
page.on('console', (m) => m.type() === 'error' && errors.push(m.text()));
await page.goto('http://localhost:8080/?test=1&seed=1');
// Step a few frames per poll, so assets can load between polls.
await page.waitForFunction(() => {
window.advanceFrames?.(3);
return window.gameState?.().scene === 'playing';
});
for (let i = 0; i < 5; i++) {
await page.evaluate(() => { window.restart(); window.advanceFrames(30); });
}
const before = await page.evaluate(() => window.gameState());
expect(before.listeners).toBe(1);
await page.evaluate(() => { window.catchStar(); window.advanceFrames(1); });
expect((await page.evaluate(() => window.gameState())).score).toBe(before.score + 1);
expect(errors).toEqual([]);
});
Playtesting games with AI adds a general smoke test that plays one seeded round, and you’ll just need to adapt its port and hooks to this template.
8. Fit the game to a phone screen
- Screen fit.
Scale.FITkeeps the aspect ratio inside the parent element. The parent needs a real size, the ScaleManager ignores its padding, and CSS on the canvas itself conflicts with it (scale skill). - Two thumbs. This one’s tricky, because by default, Phaser only tracks one touch pointer, and the first pointer belongs to the mouse, so move-and-jump controls need an extra one (Config.js, InputManager.js).
| Pointer setting | Value |
|---|---|
Default input.activePointers |
1 |
| Mouse pointer | 0 |
| Touch pointers | 1 and up |
| Move-and-jump controls | activePointers: 2 or more |
- Audio. Phaser even unlocks Web Audio by itself on the first touch, click or key press. To start music, wait for the sound manager’s
unlockedevent wheneverthis.sound.lockedis true (audio skill). - Fullscreen. Request it on
pointerup, since touch browsers can block it onpointerdown, and give your iframeallowfullscreen(scale skill).
How to make a mobile game with AI goes through the phone test session in more detail.
9. Build and ship
Run npm run build-nolog, and the template writes the game to dist/. This is where those relative base: './' paths come in handy, since itch.io requires relative asset paths. Zip the contents of dist/ with index.html at the root of the archive and upload it as an HTML game (itch.io docs).
If itch.io isn’t the right home for it, where to publish a browser game compares the other hosts.
When the editor and cloud agent help
Phaser Studio also makes two AI products alongside the open-source framework, though you don’t need either one for the setup above.
-
Phaser Editor v5 includes an MCP server that lets an AI client work inside a running editor. It can list and open scenes, edit objects, take screenshots, and manage assets, spritesheets, animations and tilemaps, and the release post counts more than 40 tools (release post). The docs show setup for Claude Desktop, Cursor and VS Code, and warn that many features are still to come (docs).
-
The Phaser Game Agent builds a game from a description in a cloud sandbox, using Phaser AE, an AI-specific framework that’s separate from Phaser 4 (announcement). Its MCP server works with Claude Code, Codex and Cursor. Sandbox time is billed per minute, and a full game typically costs around 500 credits (MCP page). You can export the TypeScript source (export post).
What creators have built with Phaser
The Phaser games we list credit Claude Code, Codex and Cursor. Our entries record the engine and the tools, though, not which skills or tests a creator used.
Out of 27 games; a game can count in several bars.
-
Reach the Relay is a turn-based RPG with active-time battles, made with Claude Code, and it placed 65th at Vibe Jam.
-
Hired Swords is an autobattler that pits your team against other players’ saved ghost teams, so nobody else has to be online at the same time. It placed 68th and was also made with Claude Code.
-
Vibe Party is a board game with minigames for up to four players, online or local, made with Codex.
-
Block Yard is a mobile-first factory puzzle with a level editor for sharing puzzles, made with Claude Code.
-
Dungeon Cast is kind of a surprise for a 2D engine, because it draws a first-person dungeon with raycasting. It was made with Claude Code.
-
Wagon Bones puts Balatro-style scoring with d12 dice on the Oregon Trail, and it placed seventh at the third AI Browser Game Jam.
For more, there’s the Phaser hub, Claude Code games and Codex games, plus the engine comparison, which sets Phaser against Three.js, PixiJS and Godot.
Know when the build is done
You can call the build done when the release build loads from dist/, plays a full run, restarts five times without doubled events and works with two thumbs on a real phone, all with no console errors. Write down the Phaser version and the skills you copied alongside the build, so the next session starts from the same facts.
Then submit the game with its playable URL and an honest account of what the AI made. We review every game before it’s listed, under our editorial policy.
Games to look at
, Phone friendlyReach the Relay
Pick a route through AI-ravaged ruins and keep your VIP alive in turn-based fights.
, Phone friendly , Online multiplayerHired Swords
Draft a team of fighters and battle other players' ghost teams in auto-battles.
, Phone friendly , Online multiplayerVibe Party
Race around a board and win chaotic minigames with cute AI-themed characters
, Phone friendly , Online multiplayerBlock Yard
Place factories on a grid to build shapes, then design levels to stump friends.
Dungeon Cast
Explore a raycast dungeon in first person, right in your browser.
Wagon Bones
Roll d12 dice, build scoring hands, and travel the Oregon Trail one leg at a time.
Questions
Can AI make a Phaser game?
Yes. A Phaser game is just JavaScript or TypeScript in text files, so coding agents like Claude Code, Codex and Cursor can write, run and test it. We list 27 Phaser games, including Reach the Relay and Hired Swords, which both placed in the Vibe Jam 2026 top 70 and were both made with Claude Code.
Where are Phaser's AI agent skills?
They're in the skills folder of the Phaser repository and inside the npm package. After npm install phaser@4.2.1 you'll find 28 folders in node_modules/phaser/skills, from scenes and tilemaps to a v3-to-v4 migration skill. Copy them into .claude/skills for Claude Code or .agents/skills for Codex.
Should a new game made with AI use Phaser 3 or Phaser 4?
Phaser 4. It came out on April 10, 2026, its skills cover Phaser 4 APIs, and the official templates install it. Add a rules file that lists the Phaser 3 APIs it removed or changed, though, because older tutorials and examples still use them.
Does the Phaser Game Agent use Phaser 4?
No. Its page says games are built with the Phaser Agentic Engine, Phaser AE, in a cloud sandbox that's billed in credits. Since August 2026 you can export the TypeScript source with the exact Phaser AE version, while Phaser 4 itself is free and open source.
Why does my Phaser game ignore a second finger on a phone?
Because Phaser creates only one touch pointer by default (input.activePointers is 1). For controls that need two thumbs at once, like move and jump, set input.activePointers to 2 or more in the game config, or call this.input.addPointer().
Do I need Phaser Editor to make a game with AI?
No, since the agent writes scenes as code. Phaser Editor v5 does add an MCP server that lets an AI client work on editor scenes, assets and tilemaps, which helps if you like to lay out levels visually in the editor.