# Page: simulations

Page: simulations

**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 an Artifacts page that simulates queue times at the help desk as staffing changes.” 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-simulations`, 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-simulations` |

Read this with topic "pages". A simulation lets people change something and watch what follows: a pendulum, an
orbit, an epidemic, a supply chain, compound interest, traffic, a neural network learning. It teaches through
cause and effect, so it has to be right as well as beautiful.

## Start from the question

Write one sentence: "This shows that when you change [input], [result] happens because [reason]." Then choose:

- The few inputs people can change. Three good sliders beat twelve.
- What they watch: the moving picture, plus a chart or number that shows the result over time.
- The first state. Open with something already moving and worth seeing, never a blank canvas.

## The model

- Write the real equations or rules, and state them in a line on the page.
- **Units on everything:** show metres, seconds or people. Never a bare number.
- **Assumptions are visible:** say what it leaves out ("no friction", "mixed population").
- Use real values, and name their source when they come from the world. Never invent a constant that looks
  measured; mark an illustrative one as such.

## Time steps

- Separate the physics from the frames: run the model in small fixed steps with an accumulator, several per
  frame, and clamp the time since the last frame to 0.1 s.
- **Pick the integrator for the job:** semi-implicit Euler for games and particles, Runge-Kutta 4 for anything
  that must stay accurate: orbits, pendulums, chaos. Plain Euler gains energy and blows up.
- **Check it:** track something that must stay constant, such as total energy, and show the drift. If it drifts,
  shrink the step.
- For agents on a grid (epidemics, traffic, cellular automata), update from a copy of the state, so the order of
  update does not change the result.
- Seed the randomness, so the same settings give the same run, and offer a new seed.
- For rigid bodies that stack and collide, use Matter.js rather than writing collisions:
  `https://cdn.jsdelivr.net/npm/matter-js@0.20.0/build/matter.min.js`.

## Controls

- Every slider shows its value and unit, updates live and has a sensible range. Use `<label for>` and a real
  `<input type="range">`, so it works with the keyboard.
- Always have Play or Pause, and Reset. Add a speed control when the event is too fast or too slow to watch.
- Say what a change does: restart the run, or change it while it runs. Mixing the two confuses people.
- Offer two or three presets of interesting settings, named by what they show.

## Showing the result

- Draw on a `<canvas>` sized from its element, with the pixel ratio capped at 2.
- Keep a time chart beside the picture. Plain canvas handles a live line well. For a finished chart, use Chart.js:
  `https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js`.
- **Clean axes:** round tick labels ("9.6 s", never 9.5500000012), label both axes, and fix the range so a live
  chart does not jump.
- **Wrap with care:** an angle wrapped to ±π draws false vertical lines. Plot it unwrapped, or break the line at
  the wrap.
- Keep trails in a fixed-size array, and drop the oldest point instead of growing without end.

## Check it

1. Test a case you can work out by hand: a small swing keeps the known period, zero force means no motion.
2. Push every control to its limits: nothing goes blank, freezes or shows NaN.
3. `render_page` with steps: wait so it is moving, click Pause, click Reset, and check at width 390.
4. Run it for a while and confirm the drift check stays small.
5. Say what you verified and what the model leaves out.

Design it with topic "page-design".

## Starter

A double pendulum, tested in the sandbox: Runge-Kutta 4, live slider, pause, reset, a trail, a time chart and an
energy check.

