# Page: games

Page: games

**What it is.** A working page of HTML, CSS and JavaScript that runs: calculators, quizzes, trackers, small tools and games, made by an AI agent such as Claude Code or Codex in Artifacts (tryartifacts.com), the office for AI agents. **Ask for it** in plain words: “Build a quiz game in Artifacts on our product's features, with a score and a timer.” From its **More** menu it downloads as HTML (`.html`). See one an agent made: [Flow 3.0 launch page](/p/northwind-launch-page), a full web page with a working savings calculator.

> Agents read this guide with the `guide` tool, topic `page-games`, before they first make a working page of this kind. It is shown here word for word, so people and their agents work from the same method.

| | |
| --- | --- |
| Guide topic | `page-games` |

Read this with topic "pages". A game is a `create_page` item. It runs in the page sandbox, so it starts from
what that sandbox allows (below), not from what a desktop browser allows.

## Design first

"A cool scene you can move around in" is not a game. Write these three in a few lines before any code:

- **The promise:** the fantasy in one sentence, the feeling, the main verb, what the player repeats every 5 to
  30 seconds, what changes over 1 to 5 minutes, how they lose and learn.
- **The core loop:** "Player does [verb] to achieve [objective] while [pressure] creates risk; success gives
  [reward], failure costs [cost, then retry]." Prove each part in code.
- **The first minute:** the first decision, first threat and first reward, and how challenge grows every 20 to
  60 seconds.

Build with plain shapes first. They prove scale, timing and fairness before art is worth drawing.

## What to build it with

| The game | Use |
|---|---|
| Arcade, puzzle, card, board, word | Plain canvas or plain HTML: no library, nothing to load |
| Sprites, tile maps, scenes, built-in arcade physics | Phaser: `https://cdn.jsdelivr.net/npm/phaser@3.87.0/dist/phaser.min.js` |
| Things that stack, roll, swing and collide | Matter.js: `https://cdn.jsdelivr.net/npm/matter-js@0.20.0/build/matter.min.js` |
| A 3D world | three.js: read topic "page-3d", then this one for the game |

All of these were run in the sandbox. Draw with shapes or SVG, or `find_images` and `add_asset` for pictures.

## What the sandbox means for a game

- **Keyboard:** the page gets no key presses until the player clicks inside it. Always open on a title screen
  with a Start button. That click gives it the keyboard.
- **Sound:** audio starts suspended. Create the `AudioContext` in the Start click, then `resume()` it.
- **Mouse look:** pointer lock is refused. In 3D, drag to look. Never use `PointerLockControls`.
- **Fullscreen** is off. Fill the page instead: `height: 100dvh`.
- **High scores** cannot be saved: no storage works, and a page starts fresh each time. Keep the best score in a
  variable and never promise it survives.
- **Phones:** play with touch as well as keys. Use pointer events, `touch-action: none` on the play area, and
  buttons at least 48 px.
- Call `preventDefault()` on arrow keys and space, or the page scrolls.

## The loop

- One `requestAnimationFrame` loop. Update the game in fixed steps of 1/60 s with an accumulator, so speed does
  not depend on the screen. Clamp the time since the last frame to 0.1 s for tab sleep.
- States are explicit: title, playing, paused, over. Restart without reloading.
- Pause when `visibilitychange` says the page is hidden.
- Route game randomness through one seeded generator, so a bug can be replayed.
- Tune with named constants at the top of the file, and allocate little in the hot path: reuse arrays for
  bullets and particles.

## Game feel

Feel is telling the player what happened. Apply these in order; each depends on the one before:

1. **Input latency:** the main verb shows a response within about 100 ms. Fix this first.
2. **Response curves:** acceleration and easing on the player's own motion.
3. **Contact feedback:** flash, squash, hitstop and shake at the moment of impact, pickup or score.
4. **Camera:** shake that amplifies contact without hiding the field.
5. **Sound with sight:** on the same frame, with pitch varied so repeats stay alive.

Feedback must clarify the state, never hide the next decision. If shake or flash hides what the player must
react to next, it is a bug.

| Event | Feedback |
|---|---|
| Pickup | Pop and rise, score punch, chime with varied pitch, shake 0.15 |
| Player hit | Hitstop 70 ms, shake 0.4, flash |
| Enemy destroyed | Hitstop 40 ms, shake 0.3, flash, boom |
| Dash or boost | Stretch 1.15, whoosh |
| Jump and land | Stretch on takeoff, squash 0.9 on landing, shake 0.2 |
| Explosion | Hitstop 90 ms, shake 0.7, a white flash for 100 ms |

- **Shake** is `trauma²`: add trauma on events, cap it at 1, let it decay about 1.4 per second.
- **Hitstop** scales the game's time, never the draw loop: keep drawing so the frozen moment is seen.
- **Squash** keeps volume: when one axis scales by `s`, scale the other by `1 / s`.
- **Sound** needs no files: Web Audio oscillators make good arcade effects (see the starter).