```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Double pendulum</title>
<style>
  :root { color-scheme: light; }
  body { margin: 0 auto; max-width: 760px; padding: 16px; background: #f5f7f2; color: #1d2a24; font: 16px/1.5 system-ui, sans-serif; }
  h1 { margin: 0; font-size: 24px; }
  p { margin: 4px 0 12px; }
  canvas { display: block; width: 100%; background: #fff; border: 1px solid #cfd8cf; border-radius: 8px; }
  #swing { height: 340px; }
  #chart { height: 160px; margin-top: 12px; }
  .controls { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; margin: 12px 0; }
  .controls label { flex: 1 1 260px; }
  input[type=range] { width: 100%; }
  button { font: inherit; font-weight: 600; min-height: 44px; padding: 0 18px; border: 1px solid #1d2a24; border-radius: 8px; background: #fff; color: #1d2a24; cursor: pointer; }
</style>
</head>
<body>
<h1>Double pendulum</h1>
<p>Two arms of 1 m and two masses of 1 kg, with no friction. Change the start angle and watch tiny differences grow.</p>
<canvas id="swing"></canvas>
<div class="controls">
  <label for="angle">Start angle of the lower arm: <strong id="angleValue"></strong>
    <input id="angle" type="range" min="10" max="175" step="1" value="120">
  </label>
  <button id="toggle">Pause</button>
  <button id="reset">Reset</button>
</div>
<canvas id="chart"></canvas>
<p id="energy"></p>
<script>
const G = 9.81, L = 1, M = 1, H = 1 / 480, TRAIL = 600, CHART_SECONDS = 20
const $ = (id) => document.getElementById(id)
const swing = $('swing'), chart = $('chart')
let s, t, trail, history, energy0, running = true, last = 0, acc = 0

function fit(c) {
  const r = c.getBoundingClientRect(), d = Math.min(devicePixelRatio, 2)
  c.width = r.width * d; c.height = r.height * d
  c.getContext('2d').setTransform(d, 0, 0, d, 0, 0)
}
new ResizeObserver(() => { fit(swing); fit(chart) }).observe(document.body)

function deriv([a1, a2, w1, w2]) {
  const d = a1 - a2, den = 3 - Math.cos(2 * d)
  const b1 = (-3 * G * Math.sin(a1) - G * Math.sin(a1 - 2 * a2) - 2 * Math.sin(d) * (w2 * w2 * L + w1 * w1 * L * Math.cos(d))) / (L * den)
  const b2 = (2 * Math.sin(d) * (2 * w1 * w1 * L + 2 * G * Math.cos(a1) + w2 * w2 * L * Math.cos(d))) / (L * den)
  return [w1, w2, b1, b2]
}
function rk4(y, h) {
  const add = (a, b, k) => a.map((v, i) => v + b[i] * k)
  const k1 = deriv(y), k2 = deriv(add(y, k1, h / 2)), k3 = deriv(add(y, k2, h / 2)), k4 = deriv(add(y, k3, h))
  return y.map((v, i) => v + (h / 6) * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]))
}
function energy([a1, a2, w1, w2]) {
  const kinetic = 0.5 * M * L * L * (2 * w1 * w1 + w2 * w2 + 2 * w1 * w2 * Math.cos(a1 - a2))
  return kinetic - M * G * L * (2 * Math.cos(a1) + Math.cos(a2))
}
function reset() {
  const deg = +$('angle').value
  $('angleValue').textContent = `${deg}°`
  s = [Math.PI / 2, (deg * Math.PI) / 180, 0, 0]
  t = 0; trail = []; history = []; energy0 = energy(s); acc = 0
}
$('angle').addEventListener('input', reset)
$('reset').addEventListener('click', reset)
$('toggle').addEventListener('click', () => { running = !running; $('toggle').textContent = running ? 'Pause' : 'Play' })

function drawSwing() {
  const c = swing.getContext('2d'), w = swing.clientWidth, h = swing.clientHeight
  const cx = w / 2, cy = h / 2, u = Math.min(w, h) / 4.6
  const x1 = cx + Math.sin(s[0]) * u, y1 = cy + Math.cos(s[0]) * u
  const x2 = x1 + Math.sin(s[1]) * u, y2 = y1 + Math.cos(s[1]) * u
  trail.push([x2, y2]); if (trail.length > TRAIL) trail.shift()
  c.clearRect(0, 0, w, h)
  c.strokeStyle = '#d1495b'; c.lineWidth = 1.5; c.beginPath()
  trail.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.stroke()
  c.strokeStyle = '#1d2a24'; c.lineWidth = 3; c.beginPath(); c.moveTo(cx, cy); c.lineTo(x1, y1); c.lineTo(x2, y2); c.stroke()
  for (const [x, y, color] of [[x1, y1, '#2e6f95'], [x2, y2, '#d1495b']]) { c.fillStyle = color; c.beginPath(); c.arc(x, y, 10, 0, 6.283); c.fill() }
}
function drawChart() {
  const c = chart.getContext('2d'), w = chart.clientWidth, h = chart.clientHeight, left = 56, bottom = 24
  const from = Math.max(0, t - CHART_SECONDS), y = (v) => (h - bottom) / 2 - (v / 30) * ((h - bottom) / 2)
  c.clearRect(0, 0, w, h); c.fillStyle = '#54635b'; c.font = '12px system-ui'
  for (const v of [-30, 0, 30]) { c.fillText(`${v} rad`, 6, Math.min(h - bottom, Math.max(10, y(v) + 4))) }
  c.fillText(`${from.toFixed(0)} s`, left, h - 6); c.fillText(`${(from + CHART_SECONDS).toFixed(0)} s`, w - 36, h - 6)
  c.strokeStyle = '#cfd8cf'; c.beginPath(); c.moveTo(left, y(0)); c.lineTo(w, y(0)); c.stroke()
  c.strokeStyle = '#d1495b'; c.lineWidth = 1.5; c.beginPath()
  history.forEach(([time, a], i) => {
    const px = left + ((time - from) / CHART_SECONDS) * (w - left)
    if (px >= left) (i ? c.lineTo(px, y(a)) : c.moveTo(px, y(a)))
  })
  c.stroke()
}
function frame(now) {
  const real = Math.min((now - last) / 1000, 0.1); last = now
  if (running) {
    acc += real
    while (acc >= H) { s = rk4(s, H); t += H; acc -= H }
    history.push([t, s[1]]); if (history.length > 2400) history.shift()
  }
  drawSwing(); drawChart()
  $('energy').textContent = `Time ${t.toFixed(1)} s. Energy drift ${Math.abs(energy(s) - energy0).toExponential(1)} J (should stay near zero).`
  requestAnimationFrame(frame)
}
fit(swing); fit(chart); reset(); requestAnimationFrame(frame)
</script>
</body>
</html>
```

## See it in use

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