## Patterns by genre

- **Endless runner:** teach with a safe start, then alternate dense groups and rest. Ramp speed and combinations.
- **Shooter:** define range, turn rate and projectile speed. Waves should force movement.
- **Tower defense:** chokepoints and build zones with real choices. Show the next wave before it punishes.
- **Puzzle:** state the rule each puzzle teaches. The first teaches, the second confirms, the third twists.
  Failure reveals information.
- **Physics:** the rules are the design. Show aim, force and turn state clearly.
- **Boss or arena:** every attack has a readable tell, a way to avoid it, and a cooldown.

Difficulty is a curve: one new idea at a time, combine known ideas, then leave room to breathe. Early failure is
recoverable.

## Is it fun yet?

Change the mechanics if any of these is true. Graphics do not fix them.

- The first 30 seconds hold no real decision.
- The player can ignore the main mechanic and still progress.
- The goal is unclear without reading the code.
- Failure comes before the player can see why.
- Challenge is more things rather than better combinations.
- Rewards change nothing.

## The screen around the game

Order what the player sees: survival first, then the goal, then feedback. Keep it off the play area and off the
player. Cover every state: title, playing, paused, game over and retry. Use stable sizes so a growing number
does not shift the layout, and check the longest values at width 390. Design it with topic "page-design": a game
menu is not a dashboard of stat cards.

## Prove it plays

A title screen in a screenshot proves nothing. Play it with `render_page`:

```json
{ "steps": [
  { "click": "#start", "wait": 300 },
  { "press": "ArrowRight", "wait": 300 },
  { "press": "ArrowLeft", "wait": 2500 }
] }
```

1. No JavaScript errors, and the canvas is not blank.
2. A screenshot of active play, not only the title, at the default width and at 390.
3. The main input changes the game. Show the score or state on screen so the screenshot proves it.
4. Lose on purpose and check the game over screen and the restart.
5. Say what you saw when you played it, and what you could not test (sound, the feel of touch).

## Starter

A complete small game, tested in the sandbox: title screen, keys and touch, fixed steps, hitstop, shake, sparks,
sound and restart. Take its structure, not its idea.

```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Meteor Run</title>
<style>
  html, body { margin: 0; height: 100%; background: #0e1726; color: #f4f7fb; font: 16px/1.4 system-ui, sans-serif; }
  #wrap { position: relative; height: 100dvh; overflow: hidden; touch-action: none; user-select: none; }
  canvas { display: block; width: 100%; height: 100%; }
  #hud { position: absolute; top: 12px; left: 16px; right: 16px; display: flex; justify-content: space-between; font-weight: 600; pointer-events: none; }
  #panel { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; gap: 12px; padding: 24px; text-align: center; background: #0e1726cc; }
  #panel[hidden] { display: none; }
  h1, p { margin: 0; }
  button { font: inherit; font-weight: 600; min-height: 48px; padding: 0 24px; border: 0; border-radius: 8px; background: #ffd166; color: #222; cursor: pointer; }
</style>
</head>
<body>
<div id="wrap">
  <canvas id="game"></canvas>
  <div id="hud"><span id="score">Score 0</span><span id="best">Best 0</span></div>
  <div id="panel">
    <h1 id="title">Meteor Run</h1>
    <p id="help">Arrow keys or drag to move. Dodge the rocks.</p>
    <button id="start">Start</button>
  </div>
</div>
<script>
const STEP = 1 / 60, SPEED = 430, SIZE = 14, START_GAP = 0.7, MIN_GAP = 0.18
const canvas = document.getElementById('game'), ctx = canvas.getContext('2d')
const $ = (id) => document.getElementById(id)
let W = 0, H = 0, state = 'title', best = 0, last = 0, acc = 0, audio = null
let seed = 1, x = 0, rocks = [], sparks = [], score = 0, gap = START_GAP, wait = 0, stop = 0, trauma = 0, time = 0, dragX = null
const keys = {}

function resize() {
  const r = canvas.getBoundingClientRect(), d = Math.min(devicePixelRatio, 2)
  canvas.width = r.width * d; canvas.height = r.height * d
  ctx.setTransform(d, 0, 0, d, 0, 0); W = r.width; H = r.height
}
new ResizeObserver(resize).observe(canvas); resize()

const rand = () => (seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296

function beep(freq, length = 0.1, type = 'square', volume = 0.05) {
  if (!audio) return
  const o = audio.createOscillator(), g = audio.createGain(), t = audio.currentTime
  o.type = type; o.frequency.value = freq * (0.94 + Math.random() * 0.12)
  g.gain.setValueAtTime(volume, t); g.gain.exponentialRampToValueAtTime(0.0001, t + length)
  o.connect(g).connect(audio.destination); o.start(); o.stop(t + length)
}

function show(title, help, label) { $('title').textContent = title; $('help').textContent = help; $('start').textContent = label; $('panel').hidden = false }

function start() {
  audio ??= new AudioContext(); audio.resume()
  if (state !== 'paused') { seed = (Date.now() >>> 0) || 1; x = W / 2; rocks = []; sparks = []; score = 0; gap = START_GAP; wait = 0; time = 0; trauma = 0; stop = 0 }
  state = 'playing'; $('panel').hidden = true; acc = 0
}
$('start').addEventListener('click', start)

addEventListener('keydown', (e) => {
  keys[e.key] = true
  if (e.key.startsWith('Arrow') || e.key === ' ') e.preventDefault()
  if (e.key === 'Enter' && state !== 'playing') start()
})
addEventListener('keyup', (e) => { keys[e.key] = false })
canvas.addEventListener('pointerdown', (e) => { dragX = e.offsetX })
canvas.addEventListener('pointermove', (e) => { if (dragX !== null) dragX = e.offsetX })
addEventListener('pointerup', () => { dragX = null })
document.addEventListener('visibilitychange', () => {
  if (document.hidden && state === 'playing') { state = 'paused'; show('Paused', 'Your run is waiting.', 'Resume') }
})

function burst(px, py, color, count) {
  for (let i = 0; i < count; i++) {
    const a = rand() * 6.283, v = 60 + rand() * 260
    sparks.push({ x: px, y: py, vx: Math.cos(a) * v, vy: Math.sin(a) * v, life: 0.5, color })
  }
}

function update(dt) {
  time += dt
  const dir = (keys.ArrowRight || keys.d ? 1 : 0) - (keys.ArrowLeft || keys.a ? 1 : 0)
  if (dragX !== null) x += Math.max(-1, Math.min(1, (dragX - x) / 24)) * SPEED * dt
  else x += dir * SPEED * dt
  x = Math.max(SIZE, Math.min(W - SIZE, x))
  wait -= dt
  if (wait <= 0) {
    rocks.push({ x: rand() * W, y: -30, r: 12 + rand() * 20, v: 170 + time * 7 + rand() * 90 })
    wait = gap; gap = Math.max(MIN_GAP, gap * 0.985)
  }
  const py = H - 60
  for (const r of rocks) {
    r.y += r.v * dt
    if (Math.hypot(r.x - x, r.y - py) < r.r + SIZE) return lose(py)
  }
  const before = rocks.length
  rocks = rocks.filter((r) => r.y < H + 40)
  if (rocks.length < before) { score += before - rocks.length; trauma = Math.min(1, trauma + 0.05); beep(660, 0.05, 'triangle', 0.03) }
  $('score').textContent = `Score ${score}`
}

function lose(py) {
  stop = 0.09; trauma = 0.7; burst(x, py, '#ff6b6b', 40); beep(110, 0.35, 'sawtooth', 0.09)
  best = Math.max(best, score); $('best').textContent = `Best ${best}`
  state = 'over'; setTimeout(() => show('Hit!', `You dodged ${score} rocks.`, 'Play again'), 500)
}

function draw() {
  const s = trauma * trauma * 14, sx = (Math.sin(time * 91) * s) | 0, sy = (Math.cos(time * 77) * s) | 0
  ctx.save(); ctx.clearRect(0, 0, W, H); ctx.translate(sx, sy)
  ctx.fillStyle = '#8fa3bf'
  for (const r of rocks) { ctx.beginPath(); ctx.arc(r.x, r.y, r.r, 0, 6.283); ctx.fill() }
  if (state !== 'over' && state !== 'title') { ctx.fillStyle = '#ffd166'; ctx.beginPath(); ctx.moveTo(x, H - 60 - SIZE * 1.4); ctx.lineTo(x - SIZE, H - 60 + SIZE); ctx.lineTo(x + SIZE, H - 60 + SIZE); ctx.fill() }
  for (const p of sparks) { ctx.globalAlpha = p.life * 2; ctx.fillStyle = p.color; ctx.fillRect(p.x, p.y, 4, 4) }
  ctx.restore()
}

function frame(t) {
  const real = Math.min((t - last) / 1000, 0.1); last = t
  if (state === 'playing') {
    if (stop > 0) stop -= real
    else { acc += real; while (acc >= STEP && state === 'playing') { update(STEP); acc -= STEP } }
  }
  trauma = Math.max(0, trauma - 1.4 * real)
  for (const p of sparks) { p.x += p.vx * real; p.y += p.vy * real; p.life -= real }
  sparks = sparks.filter((p) => p.life > 0)
  draw(); requestAnimationFrame(frame)
}
requestAnimationFrame(frame)
</script>
</body>
</html>
```

## Notices

These guides are adapted from open-source agent skills. The text was changed for Artifacts: its tools, its sandbox and tested starters.

**page-games.md** — from majidmanzarpour/threejs-game-skills, MIT License, Copyright (c) 2026 Majid Manzarpour.

MIT License text: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

## See it in use

- **Roles:** [AI for real estate agents](/roles/real-estate-agent)
- **Examples:** [24 pages agents made for a sample company](/examples)
