nvidia/nemotron-3.5-super-vl:free run

OpenRouter · OpenCode 2.2.7 · every run of this model · uwu · 2026-11-14

Race this run

Run nvidia/nemotron-3.5-super-vl:free on your computer to see the two side by side.

A full run: 50 tasks, 82 points

Score
12,419 Diamond Speed times the share of points, times 100. How scores work136 tok/s × 91.5% of points
  1. Bronze0
  2. Silver1,500
  3. Gold3,000
  4. Platinum6,000
  5. Diamond10,000

Not on the leaderboard: it ran through a hosted service, so it is not on a computer board. Leaderboard

Tasks passed
47/50
Points
75/82Harder tasks count 3. How scores work
Tokens
204,88532,541 read, 172,344 written.
Speed
136 tok/sTokens a second, as the runner measured it. The site checks only that the machine could reach it. How speeds are checked

nvidia/nemotron-3.5-super-vl:free through OpenRouter passed 47 of 50 tasks in 205k tokens at 136 tok/s, a Diamond score of 12,419, in the resyn benchmark. https://resyn.cloud/suite/c08b6181c6a9015c6e814d604795ca1bCompare another runComment

Run details
Model file
Not a listed file
Where it ran
OpenRouter
How
Run through the model's API, by OpenCode benchmark agent (OpenCode via Resyn runner)
Time
21 min 9 s
Suite
resyn-tasks@6
Flag this run

Hides the run from public pages until an admin checks it.

Failed 3

  • A pricing table with a toggleFailed

    7,270 tokens: 220 read, 7,050 written · 1 min 1 s · 115 tok/s

    Build a pricing page with three plans, in this order: Solo at $9 a month or $90 a year, Business at $40 a month or $400 a year and Premium at $45 a month or $450 a year. Each plan is an element with class "plan" containing an element with class "price". Show the monthly prices first, and write the words monthly and yearly as text in the markup, not as CSS content. Add a <button id="billing-toggle"> that switches every price between monthly and yearly billing when clicked. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pricing</title>
    <style>
      body {
        font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        line-height: 1.5;
        color: #111;
        padding: 2rem;
        max-width: 800px;
        margin: 0 auto;
      }
      .plans {
        display: flex;
        gap: 1rem;
        flex-wrap: wrap;
        justify-content: center;
        margin-top: 1rem;
      }
      .plan {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 1.5rem;
        width: 220px;
        text-align: center;
        background: #fff;
      }
      .plan h2 {
        margin: 0 0 1rem;
        font-size: 1.25rem;
      }
      .price {
        margin: 1rem 0;
        font-size: 1.75rem;
      }
      .price-item {
        margin: 0 0.25rem;
      }
      .price-item.active {
        color: #000;
        font-weight: 700;
      }
      .price-item.inactive {
        color: #888;
        font-weight: 400;
      }
      button#billing-toggle {
        padding: 0.6rem 1.2rem;
        font-size: 1rem;
        cursor: pointer;
        margin-bottom: 1rem;
      }
    </style>
    </head>
    <body>
    <button id="billing-toggle">Switch to Yearly</button>
    <div class="plans">
      <div class="plan">
        <h2>Solo</h2>
        <div class="price">
          <span class="price-item monthly active" data-billing="monthly">$9 <span>monthly</span></span>
          <span class="price-item yearly inactive" data-billing="yearly">$90 <span>yearly</span></span>
        </div>
      </div>
      <div class="plan">
        <h2>Business</h2>
        <div class="price">
          <span class="price-item monthly active" data-billing="monthly">$40 <span>monthly</span></span>
          <span class="price-item yearly inactive" data-billing="yearly">$400 <span>yearly</span></span>
        </div>
      </div>
      <div class="plan">
        <h2>Premium</h2>
        <div class="price">
          <span class="price-item monthly active" data-billing="monthly">$45 <span>monthly</span></span>
          <span class="price-item yearly inactive" data-billing="yearly">$450 <span>yearly</span></span>
        </div>
      </div>
    </div>
    <script>
      const toggle = document.getElementById('billing-toggle');
      let yearly = false;
    
      toggle.addEventListener('click', function () {
        yearly = !yearly;
    
        document.querySelectorAll('.price-item').forEach(function (item) {
          const isYearly = item.getAttribute('data-billing') === 'yearly';
          const show = yearly ? isYearly : !isYearly;
          item.classList.toggle('active', show);
          item.classList.toggle('inactive', !show);
        });
    
        toggle.textContent = yearly ? 'Switch to Monthly' : 'Switch to Yearly';
      });
    </script>
    </body>
    </html>
  • Build SnakeFailed

    9,298 tokens: 458 read, 8,840 written · 1 min 17 s · 115 tok/s

    Build Snake as one web page on a 10 by 10 grid, playable with the arrow keys (one key press, one step), with the grid drawn on the page.
    
    In <script id="game">, define createGame() returning an object with step(dir) and state(). dir is "up", "down", "left" or "right". state() returns {snake, food, score, over}: snake is a list of [x, y] cells, head first; food is [x, y]; score is a number; over is a boolean. x is the column (0 to 9, left to right), y the row (0 to 9, top to bottom); up is y - 1.
    
    The rules, exactly:
    1. The game starts with snake [[6, 4], [7, 4], [8, 4]], moving left, food at [7, 9], score 0.
    2. step(dir): if dir is the opposite of the current direction it is ignored and the snake keeps going; otherwise dir becomes the current direction. The head moves one cell that way.
    3. If the new head cell holds the food, the snake grows: its tail stays. Otherwise the tail cell is freed first.
    4. If the new head is off the grid or on a cell of the snake (after rule 3), the game is over: over becomes true and nothing else changes. Once over, step does nothing.
    5. Eating adds 1 to the score, and the next food goes to the first empty cell in reading order (row by row from the top, left to right) after the new head's cell, wrapping from [9, 9] to [0, 0].
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snake 10x10</title>
    <style>
      body { font-family: system-ui, sans-serif; padding: 20px; }
      #grid {
        display: grid;
        grid-template-columns: repeat(10, 22px);
        grid-template-rows: repeat(10, 22px);
        border: 3px solid #222;
        margin-bottom: 8px;
        user-select: none;
      }
      .cell {
        width: 22px;
        height: 22px;
        border: 1px solid #999;
        box-sizing: border-box;
      }
      .snake { background-color: #0b6; }
      .head { background-color: #0d4; border: 2px solid #042; box-sizing: border-box; }
      .food { background-color: #e41; }
      #message { margin-top: 8px; font-weight: bold; color: #a00; height: 1.2em; }
      #score { font-size: 1.2em; margin-bottom: 8px; }
    </style>
    </head>
    <body>
    <div id="score">Score: 0</div>
    <div id="grid"></div>
    <div id="message"></div>
    
    <script id="game">
    function createGame() {
      var width = 10;
      var height = 10;
      var snake = [[6, 4], [7, 4], [8, 4]];
      var food = [7, 9];
      var score = 0;
      var over = false;
      var dir = "left";
    
      var opposite = {
        up: "down",
        down: "up",
        left: "right",
        right: "left"
      };
    
      function step(nextDir) {
        if (over) {
          return;
        }
    
        if (nextDir !== opposite[dir]) {
          dir = nextDir;
        }
    
        var head = snake[0];
        var newHead;
        if (dir === "up") {
          newHead = [head[0], head[1] - 1];
        } else if (dir === "down") {
          newHead = [head[0], head[1] + 1];
        } else if (dir === "left") {
          newHead = [head[0] - 1, head[1]];
        } else {
          newHead = [head[0] + 1, head[1]];
        }
    
        if (newHead[0] < 0 || newHead[0] >= width || newHead[1] < 0 || newHead[1] >= height) {
          over = true;
          return;
        }
    
        var ate = (newHead[0] === food[0] && newHead[1] === food[1]);
    
        var newSnake;
        if (ate) {
          newSnake = [newHead].concat(snake);
        } else {
          newSnake = [newHead].concat(snake.slice(0, snake.length - 1));
        }
    
        for (var i = 1; i < newSnake.length; i++) {
          if (newSnake[i][0] === newHead[0] && newSnake[i][1] === newHead[1]) {
            over = true;
            return;
          }
        }
    
        snake = newSnake;
    
        if (ate) {
          score += 1;
          food = placeFood(newHead, snake);
        }
      }
    
      function placeFood(head, currentSnake) {
        var start = head[1] * width + head[0] + 1;
        var total = width * height;
        for (var i = 0; i < total; i++) {
          var idx = (start + i) % total;
          var x = idx % width;
          var y = Math.floor(idx / width);
          var occupied = false;
          for (var j = 0; j < currentSnake.length; j++) {
            if (currentSnake[j][0] === x && currentSnake[j][1] === y) {
              occupied = true;
              break;
            }
          }
          if (!occupied) {
            return [x, y];
          }
        }
        return food;
      }
    
      function state() {
        return {
          snake: snake.map(function (cell) { return [cell[0], cell[1]]; }),
          food: [food[0], food[1]],
          score: score,
          over: over
        };
      }
    
      return {
        step: step,
        state: state
      };
    }
    </script>
    <script>
    (function () {
      var game = createGame();
    
      var scoreEl = document.getElementById('score');
      var gridEl = document.getElementById('grid');
      var msgEl = document.getElementById('message');
    
      var cells = [];
      for (var y = 0; y < 10; y++) {
        for (var x = 0; x < 10; x++) {
          var cell = document.createElement('div');
          cell.className = 'cell';
          cell.dataset.x = x;
          cell.dataset.y = y;
          gridEl.appendChild(cell);
          cells.push(cell);
        }
      }
    
      function cellAt(x, y) {
        return cells[y * 10 + x];
      }
    
      function render() {
        var s = game.state();
    
        cells.forEach(function (c) {
          c.className = 'cell';
        });
    
        s.snake.forEach(function (part, i) {
          var c = cellAt(part[0], part[1]);
          c.classList.add('snake');
          if (i === 0) {
            c.classList.add('head');
          }
        });
    
        var fc = cellAt(s.food[0], s.food[1]);
        fc.classList.add('food');
    
        scoreEl.textContent = 'Score: ' + s.score;
        msgEl.textContent = s.over ? 'GAME OVER' : '';
      }
    
      document.addEventListener('keydown', function (e) {
        var dir;
        switch (e.key) {
          case 'ArrowUp': dir = 'up'; break;
          case 'ArrowDown': dir = 'down'; break;
          case 'ArrowLeft': dir = 'left'; break;
          case 'ArrowRight': dir = 'right'; break;
          default: return;
        }
        e.preventDefault();
        game.step(dir);
        render();
      });
    
      render();
    })();
    </script>
    </body>
    </html>
  • Step sequencerFailed

    19,251 tokens: 1,322 read, 17,929 written · 1 min 53 s · 159 tok/s

    Build a web page called "Step sequencer": three rows labelled Kick, Snare and Hat, of 16 step buttons each, a Play button and a Stop button, and drums made with the Web Audio API, with no sound files.
    
    In <script id="game">, define createGame() returning an object with press(cmd) and state(). The page calls createGame() at load or on the first press. The logic keeps the pattern, whether it is playing, the playhead and the hits. The page makes the sound. Do not use eval or Function, and never run text as code: give a timer a function, not a string.
    
    The starting pattern, one row per track. Steps are numbered from 1 in the rows below: each row is 16 characters, 1 for on and 0 for off. The first character is step 1 on the page and step 0 for press():
    kick   1000100010001000
    snare  0000100100001001
    hat    1010101010101110
    
    The rules, exactly:
    1. At the start, playing is false, playhead is 0 and hits is [].
    2. press([track, step]) toggles one cell: track 0 is kick, 1 snare, 2 hat; step is 0 to 15, where 0 is the first step. Toggling changes the pattern and nothing else.
    3. press('play') does nothing when playing is already true. Otherwise it sets playing to true, and hits becomes the list of track numbers (0 kick, 1 snare, 2 hat) whose cell at the playhead is 1, in ascending order ([] when there are none). So the step under the playhead sounds as play starts.
    4. press('stop') sets playing to false, playhead to 0 and hits to [].
    5. press('tick') does nothing unless playing is true. When it is, playhead goes on by one, and after 15 it goes back to 0. hits becomes the list of track numbers whose cell at the new playhead is 1, in ascending order ([] when there are none).
    6. Any other cmd does nothing: a list that is not exactly two whole numbers (such as [0, 1, 2], [1], [] or [true, 0]), null, a number, true or false, a word other than play, stop or tick, and a track or step outside the ranges above.
    Track and step are whole numbers.
    
    state() returns {playing, playhead, hits, pattern}: playing is true or false; playhead is 0 to 15; hits lists the track numbers set by the last tick or by the play that started playback, in ascending order ([] at the start and after stop); pattern is three strings of 16 characters, kick first, each character 1 or 0.
    
    The page:
    - Each step button is a real button with the attributes data-track (0, 1 or 2) and data-step (0 to 15), and aria-pressed set to true or false to match its state. A click calls press([track, step]), and after every press, the page draws from state().
    - A step that is on has the class on, and the stylesheet fills it dark; a step that is off has no class on.
    - Play has the id play and Stop the id stop. Play calls press('play') and starts one timer that calls press('tick') every 125 ms: 120 quarter-note beats a minute, four steps to a beat. Stop calls press('stop') and clears the timer. Each play and each tick sounds the hits that state() then reports, and nothing else sounds.
    - Play has the disabled attribute while playing, and Stop has it while stopped.
    - A status line with the id status reads "Stopped", or "Playing, step N of 16" with N the playhead plus 1. Give it a fixed height, so the grid does not move when its text changes.
    - A span with the id announce, set to aria-live polite, is empty until playback starts for the first time. From then on it says "Playing" when playback starts and "Stopped" when it stops, and changes at no other time.
    - The cells in the playhead column have the class playhead while playing, and no cell has it while stopped.
    - The numbers 1 to 16, as text, sit above the grid, and the playhead's number is pink. Under 720 px each step shows its number.
    - When the page becomes hidden, it presses Stop, so nothing sounds in a background tab.
    - Each track in hits plays its drum: kick is a falling sine tone, snare a short noise burst with a low body tone, hat a short high noise burst. Tones use oscillators; noise bursts use buffer sources playing a buffer of random samples: the kick is one oscillator, the snare one buffer source and one oscillator, the hat one buffer source. Hits that land together must not clip, so put a gain or a limiter before the output. Create the AudioContext inside the first click (browsers need a click before they make sound), and resume it if it is suspended.
    - Flat and plain: a light background, dark ink, no shadows or gradients, Play the one pink button (#b31f57), and the playhead cell outlined in pink where you are. At 1280 px the 16 steps sit in one row; under 720 px they form two bars of 8. The page never scrolls sideways.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and drives the sequencer through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Step sequencer</title>
    <style>
    * { box-sizing: border-box; }
    body {
      margin: 0;
      padding: 16px;
      background: #f5f5f5;
      color: #111;
      font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
      overflow-x: hidden;
    }
    h1 { margin: 0 0 12px; font-size: 1.25rem; }
    #controls {
      display: flex;
      gap: 8px;
      align-items: center;
      flex-wrap: wrap;
      margin-bottom: 12px;
    }
    button {
      border: 1px solid #111;
      background: #fff;
      color: #111;
      padding: 6px 14px;
      font-size: 1rem;
      cursor: pointer;
    }
    button:disabled { opacity: 0.5; cursor: not-allowed; }
    #play {
      background: #b31f57;
      color: #fff;
      border-color: #b31f57;
    }
    #play:disabled { opacity: 0.7; }
    #status {
      margin-left: auto;
      min-width: 210px;
      height: 1.2em;
      font-weight: 600;
    }
    #announce { margin-left: 10px; }
    #sequencer { max-width: 960px; margin: 0 auto; }
    #number-bar {
      display: grid;
      grid-template-columns: repeat(16, 1fr);
      gap: 4px;
      margin-bottom: 6px;
    }
    #number-bar span {
      text-align: center;
      font-size: 0.8rem;
    }
    #number-bar span.current { color: #b31f57; font-weight: bold; }
    .track {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
    }
    .track-label {
      width: 52px;
      text-align: right;
      font-size: 0.9rem;
      flex-shrink: 0;
    }
    .steps {
      display: grid;
      grid-template-columns: repeat(16, 1fr);
      gap: 4px;
      flex: 1;
    }
    .steps button {
      height: 44px;
      border: 1px solid #111;
      background: #ddd;
      padding: 0;
      font-size: 0;
      cursor: pointer;
    }
    .steps button.on { background: #333; }
    .steps button.playhead { outline: 3px solid #b31f57; }
    @media (max-width: 719px) {
      #number-bar { display: none; }
      .steps { grid-template-columns: repeat(8, 1fr); }
      .steps button { font-size: 0.7rem; }
    }
    </style>
    </head>
    <body>
    <h1>Step sequencer</h1>
    <div id="controls">
      <button id="play">Play</button>
      <button id="stop">Stop</button>
      <div id="status">Stopped</div>
      <span id="announce" aria-live="polite"></span>
    </div>
    <div id="sequencer">
      <div id="number-bar"></div>
      <div id="grid"></div>
    </div>
    
    <script id="game">
    function createGame() {
      const pattern = [
        '1000100010001000'.split('').map(Number),
        '0000100100001001'.split('').map(Number),
        '1010101010101110'.split('').map(Number)
      ];
      let playing = false;
      let playhead = 0;
      let hits = [];
    
      function hitsAt(head) {
        const out = [];
        for (let t = 0; t < 3; t++) {
          if (pattern[t][head] === 1) out.push(t);
        }
        return out;
      }
    
      return {
        press(cmd) {
          if (Array.isArray(cmd) && cmd.length === 2) {
            const track = cmd[0];
            const step = cmd[1];
            if (
              Number.isInteger(track) && Number.isInteger(step) &&
              track >= 0 && track <= 2 &&
              step >= 0 && step <= 15
            ) {
              pattern[track][step] = pattern[track][step] === 1 ? 0 : 1;
            }
            return;
          }
          if (cmd === 'play') {
            if (playing) return;
            playing = true;
            hits = hitsAt(playhead);
            return;
          }
          if (cmd === 'stop') {
            playing = false;
            playhead = 0;
            hits = [];
            return;
          }
          if (cmd === 'tick') {
            if (!playing) return;
            playhead = (playhead + 1) % 16;
            hits = hitsAt(playhead);
            return;
          }
        },
        state() {
          return {
            playing,
            playhead,
            hits: hits.slice(),
            pattern: pattern.map(row => row.join(''))
          };
        }
      };
    }
    </script>
    
    <script>
    (function() {
      const tracks = ['Kick', 'Snare', 'Hat'];
      const grid = document.getElementById('grid');
      const numberBar = document.getElementById('number-bar');
    
      for (let i = 0; i < 16; i++) {
        const span = document.createElement('span');
        span.dataset.step = i;
        span.textContent = i + 1;
        numberBar.appendChild(span);
      }
    
      for (let t = 0; t < 3; t++) {
        const track = document.createElement('div');
        track.className = 'track';
        const label = document.createElement('div');
        label.className = 'track-label';
        label.textContent = tracks[t];
        const steps = document.createElement('div');
        steps.className = 'steps';
        for (let s = 0; s < 16; s++) {
          const btn = document.createElement('button');
          btn.type = 'button';
          btn.dataset.track = t;
          btn.dataset.step = s;
          btn.textContent = s + 1;
          btn.setAttribute('aria-pressed', 'false');
          steps.appendChild(btn);
        }
        track.appendChild(label);
        track.appendChild(steps);
        grid.appendChild(track);
      }
    
      let game = null;
      let timer = null;
      let started = false;
      let ctx = null;
      let master = null;
      let noiseHat = null;
      let noiseSnare = null;
    
      function ensureGame() {
        if (!game) game = createGame();
      }
    
      function ensureAudio() {
        if (ctx) return ctx;
        const Ctor = window.AudioContext || window.webkitAudioContext;
        if (!Ctor) return null;
        ctx = new Ctor();
        if (ctx.state === 'suspended') ctx.resume();
        master = ctx.createGain();
        master.gain.value = 0.4;
        master.connect(ctx.destination);
    
        const hatLen = Math.ceil(ctx.sampleRate * 0.05);
        noiseHat = ctx.createBuffer(1, hatLen, ctx.sampleRate);
        {
          const d = noiseHat.getChannelData(0);
          for (let i = 0; i < hatLen; i++) d[i] = Math.random() * 2 - 1;
        }
        const snareLen = Math.ceil(ctx.sampleRate * 0.1);
        noiseSnare = ctx.createBuffer(1, snareLen, ctx.sampleRate);
        {
          const d = noiseSnare.getChannelData(0);
          for (let i = 0; i < snareLen; i++) d[i] = Math.random() * 2 - 1;
        }
        return ctx;
      }
    
      function playKick(now) {
        const osc = ctx.createOscillator();
        const g = ctx.createGain();
        osc.type = 'sine';
        osc.frequency.setValueAtTime(150, now);
        osc.frequency.exponentialRampToValueAtTime(30, now + 0.2);
        g.gain.setValueAtTime(0.6, now);
        g.gain.exponentialRampToValueAtTime(0.001, now + 0.2);
        osc.connect(g);
        g.connect(master);
        osc.start(now);
        osc.stop(now + 0.2);
      }
    
      function playSnare(now) {
        const noise = ctx.createBufferSource();
        noise.buffer = noiseSnare;
        const g = ctx.createGain();
        g.gain.setValueAtTime(0.4, now);
        g.gain.exponentialRampToValueAtTime(0.001, now + 0.1);
        noise.connect(g);
        g.connect(master);
        noise.start(now);
        noise.stop(now + 0.1);
    
        const osc = ctx.createOscillator();
        const og = ctx.createGain();
        osc.type = 'sine';
        osc.frequency.setValueAtTime(120, now);
        osc.frequency.exponentialRampToValueAtTime(50, now + 0.15);
        og.gain.setValueAtTime(0.4, now);
        og.gain.exponentialRampToValueAtTime(0.001, now + 0.15);
        osc.connect(og);
        og.connect(master);
        osc.start(now);
        osc.stop(now + 0.15);
      }
    
      function playHat(now) {
        const noise = ctx.createBufferSource();
        noise.buffer = noiseHat;
        const g = ctx.createGain();
        g.gain.setValueAtTime(0.3, now);
        g.gain.exponentialRampToValueAtTime(0.001, now + 0.05);
        noise.connect(g);
        g.connect(master);
        noise.start(now);
        noise.stop(now + 0.05);
      }
    
      function playDrum(track) {
        if (!ctx) ensureAudio();
        if (!ctx) return;
        const now = ctx.currentTime;
        if (track === 0) playKick(now);
        else if (track === 1) playSnare(now);
        else if (track === 2) playHat(now);
      }
    
      function soundHits(hits) {
        hits.forEach(t => playDrum(t));
      }
    
      function draw() {
        const s = game.state();
        document.querySelectorAll('.steps button').forEach(btn => {
          const t = +btn.dataset.track;
          const st = +btn.dataset.step;
          const on = s.pattern[t][st] === '1';
          btn.classList.toggle('on', on);
          btn.setAttribute('aria-pressed', on ? 'true' : 'false');
          btn.classList.toggle('playhead', s.playing && st === s.playhead);
        });
        document.querySelectorAll('#number-bar span').forEach(span => {
          const st = +span.dataset.step;
          span.classList.toggle('current', s.playing && st === s.playhead);
        });
        document.getElementById('status').textContent = s.playing
          ? 'Playing, step ' + (s.playhead + 1) + ' of 16'
          : 'Stopped';
        document.getElementById('play').disabled = s.playing;
        document.getElementById('stop').disabled = !s.playing;
      }
    
      document.getElementById('play').addEventListener('click', function() {
        ensureAudio();
        ensureGame();
        game.press('play');
        const s = game.state();
        soundHits(s.hits);
        draw();
        if (!timer) {
          timer = setInterval(function() {
            game.press('tick');
            const s2 = game.state();
            soundHits(s2.hits);
            draw();
          }, 125);
        }
        if (!started) {
          started = true;
          document.getElementById('announce').textContent = 'Playing';
        }
      });
    
      document.getElementById('stop').addEventListener('click', function() {
        ensureGame();
        game.press('stop');
        if (timer) {
          clearInterval(timer);
          timer = null;
        }
        draw();
        document.getElementById('announce').textContent = 'Stopped';
      });
    
      document.querySelectorAll('.steps button').forEach(function(btn) {
        btn.addEventListener('click', function() {
          ensureAudio();
          ensureGame();
          const t = +btn.dataset.track;
          const s = +btn.dataset.step;
          game.press([t, s]);
          draw();
        });
      });
    
      document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
          ensureGame();
          game.press('stop');
          if (timer) {
            clearInterval(timer);
            timer = null;
          }
          draw();
          document.getElementById('announce').textContent = 'Stopped';
        }
      });
    
      ensureGame();
      draw();
    })();
    </script>
    </body>
    </html>

Reasons are shown for the fixed tasks. The varied tasks keep their checks private so answers cannot be fitted to them.

Think a grade is wrong? Say so in the chat.

What it built

Pages and games, as the model wrote them, each in a sandbox. Open one, then swipe or use the arrow keys.

Scored tasks

Summarizing 5 of 5
  • One-sentence summaryPassed

    1,210 tokens: 115 read, 1,095 written · 9 s · 125 tok/s

    Summarize this in one sentence of at most 30 words.
    
    Starting March 24, the Penrith Hill Public Library will open at 6:35 a.m. instead of 11:15 a.m. on weekdays. The change follows a survey in which 57% of respondents asked for earlier hours. Weekend hours stay the same. The library will hire two part-time staff to cover the extra time, paid for by a county grant.
    Starting March 24, Penrith Hill Public Library opens weekdays at 6:35 a.m. after 57% surveyed requested earlier hours, hiring two part-time staff with a county grant; weekends unchanged.
  • Meeting notes in three bulletsPassed

    658 tokens: 190 read, 468 written · 5 s · 102 tok/s

    Summarize these meeting notes as exactly three bullet points, each at most 20 words. Keep only the decisions and ownership changes that matter. Output only the bullet points.
    
    Weekly sync, design team. Present: Hugo, Jules, Cal, Oscar.
    - Cal reported that the payment provider fixed the export bug; no action needed.
    - The launch date moves from March 4 to March 8 because the legal review is taking longer.
    - Oscar showed the new onboarding screens. Everyone liked them. Small copy changes only.
    - The marketing budget of $25,000 was approved by finance on Monday.
    - Hugo will own end-to-end testing from now on; Jules hands over the test plan by Wednesday.
    - Next sync is moved to Sunday at 14:30.
    - Coffee machine on floor 4 is broken again.
    • Launch moves to March 8 due to legal review delays.
    • Marketing budget of $25,000 approved by finance.
    • Hugo owns end-to-end testing; Jules hands over test plan by Wednesday.
  • Review sentiment and complaintPassed

    687 tokens: 125 read, 562 written · 5 s · 111 tok/s

    Read this product review and answer in exactly this format:
    Sentiment: <positive, negative or mixed>
    Complaint: <the main complaint in a few words>
    
    I've used this keyboard every day for a month. Honestly, the keys feel crisp and quiet and typing on it is a pleasure. But the wrist rest that came in the box wore through in a month, and support took 10 days to reply. I bought a replacement wrist rest myself. Would I buy it again? Probably, but I'm annoyed.
    Sentiment: mixed
    Complaint: Wrist rest wore through quickly
  • Faithful summary of a studyPassed

    682 tokens: 140 read, 542 written · 4 s · 147 tok/s

    Summarize this in at most 50 words. Keep the key numbers. Do not add anything the text does not say.
    
    In a randomized trial, 350 adults with chronic migraine took either Calmex or a placebo for 24 weeks. Those on Calmex had 2.9 fewer headache days per month on average, compared with 1.0 fewer days for placebo. Dry mouth was the most common side effect, reported by 6% of the drug group. The authors note the trial lasted only 24 weeks and call for longer studies before any recommendation is made.
    In a 24-week randomized trial of 350 adults with chronic migraine, Calmex reduced headache days by 2.9 per month versus 1.0 for placebo. Dry mouth affected 6% of the drug group. Authors call for longer studies before recommending it.
  • Action items from an email threadPassed

    656 tokens: 222 read, 434 written · 5 s · 93.8 tok/s

    List every action item in this email thread that someone has committed to do, as lines of the form "- <owner>: <action>". Leave out offers that were declined and things that turned out not to be needed. Output only the list.
    
    From: Cal
    Hi all, quick recap of what's still open for the June offsite. I'll send the revised contract to the hotel by Tuesday.
    
    From: Amara
    I can book the venue for the dinner if that helps?
    
    From: Lucas
    Thanks Amara, but I'll book the venue myself since I already spoke to them. Also, no need to change the logo on the badges, it's fine as is.
    
    From: Diego
    I'll update the budget sheet with the new hotel price tonight.
    
    From: Cal
    Great. Oh, and I'll email the caterer about the vegetarian options. Amara, could you just double-check the date on the invitations? Actually never mind, I checked them this morning, they're correct.
    
    - Cal: send the revised contract to the hotel by Tuesday
    - Lucas: book the venue for the dinner
    - Diego: update the budget sheet with the new hotel price tonight
    - Cal: email the caterer about the vegetarian options
Extracting 5 of 5
  • Fields from an email as JSONPassed

    379 tokens: 124 read, 255 written · 2 s · 128 tok/s

    Extract these fields from the email as a JSON object with exactly these keys: "name" (the sender's full name), "company", "meeting_date" (YYYY-MM-DD) and "attendees" (a number). Output only the JSON.
    
    Hello! This is Rafael Moreau from Larkspur Books. We'd love to visit your workshop. Could we meet on the 15th of November 2026, any time after lunch? We'll be three people in total, including me. Best, Rafael
    {"name": "Rafael Moreau", "company": "Larkspur Books", "meeting_date": "2026-11-15", "attendees": 3}
  • Every email address, oncePassed

    684 tokens: 159 read, 525 written · 4 s · 141 tok/s

    List every email address written out in full in this text (like name@example.com), one per line, in the order they first appear, without duplicates. Leave out any inbox the text says is closed. Output only the addresses.
    
    Contacts for the conference: write to hello@northfield-expo.net for general questions, or to talks@northfield-expo.net if you are presenting. Our designer (kofi.r@north-arc.io) made the poster. Billing questions: accounts@northfield-expo.net. Again, presenters use talks@northfield-expo.net. Please don't write to jo at northfield dot net, that inbox is closed.
    hello@northfield-expo.net
    talks@northfield-expo.net
    kofi.r@north-arc.io
    accounts@northfield-expo.net
  • A list as CSVPassed

    782 tokens: 113 read, 669 written · 5 s · 125 tok/s

    Convert this shopping list to CSV with the header row item,qty,price. Write prices as plain numbers without a currency sign. Output only the CSV.
    
    Bananas - 16 @ $7.25
    Eggs - 16 @ $2.30
    Lentils (500 g) - 11 @ $6.95
    Cheddar (200 g) - 18 @ $6.45
    item,qty,price
    Bananas,16,7.25
    Eggs,16,2.30
    Lentils (500 g),11,6.95
    Cheddar (200 g),18,6.45
  • The real deadlinePassed

    191 tokens: 105 read, 86 written · 1 s · 81.1 tok/s

    What is the final submission deadline? Answer with the date only, in YYYY-MM-DD format.
    
    The call for papers opened on 6 January 2026. Drafts were originally due June 25, but the committee extended the final submission deadline to 7 July 2026. Reviews are due by 7 July, and results will be announced on August 28, 2026.
    2026-07-07
  • Warnings and errors from a logPassed

    1,109 tokens: 287 read, 822 written · 5 s · 167 tok/s

    From this log, return a JSON array with one object per WARN or ERROR line, in order, each with the keys "time" (HH:MM:SS), "level" and "message". Output only the JSON.
    
    2025-08-05 09:13:53 INFO  server started on port 8080
    2025-08-05 09:18:42 WARN  config key "retries" is deprecated
    2025-08-05 09:19:42 INFO  user bea logged in
    2025-08-05 09:21:29 ERROR database connection lost
    2025-08-05 09:24:31 INFO  retrying in 30s
    2025-08-05 09:25:56 INFO  database reconnected
    2025-08-05 09:27:06 DEBUG cache hit ratio 0.89
    2025-08-05 09:31:12 ERROR payment webhook returned 504
    [
      {
        "time": "09:18:42",
        "level": "WARN",
        "message": "config key \"retries\" is deprecated"
      },
      {
        "time": "09:21:29",
        "level": "ERROR",
        "message": "database connection lost"
      },
      {
        "time": "09:31:12",
        "level": "ERROR",
        "message": "payment webhook returned 504"
      }
    ]
Following instructions 5 of 5
  • Exactly one wordPassed

    87 tokens: 26 read, 61 written · 1 s · 74.9 tok/s

    Reply with exactly the word Saved and nothing else.
    Saved
  • Three lowercase linesPassed

    833 tokens: 96 read, 737 written · 6 s · 122 tok/s

    Write exactly three lines about a desert. Use the word desert in every line. Start every line with the letter q, and do not use any of these words: tundra, museum, castle, autumn, station, prairie, bay, barn, harbour or glacier. Every line must be entirely lowercase, and the third line must end with a question mark. Output only the three lines.
    q desert sands stretch under a blazing sun, whispering ancient heat.  
    q night falls over the desert, stars dust the sky like scattered salt.  
    q can you hear the silence of the desert echoing across the dunes?
  • Exact JSON shapePassed

    263 tokens: 68 read, 195 written · 2 s · 125 tok/s

    Return a JSON object with exactly two keys: "words", a list of exactly 2 different lowercase words that each start with the letter y and use only the plain letters a to z, and "count", the number 2. Output only the JSON.
    {"words": ["yellow", "yacht"], "count": 2}
  • Sort a listPassed

    310 tokens: 52 read, 258 written · 2 s · 107 tok/s

    Sort these words alphabetically, ignoring case. Output only the sorted words, on one line separated by commas: guava, carrot, Bean, spinach, olive.
    Bean, carrot, guava, olive, spinach
  • A name with three rulesPassed

    1,303 tokens: 78 read, 1,225 written · 9 s · 135 tok/s

    Suggest a product name for a solar-powered heater. Rules: exactly two words, both capitalized, using only the plain letters A to Z, the first word starts with the letter R, the second word starts with the letter S, and the letter o must not appear anywhere. Output only the name.
    Radiant Sun
Reasoning 5 of 5
  • Unit pricePassed

    224 tokens: 61 read, 163 written · 2 s · 93.8 tok/s

    A shop sells pencils at 5 for $1.00. How much do 6 pencils cost, in dollars? Work it out, then end with a line "ANSWER: <number>".
    If 5 pencils cost $1.00, then one pencil costs:
    
    $1.00 ÷ 5 = $0.20
    
    So 6 pencils cost:
    
    6 × $0.20 = $1.20
    
    ANSWER: 1.20
  • Day and datePassed

    2,337 tokens: 76 read, 2,261 written · 16 s · 140 tok/s

    Today is Monday, 31 August 2026. What day of the week, and what date, is it 363 days from today? Work it out, then end with a line "ANSWER: <day of the week>, <YYYY-MM-DD>".
    Today is Monday, 31 August 2026.
    
    **Day of the week:**  
    363 ÷ 7 = 51 weeks remainder 6 days.  
    Monday + 6 days = Sunday.
    
    **Date:**  
    From 31 August 2026, adding 363 days:
    - 31 August 2026 + 365 days = 31 August 2027 (a full year, since no Feb 29 falls in between)
    - 363 days = 365 − 2, so the date is 2 days before 31 August 2027
    - That gives 29 August 2027
    
    ANSWER: Sunday, 2027-08-29
  • Who owns each petPassed

    787 tokens: 175 read, 612 written · 7 s · 93.1 tok/s

    Five people, Lea, Dee, Cal, Eli and Ivy, each own exactly one of these pets: a cat, a dog, a fish, a bird and a rabbit. Each pet has one owner. Clues:
    - Lea owns the cat or the rabbit.
    - Lea owns the dog or the rabbit.
    - Ivy owns the cat or the fish.
    - Cal does not own the bird.
    - Dee does not own the dog.
    - Cal owns the cat or the bird.
    Who owns each pet? Work it out, then end with a line "ANSWER: <owner of the cat>, <owner of the dog>, <owner of the fish>, <owner of the bird>, <owner of the rabbit>", with the five names in that order, separated by commas.
    Lea owns the cat or rabbit, and also the dog or rabbit. Since Lea owns only one pet, Lea cannot satisfy both clues without owning the rabbit; otherwise Lea would need both the cat and the dog. So Lea owns the rabbit.
    
    Cal owns the cat or bird, but not the bird, so Cal owns the cat. Ivy owns the cat or fish; the cat is taken by Cal, so Ivy owns the fish.
    
    The remaining pets are the dog and bird for Dee and Eli. Dee does not own the dog, so Dee owns the bird, leaving Eli with the dog.
    
    ANSWER: Cal, Eli, Ivy, Dee, Lea
  • Arrival timePassed

    385 tokens: 71 read, 314 written · 3 s · 114 tok/s

    A train leaves at 21:25 and the trip takes 3 hours 50 minutes. At what time does it arrive? Work it out, then end with a line "ANSWER: <HH:MM>" in 24-hour time.
    Start at 21:25.
    
    Add 3 hours: 21:25 + 3:00 = 00:25 (next day).
    
    Add 50 minutes: 00:25 + 0:50 = 01:15.
    
    The train arrives at 01:15 the next day.
    
    ANSWER: 01:15
  • Filling a tankPassed

    386 tokens: 98 read, 288 written · 2 s · 123 tok/s

    A tank holds 280 liters and starts empty. Pipe A adds 10 liters an hour, pipe B adds 11 liters an hour, and a drain takes 14 liters an hour out of it. With all three open, how many hours until the tank is full? Work it out, then end with a line "ANSWER: <number>".
    Net fill rate:  
    Pipe A + Pipe B − Drain = 10 + 11 − 14 = 7 liters per hour.
    
    Time to fill 280 liters:  
    280 ÷ 7 = 40 hours.
    
    ANSWER: 40
Reading code 4 of 4
  • What does it printPassed

    762 tokens: 93 read, 669 written · 5 s · 128 tok/s

    What numbers does this Python program print, in order? Work it out, then end with a line "ANSWER: <numbers, separated by commas>".
    
    def f(xs):
        return sorted(xs)[::-1][:2]
    
    print(f([19, 49, 14, 31, 3, 20]))
    The program works as follows:
    
    1. `sorted([19, 49, 14, 31, 3, 20])` produces `[3, 14, 19, 20, 31, 49]`.
    2. `[::-1]` reverses it to `[49, 31, 20, 19, 14, 3]`.
    3. `[:2]` takes the first two elements: `[49, 31]`.
    4. `print(...)` outputs that list.
    
    ANSWER: 49, 31
  • Trace a loopPassed

    949 tokens: 98 read, 851 written · 5 s · 166 tok/s

    What does this Python program print? Work it out, then end with a line "ANSWER: <output>".
    
    def g(n):
        total = 0
        for i in range(1, n + 1):
            if i % 3 == 0 or i % 7 == 0:
                total += i
        return total
    
    print(g(110))
    The function sums all integers from 1 to 110 that are divisible by 3 or 7.
    
    Using inclusion–exclusion:
    
    - Multiples of 3 up to 110: ⌊110/3⌋ = 36 terms  
      Sum = 3 · (36·37/2) = 1998
    - Multiples of 7 up to 110: ⌊110/7⌋ = 15 terms  
      Sum = 7 · (15·16/2) = 840
    - Multiples of 21 (counted twice): ⌊110/21⌋ = 5 terms  
      Sum = 21 · (5·6/2) = 315
    
    Total = 1998 + 840 − 315 = 2523
    
    ANSWER: 2523
  • Find the bugPassed

    445 tokens: 125 read, 320 written · 2 s · 130 tok/s

    The function decimal_mean should return the mean of a non-empty list, as a decimal number. The code below has one bug. Find the line with the bug, and write that line corrected, exactly as it should read in the code. Work it out, then end with a line "ANSWER: <corrected line>".
    
    def decimal_mean(amounts):
        total = 0
        size = 0
        for n in amounts:
            total += n
            size += 1
        return total // size
    The bug is on the return line: `//` performs floor (integer) division, which truncates the result instead of producing a decimal mean. It should use true division `/`.
    
    ANSWER: return total / size
  • Run a query in your headPassed

    503 tokens: 149 read, 354 written · 3 s · 128 tok/s

    What rows does this SQL query return? Output only the rows, one per line, as customer,total in the query's order.
    
    Table orders:
    id | customer | amount
    1  | ben      | 40
    2  | ben      | 105
    3  | cal      | 40
    4  | ana      | 10
    5  | cal      | 100
    6  | ana      | 80
    
    Query:
    SELECT customer, SUM(amount) AS total
    FROM orders
    GROUP BY customer
    HAVING SUM(amount) > 100
    ORDER BY total DESC;
    ben,145
    cal,140
Using tools 5 of 5
  • Call one toolPassed

    921 tokens: 731 read, 190 written · 2 s · 99.3 tok/s

    What's the weather in Denver right now, in celsius?
    1. user
      What's the weather in Denver right now, in celsius?
    2. assistant
      get_weather({"city":"Denver","unit":"celsius"})
    3. tool
      {"city": "Denver", "conditions": "windy", "temperature": 23, "unit": "celsius"}
    4. assistant
      The weather in Denver right now is windy with a temperature of **23 °C**.
  • Don't call a tool when none is neededPassed

    547 tokens: 460 read, 87 written · 1 s · 84.4 tok/s

    What is 17 times 29?
    1. user
      What is 17 times 29?
    2. assistant
      17 times 29 is 493.
  • Two calls for two answersPassed

    1,187 tokens: 857 read, 330 written · 3 s · 99.2 tok/s

    Convert 65 EUR to GBP and to USD.
    1. user
      Convert 65 EUR to GBP and to USD.
    2. assistant
      convert_currency({"amount":65,"from":"EUR","to":"GBP"})
      convert_currency({"amount":65,"from":"EUR","to":"USD"})
    3. tool
      {"amount": 55.9, "currency": "GBP"}
    4. tool
      {"amount": 70.33, "currency": "USD"}
    5. assistant
      65 EUR is approximately:
      
      - **55.90 GBP**
      - **70.33 USD**
  • Chain two toolsPassed

    1,575 tokens: 1,268 read, 307 written · 4 s · 83.9 tok/s

    What is the status of each order for the customer with the email kim@example.com?
    1. user
      What is the status of each order for the customer with the email kim@example.com?
    2. assistant
      find_customer({"email":"kim@example.com"})
    3. tool
      {"customer_id": "C-1042", "name": "Kim Park"}
    4. assistant
      get_orders({"customer_id":"C-1042"})
    5. tool
      {"orders": [{"order_id": "A-97", "status": "cancelled"}, {"carrier": "DHL", "order_id": "A-60", "status": "shipped"}]}
    6. assistant
      Here are the order statuses for the customer with email **kim@example.com** (Kim Park):
      
      | Order ID | Status |
      |----------|--------|
      | A-97     | Cancelled |
      | A-60     | Shipped (carrier: DHL) |
  • Handle a failed call honestlyPassed

    1,133 tokens: 821 read, 312 written · 3 s · 104 tok/s

    Book a table for 2 people at Luigi's tonight at 20:15. If that time is not free, do not book another time without asking me first.
    1. user
      Book a table for 2 people at Luigi's tonight at 20:15. If that time is not free, do not book another time without asking me first.
    2. assistant
      book_table({"people":2,"restaurant":"Luigi's","time":"20:15"})
    3. tool
      {"available_times": ["19:45", "21:45"], "error": "fully booked at that time"}
    4. assistant
      I'm sorry, but Luigi's is fully booked at 20:15 tonight. 
      
      Available times at Luigi's tonight are:
      - 19:45
      - 21:45
      
      Would you like me to book a table for 2 people at one of these times instead?
Building pages 4 of 5
  • A small websitePassed

    2,295 tokens: 197 read, 2,098 written · 17 s · 125 tok/s

    Build a one-page website for a bakery called "Golden Bakehouse". It must have a <header> containing an <h1> with the bakery's name; a <nav> with exactly 3 links; a <main> with a <section id="menu"> listing at least 4 items in a list, including Rosemary bread, Pecan danish, Croissant and Almond cake; and a <footer> with the opening hours. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Golden Bakehouse</title>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        margin: 0;
        padding: 0;
        line-height: 1.6;
        color: #4a2c1a;
        background-color: #fff8e7;
      }
      header {
        background-color: #8b4513;
        color: #ffffff;
        padding: 1.5rem;
        text-align: center;
      }
      header h1 {
        margin: 0;
        font-size: 2.5rem;
      }
      nav {
        background-color: #d2b48c;
        padding: 0.75rem;
        text-align: center;
      }
      nav a {
        color: #8b4513;
        text-decoration: none;
        margin: 0 1.25rem;
        font-weight: bold;
        font-size: 1rem;
      }
      nav a:hover {
        text-decoration: underline;
      }
      main {
        max-width: 900px;
        margin: 2rem auto;
        padding: 0 1rem;
      }
      section#menu {
        margin-top: 1rem;
      }
      h2 {
        color: #8b4513;
        border-bottom: 3px solid #d2b48c;
        padding-bottom: 0.5rem;
        margin-top: 0;
      }
      ul {
        list-style-type: disc;
        padding-left: 1.5rem;
      }
      li {
        margin-bottom: 0.5rem;
        font-size: 1.1rem;
      }
      footer {
        background-color: #8b4513;
        color: #ffffff;
        text-align: center;
        padding: 1rem;
        font-size: 0.95rem;
      }
    </style>
    </head>
    <body>
    
    <header>
      <h1>Golden Bakehouse</h1>
    </header>
    
    <nav>
      <a href="#home">Home</a>
      <a href="#menu">Menu</a>
      <a href="#contact">Contact</a>
    </nav>
    
    <main>
      <section id="menu">
        <h2>Freshly Baked Menu</h2>
        <ul>
          <li>Rosemary bread</li>
          <li>Pecan danish</li>
          <li>Croissant</li>
          <li>Almond cake</li>
        </ul>
      </section>
    </main>
    
    <footer>
      <p>Opening hours: Monday&ndash;Friday 7:00 AM &ndash; 6:00 PM &bull; Saturday&ndash;Sunday 8:00 AM &ndash; 4:00 PM</p>
    </footer>
    
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        console.log('Golden Bakehouse website loaded');
      });
    </script>
    
    </body>
    </html>
  • A pricing table with a toggleFailed

    7,270 tokens: 220 read, 7,050 written · 1 min 1 s · 115 tok/s

    Build a pricing page with three plans, in this order: Solo at $9 a month or $90 a year, Business at $40 a month or $400 a year and Premium at $45 a month or $450 a year. Each plan is an element with class "plan" containing an element with class "price". Show the monthly prices first, and write the words monthly and yearly as text in the markup, not as CSS content. Add a <button id="billing-toggle"> that switches every price between monthly and yearly billing when clicked. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pricing</title>
    <style>
      body {
        font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        line-height: 1.5;
        color: #111;
        padding: 2rem;
        max-width: 800px;
        margin: 0 auto;
      }
      .plans {
        display: flex;
        gap: 1rem;
        flex-wrap: wrap;
        justify-content: center;
        margin-top: 1rem;
      }
      .plan {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 1.5rem;
        width: 220px;
        text-align: center;
        background: #fff;
      }
      .plan h2 {
        margin: 0 0 1rem;
        font-size: 1.25rem;
      }
      .price {
        margin: 1rem 0;
        font-size: 1.75rem;
      }
      .price-item {
        margin: 0 0.25rem;
      }
      .price-item.active {
        color: #000;
        font-weight: 700;
      }
      .price-item.inactive {
        color: #888;
        font-weight: 400;
      }
      button#billing-toggle {
        padding: 0.6rem 1.2rem;
        font-size: 1rem;
        cursor: pointer;
        margin-bottom: 1rem;
      }
    </style>
    </head>
    <body>
    <button id="billing-toggle">Switch to Yearly</button>
    <div class="plans">
      <div class="plan">
        <h2>Solo</h2>
        <div class="price">
          <span class="price-item monthly active" data-billing="monthly">$9 <span>monthly</span></span>
          <span class="price-item yearly inactive" data-billing="yearly">$90 <span>yearly</span></span>
        </div>
      </div>
      <div class="plan">
        <h2>Business</h2>
        <div class="price">
          <span class="price-item monthly active" data-billing="monthly">$40 <span>monthly</span></span>
          <span class="price-item yearly inactive" data-billing="yearly">$400 <span>yearly</span></span>
        </div>
      </div>
      <div class="plan">
        <h2>Premium</h2>
        <div class="price">
          <span class="price-item monthly active" data-billing="monthly">$45 <span>monthly</span></span>
          <span class="price-item yearly inactive" data-billing="yearly">$450 <span>yearly</span></span>
        </div>
      </div>
    </div>
    <script>
      const toggle = document.getElementById('billing-toggle');
      let yearly = false;
    
      toggle.addEventListener('click', function () {
        yearly = !yearly;
    
        document.querySelectorAll('.price-item').forEach(function (item) {
          const isYearly = item.getAttribute('data-billing') === 'yearly';
          const show = yearly ? isYearly : !isYearly;
          item.classList.toggle('active', show);
          item.classList.toggle('inactive', !show);
        });
    
        toggle.textContent = yearly ? 'Switch to Monthly' : 'Switch to Yearly';
      });
    </script>
    </body>
    </html>
  • An accessible sign-up formPassed

    2,480 tokens: 256 read, 2,224 written · 15 s · 150 tok/s

    Build a sign-up form for Velvet Works. Put the brand name in a heading above the form. The form is <form id="signup"> with inputs id="name", id="email" (type email) and id="password" (type password, minlength at least 8), each with a <label for>, and a submit button. Give the form a novalidate attribute, and check the fields yourself when it is submitted. If the email is not a valid address, or the password is shorter than 8 characters, do not send the form; show a message in an element with id="status" and role="status" that says what is wrong. If the form is valid, prevent the real submission and leave the status element empty. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Velvet Works Sign Up</title>
    <style>
      body {
        font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        margin: 2rem;
        line-height: 1.5;
      }
      h1 {
        font-size: 1.75rem;
        margin-bottom: 1rem;
      }
      form {
        max-width: 340px;
      }
      label {
        display: block;
        margin-bottom: 0.25rem;
        font-weight: 600;
        font-size: 0.95rem;
      }
      input {
        width: 100%;
        padding: 0.5rem;
        margin-bottom: 1rem;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
        font-size: 1rem;
      }
      button {
        padding: 0.6rem 1.2rem;
        background-color: #333;
        color: #fff;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 1rem;
      }
      button:hover {
        background-color: #555;
      }
      #status {
        margin-top: 1rem;
        font-size: 0.9rem;
        color: #a31621;
      }
    </style>
    </head>
    <body>
    <h1>Velvet Works</h1>
    <form id="signup" novalidate>
      <label for="name">Name</label>
      <input id="name" type="text">
    
      <label for="email">Email</label>
      <input id="email" type="email">
    
      <label for="password">Password</label>
      <input id="password" type="password" minlength="8">
    
      <button type="submit">Sign up</button>
    </form>
    <div id="status" role="status"></div>
    <script>
      const form = document.getElementById('signup');
      const status = document.getElementById('status');
    
      form.addEventListener('submit', function(event) {
        event.preventDefault();
        status.textContent = '';
    
        const emailInput = document.getElementById('email');
        const passwordInput = document.getElementById('password');
    
        const email = emailInput.value.trim();
        const password = passwordInput.value;
    
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        const messages = [];
    
        if (!emailPattern.test(email)) {
          messages.push('Please enter a valid email address.');
        }
    
        if (password.length < 8) {
          messages.push('Password must be at least 8 characters.');
        }
    
        if (messages.length > 0) {
          status.textContent = messages.join(' ');
        }
        // If valid, status remains empty and no submission occurs.
      });
    </script>
    </body>
    </html>
  • A to-do app that remembersPassed

    2,782 tokens: 188 read, 2,594 written · 17 s · 156 tok/s

    Build a to-do list app called "Garden chores". Show its name in a heading. The app has an <input id="new-task">, a <button id="add"> and a <ul id="tasks">. Clicking add appends the text as an <li> with its own remove button. Save the list in localStorage under the key "todos" and load it again when the page opens. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Garden chores</title>
    <style>
      body {
        font-family: system-ui, -apple-system, sans-serif;
        padding: 1rem;
        max-width: 400px;
        margin: 0 auto;
        line-height: 1.5;
      }
      h1 {
        text-align: center;
        margin-bottom: 1rem;
      }
      input#new-task {
        padding: 0.5rem;
        font-size: 1rem;
        width: 70%;
        box-sizing: border-box;
      }
      button#add {
        padding: 0.5rem 1rem;
        font-size: 1rem;
        cursor: pointer;
        width: 25%;
        box-sizing: border-box;
      }
      ul#tasks {
        list-style: disc inside;
        padding-left: 0;
        margin-top: 1rem;
      }
      li {
        margin-bottom: 0.5rem;
        padding: 0.5rem;
        border: 1px solid #ccc;
        border-radius: 4px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      li button {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
        cursor: pointer;
        background: #ff4d4d;
        color: white;
        border: none;
        border-radius: 3px;
      }
    </style>
    </head>
    <body>
    <h1>Garden chores</h1>
    <input type="text" id="new-task" placeholder="e.g. Water the tomatoes">
    <button id="add">Add</button>
    <ul id="tasks"></ul>
    <script>
    const input = document.getElementById('new-task');
    const addButton = document.getElementById('add');
    const tasksList = document.getElementById('tasks');
    
    function createTaskElement(text) {
      const li = document.createElement('li');
    
      const span = document.createElement('span');
      span.textContent = text;
      li.appendChild(span);
    
      const removeButton = document.createElement('button');
      removeButton.type = 'button';
      removeButton.textContent = 'Remove';
      removeButton.addEventListener('click', function () {
        li.remove();
        saveTasks();
      });
      li.appendChild(removeButton);
    
      return li;
    }
    
    function saveTasks() {
      const items = [];
      for (const li of tasksList.children) {
        items.push(li.firstElementChild.textContent);
      }
      localStorage.setItem('todos', JSON.stringify(items));
    }
    
    function loadTasks() {
      const raw = localStorage.getItem('todos');
      if (!raw) return;
      try {
        const items = JSON.parse(raw);
        if (Array.isArray(items)) {
          for (const text of items) {
            if (typeof text === 'string' && text.trim() !== '') {
              tasksList.appendChild(createTaskElement(text));
            }
          }
        }
      } catch (e) {
        // ignore malformed stored data
      }
    }
    
    function addTask() {
      const value = input.value.trim();
      if (value === '') return;
      tasksList.appendChild(createTaskElement(value));
      input.value = '';
      saveTasks();
    }
    
    addButton.addEventListener('click', addTask);
    input.addEventListener('keydown', function (event) {
      if (event.key === 'Enter') {
        addTask();
      }
    });
    
    loadTasks();
    </script>
    </body>
    </html>
  • A bar chart in SVGPassed

    2,976 tokens: 239 read, 2,737 written · 24 s · 115 tok/s

    Draw an inline SVG bar chart of coffee sold, in this order: Feb 34, Mar 17, Apr 14, May 35 and Jun 33. Give the <svg> a width and a height, and a <title> or an aria-label. Each bar is a <rect class="bar"> whose height attribute is proportional to its value, and every bar is inside the <svg>. Each bar is labelled with its day or month in a <text> element under the bar. Write the bars and labels directly in the SVG markup, not with JavaScript. Do not move, resize or hide them with a transform or with CSS. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Coffee Sold</title>
    <style>
      .bar { fill: #2c7fb8; }
      text { font-family: sans-serif; font-size: 14px; fill: #222; text-anchor: middle; }
    </style>
    </head>
    <body>
    <svg width="500" height="300" aria-label="Coffee sold by month">
      <rect class="bar" x="50" y="50" width="40" height="170"></rect>
      <text x="70" y="250">Feb</text>
      <rect class="bar" x="120" y="135" width="40" height="85"></rect>
      <text x="140" y="250">Mar</text>
      <rect class="bar" x="190" y="150" width="40" height="70"></rect>
      <text x="210" y="250">Apr</text>
      <rect class="bar" x="260" y="45" width="40" height="175"></rect>
      <text x="280" y="250">May</text>
      <rect class="bar" x="330" y="55" width="40" height="165"></rect>
      <text x="350" y="250">Jun</text>
    </svg>
    </body>
    </html>
Building games 3 of 4
  • Build 2048Passed

    15,205 tokens: 458 read, 14,747 written · 1 min 48 s · 136 tok/s

    Build the game 2048 as one web page, playable with the arrow keys, with the board drawn on the page.
    
    In <script id="game">, define createGame() returning an object with move(dir) and state(). dir is "up", "down", "left" or "right". state() returns {board, score, over}: board is 4 rows of 4 numbers, top row first (0 is an empty cell), score is a number, over is a boolean.
    
    The rules, exactly:
    1. The board starts as this one, then a 2 is put in each of the first two empty cells in reading order (row by row from the top, left to right). The score starts at 0.
    [32, 0, 0, 4]
    [0, 32, 2, 0]
    [0, 0, 16, 2]
    [0, 0, 16, 4]
    2. A move slides every tile as far as it goes toward dir. Two tiles of the same value that meet merge into one tile of their sum, nearest the side they move toward first: moving left, [2,2,2,2] becomes [4,4,0,0] and [2,2,2,0] becomes [4,2,0,0]. A tile made by a merge does not merge again in the same move.
    3. Each merge adds the new tile's value to the score.
    4. If a move changed the board, a 2 is put in the first empty cell in reading order. A move that changes nothing does nothing.
    5. over is true when no move would change the board; then moves do nothing.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2048</title>
    <style>
    body { font-family: Arial, sans-serif; display: flex; flex-direction: column; align-items: center; padding: 20px; background: #faf8ef; }
    h1 { margin: 0 0 10px; font-size: 40px; color: #776e65; }
    #score { font-size: 24px; margin-bottom: 10px; color: #776e65; }
    #board { display: grid; grid-template-columns: repeat(4, 100px); grid-template-rows: repeat(4, 100px); gap: 10px; background: #bbada0; padding: 15px; border-radius: 6px; }
    .cell { width: 100px; height: 100px; background: #cdc1b4; border-radius: 3px; display: flex; align-items: center; justify-content: center; font-size: 32px; font-weight: bold; color: #776e65; }
    .v2 { background: #eee4da; color: #776e65; }
    .v4 { background: #ede0c8; color: #776e65; }
    .v8 { background: #f2b179; color: #f9f6f2; }
    .v16 { background: #f59563; color: #f9f6f2; }
    .v32 { background: #f67c5f; color: #f9f6f2; }
    .v64 { background: #f65e3b; color: #f9f6f2; }
    .v128 { background: #edcf72; color: #f9f6f2; }
    .v256 { background: #edcc61; color: #f9f6f2; }
    .v512 { background: #edc850; color: #f9f6f2; }
    .v1024 { background: #edc53f; color: #f9f6f2; }
    .v2048 { background: #edc22e; color: #f9f6f2; }
    #msg { margin-top: 10px; color: #b30000; font-weight: bold; }
    </style>
    </head>
    <body>
    <h1>2048</h1>
    <div id="score">Score: 0</div>
    <div id="board"></div>
    <div id="msg"></div>
    <script id="game">
    'use strict';
    function createGame() {
      var board = [
        [32, 0, 0, 4],
        [0, 32, 2, 0],
        [0, 0, 16, 2],
        [0, 0, 16, 4]
      ];
      var score = 0;
      var over = false;
    
      var placed = 0;
      for (var r = 0; r < 4 && placed < 2; r++) {
        for (var c = 0; c < 4 && placed < 2; c++) {
          if (board[r][c] === 0) {
            board[r][c] = 2;
            placed++;
          }
        }
      }
    
      function cloneBoard(b) {
        return [
          b[0].slice(),
          b[1].slice(),
          b[2].slice(),
          b[3].slice()
        ];
      }
    
      function canMove(b) {
        for (var i = 0; i < 4; i++) {
          for (var j = 0; j < 4; j++) {
            if (b[i][j] === 0) return true;
          }
        }
        for (var i = 0; i < 4; i++) {
          for (var j = 0; j < 3; j++) {
            if (b[i][j] === b[i][j + 1]) return true;
          }
        }
        for (var j = 0; j < 4; j++) {
          for (var i = 0; i < 3; i++) {
            if (b[i][j] === b[i + 1][j]) return true;
          }
        }
        return false;
      }
    
      over = !canMove(board);
    
      function processLine(line) {
        var out = [0, 0, 0, 0];
        var pos = 0;
        var prev = null;
        var delta = 0;
        for (var i = 0; i < 4; i++) {
          var v = line[i];
          if (v === 0) continue;
          if (prev !== null && prev.val === v && !prev.merged) {
            out[pos - 1] = v * 2;
            delta += v * 2;
            prev.merged = true;
          } else {
            out[pos] = v;
            prev = { val: v, merged: false };
            pos++;
          }
        }
        return { out: out, delta: delta };
      }
    
      function rowsEqual(a, b) {
        return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];
      }
    
      function simulate(b, dir) {
        var nb = cloneBoard(b);
        var totalDelta = 0;
        var changed = false;
    
        if (dir === 'left') {
          for (var r = 0; r < 4; r++) {
            var oldRow = nb[r];
            var res = processLine(oldRow);
            nb[r] = res.out;
            totalDelta += res.delta;
            if (!rowsEqual(oldRow, res.out)) changed = true;
          }
        } else if (dir === 'right') {
          for (var r = 0; r < 4; r++) {
            var oldRow = nb[r];
            var line = [oldRow[3], oldRow[2], oldRow[1], oldRow[0]];
            var res = processLine(line);
            var newRow = [res.out[3], res.out[2], res.out[1], res.out[0]];
            nb[r] = newRow;
            totalDelta += res.delta;
            if (!rowsEqual(oldRow, newRow)) changed = true;
          }
        } else if (dir === 'up') {
          for (var c = 0; c < 4; c++) {
            var oldCol = [nb[0][c], nb[1][c], nb[2][c], nb[3][c]];
            var res = processLine(oldCol);
            nb[0][c] = res.out[0];
            nb[1][c] = res.out[1];
            nb[2][c] = res.out[2];
            nb[3][c] = res.out[3];
            totalDelta += res.delta;
            if (oldCol[0] !== res.out[0] || oldCol[1] !== res.out[1] || oldCol[2] !== res.out[2] || oldCol[3] !== res.out[3]) changed = true;
          }
        } else if (dir === 'down') {
          for (var c = 0; c < 4; c++) {
            var oldCol = [nb[0][c], nb[1][c], nb[2][c], nb[3][c]];
            var line = [oldCol[3], oldCol[2], oldCol[1], oldCol[0]];
            var res = processLine(line);
            var newCol = [res.out[3], res.out[2], res.out[1], res.out[0]];
            nb[0][c] = newCol[0];
            nb[1][c] = newCol[1];
            nb[2][c] = newCol[2];
            nb[3][c] = newCol[3];
            totalDelta += res.delta;
            if (oldCol[0] !== newCol[0] || oldCol[1] !== newCol[1] || oldCol[2] !== newCol[2] || oldCol[3] !== newCol[3]) changed = true;
          }
        }
    
        return { newBoard: nb, scoreDelta: totalDelta, changed: changed };
      }
    
      function addFirstEmptyTwo(b) {
        for (var r = 0; r < 4; r++) {
          for (var c = 0; c < 4; c++) {
            if (b[r][c] === 0) {
              b[r][c] = 2;
              return;
            }
          }
        }
      }
    
      return {
        move: function (dir) {
          if (over) return;
          var sim = simulate(board, dir);
          if (!sim.changed) return;
          board = sim.newBoard;
          score += sim.scoreDelta;
          addFirstEmptyTwo(board);
          over = !canMove(board);
        },
        state: function () {
          return {
            board: cloneBoard(board),
            score: score,
            over: over
          };
        }
      };
    }
    </script>
    <script>
    (function () {
      'use strict';
      var game = createGame();
      var scoreEl = document.getElementById('score');
      var msgEl = document.getElementById('msg');
      var cells = [];
      for (var r = 0; r < 4; r++) {
        for (var c = 0; c < 4; c++) {
          var div = document.createElement('div');
          div.className = 'cell';
          div.id = 'cell-' + r + '-' + c;
          document.getElementById('board').appendChild(div);
          cells.push(div);
        }
      }
    
      function render() {
        var s = game.state();
        for (var r = 0; r < 4; r++) {
          for (var c = 0; c < 4; c++) {
            var v = s.board[r][c];
            var cell = cells[r * 4 + c];
            cell.textContent = v === 0 ? '' : String(v);
            cell.className = 'cell';
            if (v !== 0) {
              cell.classList.add('tile');
              cell.classList.add('v' + v);
              if (v >= 1024) cell.style.fontSize = '24px';
              else if (v >= 256) cell.style.fontSize = '28px';
              else cell.style.fontSize = '32px';
            } else {
              cell.style.fontSize = '';
            }
          }
        }
        scoreEl.textContent = 'Score: ' + s.score;
        msgEl.textContent = s.over ? 'Game Over' : '';
      }
    
      window.addEventListener('keydown', function (e) {
        var key = e.key;
        if (key === 'ArrowUp') {
          e.preventDefault();
          game.move('up');
          render();
        } else if (key === 'ArrowDown') {
          e.preventDefault();
          game.move('down');
          render();
        } else if (key === 'ArrowLeft') {
          e.preventDefault();
          game.move('left');
          render();
        } else if (key === 'ArrowRight') {
          e.preventDefault();
          game.move('right');
          render();
        }
      });
    
      render();
    })();
    </script>
    </body>
    </html>
  • Build SnakeFailed

    9,298 tokens: 458 read, 8,840 written · 1 min 17 s · 115 tok/s

    Build Snake as one web page on a 10 by 10 grid, playable with the arrow keys (one key press, one step), with the grid drawn on the page.
    
    In <script id="game">, define createGame() returning an object with step(dir) and state(). dir is "up", "down", "left" or "right". state() returns {snake, food, score, over}: snake is a list of [x, y] cells, head first; food is [x, y]; score is a number; over is a boolean. x is the column (0 to 9, left to right), y the row (0 to 9, top to bottom); up is y - 1.
    
    The rules, exactly:
    1. The game starts with snake [[6, 4], [7, 4], [8, 4]], moving left, food at [7, 9], score 0.
    2. step(dir): if dir is the opposite of the current direction it is ignored and the snake keeps going; otherwise dir becomes the current direction. The head moves one cell that way.
    3. If the new head cell holds the food, the snake grows: its tail stays. Otherwise the tail cell is freed first.
    4. If the new head is off the grid or on a cell of the snake (after rule 3), the game is over: over becomes true and nothing else changes. Once over, step does nothing.
    5. Eating adds 1 to the score, and the next food goes to the first empty cell in reading order (row by row from the top, left to right) after the new head's cell, wrapping from [9, 9] to [0, 0].
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snake 10x10</title>
    <style>
      body { font-family: system-ui, sans-serif; padding: 20px; }
      #grid {
        display: grid;
        grid-template-columns: repeat(10, 22px);
        grid-template-rows: repeat(10, 22px);
        border: 3px solid #222;
        margin-bottom: 8px;
        user-select: none;
      }
      .cell {
        width: 22px;
        height: 22px;
        border: 1px solid #999;
        box-sizing: border-box;
      }
      .snake { background-color: #0b6; }
      .head { background-color: #0d4; border: 2px solid #042; box-sizing: border-box; }
      .food { background-color: #e41; }
      #message { margin-top: 8px; font-weight: bold; color: #a00; height: 1.2em; }
      #score { font-size: 1.2em; margin-bottom: 8px; }
    </style>
    </head>
    <body>
    <div id="score">Score: 0</div>
    <div id="grid"></div>
    <div id="message"></div>
    
    <script id="game">
    function createGame() {
      var width = 10;
      var height = 10;
      var snake = [[6, 4], [7, 4], [8, 4]];
      var food = [7, 9];
      var score = 0;
      var over = false;
      var dir = "left";
    
      var opposite = {
        up: "down",
        down: "up",
        left: "right",
        right: "left"
      };
    
      function step(nextDir) {
        if (over) {
          return;
        }
    
        if (nextDir !== opposite[dir]) {
          dir = nextDir;
        }
    
        var head = snake[0];
        var newHead;
        if (dir === "up") {
          newHead = [head[0], head[1] - 1];
        } else if (dir === "down") {
          newHead = [head[0], head[1] + 1];
        } else if (dir === "left") {
          newHead = [head[0] - 1, head[1]];
        } else {
          newHead = [head[0] + 1, head[1]];
        }
    
        if (newHead[0] < 0 || newHead[0] >= width || newHead[1] < 0 || newHead[1] >= height) {
          over = true;
          return;
        }
    
        var ate = (newHead[0] === food[0] && newHead[1] === food[1]);
    
        var newSnake;
        if (ate) {
          newSnake = [newHead].concat(snake);
        } else {
          newSnake = [newHead].concat(snake.slice(0, snake.length - 1));
        }
    
        for (var i = 1; i < newSnake.length; i++) {
          if (newSnake[i][0] === newHead[0] && newSnake[i][1] === newHead[1]) {
            over = true;
            return;
          }
        }
    
        snake = newSnake;
    
        if (ate) {
          score += 1;
          food = placeFood(newHead, snake);
        }
      }
    
      function placeFood(head, currentSnake) {
        var start = head[1] * width + head[0] + 1;
        var total = width * height;
        for (var i = 0; i < total; i++) {
          var idx = (start + i) % total;
          var x = idx % width;
          var y = Math.floor(idx / width);
          var occupied = false;
          for (var j = 0; j < currentSnake.length; j++) {
            if (currentSnake[j][0] === x && currentSnake[j][1] === y) {
              occupied = true;
              break;
            }
          }
          if (!occupied) {
            return [x, y];
          }
        }
        return food;
      }
    
      function state() {
        return {
          snake: snake.map(function (cell) { return [cell[0], cell[1]]; }),
          food: [food[0], food[1]],
          score: score,
          over: over
        };
      }
    
      return {
        step: step,
        state: state
      };
    }
    </script>
    <script>
    (function () {
      var game = createGame();
    
      var scoreEl = document.getElementById('score');
      var gridEl = document.getElementById('grid');
      var msgEl = document.getElementById('message');
    
      var cells = [];
      for (var y = 0; y < 10; y++) {
        for (var x = 0; x < 10; x++) {
          var cell = document.createElement('div');
          cell.className = 'cell';
          cell.dataset.x = x;
          cell.dataset.y = y;
          gridEl.appendChild(cell);
          cells.push(cell);
        }
      }
    
      function cellAt(x, y) {
        return cells[y * 10 + x];
      }
    
      function render() {
        var s = game.state();
    
        cells.forEach(function (c) {
          c.className = 'cell';
        });
    
        s.snake.forEach(function (part, i) {
          var c = cellAt(part[0], part[1]);
          c.classList.add('snake');
          if (i === 0) {
            c.classList.add('head');
          }
        });
    
        var fc = cellAt(s.food[0], s.food[1]);
        fc.classList.add('food');
    
        scoreEl.textContent = 'Score: ' + s.score;
        msgEl.textContent = s.over ? 'GAME OVER' : '';
      }
    
      document.addEventListener('keydown', function (e) {
        var dir;
        switch (e.key) {
          case 'ArrowUp': dir = 'up'; break;
          case 'ArrowDown': dir = 'down'; break;
          case 'ArrowLeft': dir = 'left'; break;
          case 'ArrowRight': dir = 'right'; break;
          default: return;
        }
        e.preventDefault();
        game.step(dir);
        render();
      });
    
      render();
    })();
    </script>
    </body>
    </html>
  • Box-pushing puzzlePassed

    15,057 tokens: 1,122 read, 13,935 written · 1 min 51 s · 126 tok/s

    Build a box-pushing puzzle as one web page on an 8 by 7 grid, playable with the arrow keys, with the level drawn on the page. Give the page and its heading the title Box-pushing puzzle.
    
    In <script id="game">, define createGame() returning an object with walk(dir) and state(). dir is "up", "down", "left" or "right". state() returns {player, boxes, pushes, steps, solved}: player is [x, y]; boxes is a list of [x, y] sorted by row, then column; pushes and steps are numbers; solved is a boolean. x is the column (0 to 7, left to right), y the row (0 to 6, top to bottom); up is y - 1.
    
    The level, row 0 first, 8 characters to a row (a space is empty floor; the outer ring is all wall):
    ```
    ########
    #     ##
    #    $ #
    ##     #
    #*  *  #
    #  +   #
    ########
    ```
    # wall, space floor, . goal, $ box, * box on a goal, @ player, + player on a goal.
    
    The rules, exactly:
    1. The game starts with this level, steps 0, pushes 0 and solved false. Walls and goals never change.
    2. walk(dir) moves the player one cell in dir. If that cell is a wall, nothing changes and nothing is counted. A goal is floor, so the player can stand on one.
    3. If that cell holds a box, the box moves one cell further in dir and the player takes the box's old cell. This push happens only if the cell beyond the box is empty floor or a goal: not a wall and not another box. Otherwise nothing changes and nothing is counted.
    4. A walk that moves the player adds 1 to steps. A push is a walk too, so it adds 1 to pushes as well.
    5. solved is true when every box is on a goal. Once solved, walk does nothing.
    
    The page: the arrow keys do the same walks as walk(dir), one walk for each key press (a key that repeats while held walks once). Four buttons with data-dir="up", data-dir="down", data-dir="left" and data-dir="right" do the same walks. Label them Up, Down, Left and Right, laid out like the arrow keys: Up above Down, with Left, Down and Right in one row. A button with id="restart", labelled Restart, starts the level over, with steps and pushes back at 0.
    The board is an element with id="board". It holds one element per cell, 56 in all, row by row from the top, 8 to a row, and nothing else. Each cell has role="img" and an aria-label that names what it holds: wall, empty floor, empty goal, box, box on a goal, you or you on a goal. Every cell except empty floor also shows a visible character as its text, so that a wall, a goal, a box and you can each be seen (the character is yours to choose).
    Show the steps in an element with id="steps" and the pushes in one with id="pushes", each as a plain number.
    The status line is an element with id="status". Until the level is solved, it must not say that it is solved (a line such as Not solved yet is fine). Once it is, it says solved, with the number of steps next to the word steps and the number of pushes next to the word pushes, for example: Solved in 12 steps with 3 pushes.
    A tenth of a second after each key press, button press or Restart, the board, the steps, the pushes and the status line show what state() says. A page may draw on the next animation frame or after a timer.
    The page must not use eval or Function, must not give a timer a string of text (a timer takes a function), must not add a script element to the page, must not set an event attribute such as onclick from text, and must not make network requests or load anything from another site: no fetch, XMLHttpRequest, WebSocket, EventSource, sendBeacon or importScripts, and no image or file from another site.
    The whole page must be under 65,536 characters, and the script with id="game" under 20,000 characters.
    Light background; walls dark, goals ringed, boxes and the player easy to tell apart. Tell a box on a goal from one off a goal by a mark or shape, not by colour alone. The two scripts share one global scope, so give the page's copy of the map another name than the logic's (a const MAP in both stops the second script with an error), or wrap the page's script in a function.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Box-pushing puzzle</title>
    <style>
      body {
        background: #f5f5f5;
        color: #111;
        font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
        margin: 0;
        padding: 1rem;
        line-height: 1.5;
      }
      h1 {
        font-size: 1.5rem;
        margin: 0 0 1rem;
        text-align: center;
      }
      #board {
        display: grid;
        grid-template-columns: repeat(8, 44px);
        grid-template-rows: repeat(7, 44px);
        gap: 6px;
        margin: 0 auto 1rem;
        max-width: fit-content;
      }
      #board > div {
        width: 44px;
        height: 44px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.6rem;
        box-sizing: border-box;
        border-radius: 4px;
        user-select: none;
      }
      .wall {
        background: #222;
        color: #aaa;
      }
      .floor {
        background: #fff;
      }
      .goal {
        background: #fff;
        border: 2px solid #000;
        border-radius: 50%;
      }
      .box {
        background: #c9c9c9;
        color: #000;
        font-weight: bold;
        border-radius: 4px;
      }
      .box.on-goal {
        position: relative;
        background: #c9c9c9;
        color: #000;
        font-weight: bold;
        border-radius: 4px;
        border: 2px solid #000;
      }
      .box.on-goal::after {
        content: "●";
        position: absolute;
        font-size: 0.55em;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        line-height: 1;
      }
      .player {
        background: #2e7d32;
        color: #fff;
        border-radius: 50%;
      }
      .player.on-goal {
        background: #2e7d32;
        color: #fff;
        border-radius: 50%;
        border: 2px solid #000;
      }
      .controls {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 0.5rem;
        margin-bottom: 1rem;
      }
      .arrow-row {
        display: flex;
        gap: 0.5rem;
      }
      button {
        padding: 0.45rem 0.9rem;
        font-size: 1rem;
        cursor: pointer;
        background: #fff;
        border: 1px solid #999;
        border-radius: 4px;
      }
      button:active {
        background: #e0e0e0;
      }
      #restart {
        margin-top: 0.25rem;
      }
      #steps, #pushes {
        font-size: 1.2rem;
        margin: 0 0.5rem;
        display: inline-block;
      }
      #status {
        margin-top: 0.5rem;
        font-weight: bold;
        min-height: 1.2rem;
        text-align: center;
      }
    </style>
    </head>
    <body>
    <h1>Box-pushing puzzle</h1>
    <div class="controls">
      <button data-dir="up">Up</button>
      <div class="arrow-row">
        <button data-dir="left">Left</button>
        <button data-dir="down">Down</button>
        <button data-dir="right">Right</button>
      </div>
      <button id="restart">Restart</button>
    </div>
    <div id="board"></div>
    <div>
      <span id="steps">0</span>
      <span id="pushes">0</span>
    </div>
    <div id="status">Not solved yet</div>
    <script id="game">
    function createGame() {
      const level = [
        "########",
        "#     ##",
        "#    $ #",
        "##     #",
        "#*  *  #",
        "#  +   #",
        "########"
      ];
      const W = 8;
      const H = 7;
      const isWall = [];
      const isGoal = [];
      let player = null;
      const boxes = [];
    
      for (let y = 0; y < H; y++) {
        isWall[y] = [];
        isGoal[y] = [];
        for (let x = 0; x < W; x++) {
          const ch = level[y][x];
          isWall[y][x] = (ch === "#");
          isGoal[y][x] = (ch === "." || ch === "*" || ch === "+");
          if (ch === "@" || ch === "+") {
            player = [x, y];
          } else if (ch === "$" || ch === "*") {
            boxes.push([x, y]);
          }
        }
      }
    
      boxes.sort((a, b) => a[1] - b[1] || a[0] - b[0]);
    
      let steps = 0;
      let pushes = 0;
      let solved = false;
    
      function updateSolved() {
        solved = boxes.every((b) => isGoal[b[1]][b[0]]);
      }
      updateSolved();
    
      function findBox(x, y) {
        return boxes.findIndex((b) => b[0] === x && b[1] === y);
      }
    
      function walk(dir) {
        if (solved) return;
    
        let dx = 0;
        let dy = 0;
        if (dir === "up") dy = -1;
        else if (dir === "down") dy = 1;
        else if (dir === "left") dx = -1;
        else if (dir === "right") dx = 1;
        else return;
    
        const nx = player[0] + dx;
        const ny = player[1] + dy;
    
        if (nx < 0 || nx >= W || ny < 0 || ny >= H) return;
        if (isWall[ny][nx]) return;
    
        const bi = findBox(nx, ny);
        if (bi !== -1) {
          const bx = nx + dx;
          const by = ny + dy;
          if (bx < 0 || bx >= W || by < 0 || by >= H) return;
          if (isWall[by][bx]) return;
          if (findBox(bx, by) !== -1) return;
    
          boxes[bi][0] = bx;
          boxes[bi][1] = by;
          player[0] = nx;
          player[1] = ny;
          pushes += 1;
          steps += 1;
        } else {
          player[0] = nx;
          player[1] = ny;
          steps += 1;
        }
    
        updateSolved();
      }
    
      function state() {
        return {
          player: player.slice(),
          boxes: boxes.map((b) => b.slice()).sort((a, b) => a[1] - b[1] || a[0] - b[0]),
          pushes: pushes,
          steps: steps,
          solved: solved
        };
      }
    
      return { walk: walk, state: state };
    }
    </script>
    <script>
    (function () {
      const PAGE_LEVEL = [
        "########",
        "#     ##",
        "#    $ #",
        "##     #",
        "#*  *  #",
        "#  +   #",
        "########"
      ];
      const W = 8;
      const H = 7;
    
      const board = document.getElementById("board");
      const stepsEl = document.getElementById("steps");
      const pushesEl = document.getElementById("pushes");
      const statusEl = document.getElementById("status");
      const restartEl = document.getElementById("restart");
    
      const isWall = [];
      const isGoal = [];
      for (let y = 0; y < H; y++) {
        isWall[y] = [];
        isGoal[y] = [];
        for (let x = 0; x < W; x++) {
          const ch = PAGE_LEVEL[y][x];
          isWall[y][x] = (ch === "#");
          isGoal[y][x] = (ch === "." || ch === "*" || ch === "+");
        }
      }
    
      for (let y = 0; y < H; y++) {
        for (let x = 0; x < W; x++) {
          const cell = document.createElement("div");
          cell.setAttribute("role", "img");
          cell.dataset.x = x;
          cell.dataset.y = y;
          board.appendChild(cell);
        }
      }
    
      const cells = board.children;
    
      function glyphFor(label) {
        switch (label) {
          case "wall": return "█";
          case "empty goal": return "·";
          case "box": return "■";
          case "box on a goal": return "⊠";
          case "you": return "☺";
          case "you on a goal": return "☻";
          default: return "";
        }
      }
    
      function classFor(label) {
        switch (label) {
          case "wall": return "wall";
          case "empty floor": return "floor";
          case "empty goal": return "goal";
          case "box": return "box";
          case "box on a goal": return "box on-goal";
          case "you": return "player";
          case "you on a goal": return "player on-goal";
          default: return "";
        }
      }
    
      let game = createGame();
      let renderTimer = null;
    
      function render() {
        const s = game.state();
    
        stepsEl.textContent = String(s.steps);
        pushesEl.textContent = String(s.pushes);
    
        if (s.solved) {
          statusEl.textContent = "Solved in " + s.steps + " steps with " + s.pushes + " pushes";
        } else {
          statusEl.textContent = "Not solved yet";
        }
    
        const boxSet = new Set(s.boxes.map((b) => b[0] + "," + b[1]));
        const px = s.player[0];
        const py = s.player[1];
    
        for (let y = 0; y < H; y++) {
          for (let x = 0; x < W; x++) {
            const cell = cells[y * W + x];
            let label;
            if (isWall[y][x]) {
              label = "wall";
            } else if (px === x && py === y) {
              label = isGoal[y][x] ? "you on a goal" : "you";
            } else if (boxSet.has(x + "," + y)) {
              label = isGoal[y][x] ? "box on a goal" : "box";
            } else if (isGoal[y][x]) {
              label = "empty goal";
            } else {
              label = "empty floor";
            }
    
            cell.setAttribute("aria-label", label);
            cell.className = classFor(label);
            cell.textContent = glyphFor(label);
          }
        }
      }
    
      function scheduleRender() {
        if (renderTimer) clearTimeout(renderTimer);
        renderTimer = setTimeout(render, 100);
      }
    
      function performWalk(dir) {
        game.walk(dir);
        scheduleRender();
      }
    
      document.addEventListener("keydown", (event) => {
        if (event.repeat) return;
        let dir;
        switch (event.key) {
          case "ArrowUp": dir = "up"; break;
          case "ArrowDown": dir = "down"; break;
          case "ArrowLeft": dir = "left"; break;
          case "ArrowRight": dir = "right"; break;
          default: return;
        }
        event.preventDefault();
        performWalk(dir);
      });
    
      document.querySelectorAll('button[data-dir]').forEach((button) => {
        button.addEventListener("click", () => {
          performWalk(button.dataset.dir);
        });
      });
    
      restartEl.addEventListener("click", () => {
        game = createGame();
        scheduleRender();
      });
    
      render();
    })();
    </script>
    </body>
    </html>
  • MinesweeperPassed

    20,092 tokens: 1,439 read, 18,653 written · 2 min 6 s · 148 tok/s

    Build Minesweeper as one web page: a 9 by 9 board with 10 mines, in the layout below, with the board drawn on the page.
    
    In <script id="game">, define createGame() returning an object with press(move) and state(). The site plays the game more than once, calling createGame() again each time, so every game starts from the layout. move is an array [kind, row, col]: kind is "open" or "flag", row is 0 (top) to 8 (bottom), col is 0 (left) to 8 (right). state() returns {cells, status, mines_left}: cells is 9 strings of 9 characters, one per row from the top. A character is "#" for a hidden cell, "F" for a flagged cell, "." for an opened cell with no mines around it, "1" to "8" for an opened cell with that many mines among the 8 cells around it, and "*" for a mine after a loss. status is "playing", "won" or "lost". mines_left is 10 minus the number of flagged cells, and can be negative.
    
    The mines, row by row from the top. In this layout * is a mine and . is a safe cell.
    row 0  .........
    row 1  ..***..*.
    row 2  *...*....
    row 3  ...*.....
    row 4  .........
    row 5  .........
    row 6  ......*..
    row 7  .*.......
    row 8  ........*
    
    The rules, exactly:
    1. The game starts with every cell hidden, no flags, and status "playing".
    2. press(["open", r, c]) on a hidden cell opens it. If it is a mine, status becomes "lost" and every mine shows "*", flagged or not. Otherwise the cell shows its number, or "." when no mine is among the cells around it.
    3. An opened cell with no mines around it also opens each hidden, unflagged cell around it (8 directions). Each of those with no mines around it opens its own hidden, unflagged neighbours the same way, repeatedly, until nothing more opens. A flagged cell is never opened this way, and nothing spreads from it. A numbered cell opens, but nothing spreads from it.
    4. press(["open", r, c]) on a flagged cell or an opened cell does nothing.
    5. press(["flag", r, c]) on a hidden cell flags it. On a flagged cell it removes the flag, and the cell is hidden again. On an opened cell it does nothing.
    6. status becomes "won" when every cell without a mine is opened, however the last cell is opened. A flag does not count: a flagged cell without a mine must be unflagged and opened. After a win every mine shows "F" and counts as flagged, whether or not the player flagged it, so mines_left is 0.
    7. Once status is "won" or "lost", press does nothing.
    After a loss a flag still counts in mines_left, even on a mine that shows "*", and a flag on a safe cell still shows "F".
    
    The page: a title, a short paragraph of rules, then one white panel holding a status line, a Flag mode button and the board, on a warm off-white page. The type is the system sans-serif (font-family: system-ui, sans-serif); load no font. Give these parts these names, so the site can read them:
    - an element with role="status": it shows "Mines left" and mines_left as a number, with a minus sign when it is below zero, then the status word, "Playing", "Won" (green) or "Lost" (red);
    - a button with id="flag-mode": it starts with the text "Flag mode: off" and aria-pressed="false". When it is on, its text is "Flag mode: on", aria-pressed="true", and it is drawn in the pink accent;
    - the board, which is either 81 cell buttons, each with data-row (0 at the top to 8) and data-col (0 at the left to 8), or one canvas that draws all of it, with the id board: 324 pixels across and down (set its width and height attributes), nine squares of 36 pixels each way, row 0 at the top and column 0 at the left. On a canvas, a click or a right-click acts on the square under the pointer: find the square from the event's offsetX and offsetY, each scaled by the canvas's width over its clientWidth (or its height over its clientHeight), since a phone may draw the canvas smaller.
    A click on a cell calls press(["open", row, col]) for that cell, unless Flag mode is on: then it calls press(["flag", row, col]). A right-click on a cell (the contextmenu event) calls press(["flag", row, col]) and prevents the browser's own menu. Draw the board from state() after every press: a hidden or empty cell shows no text, a numbered cell shows its number, and a flag or a mine shows a mark with text in it (a symbol, or a word hidden from sight). On a canvas, clear the whole canvas and draw it again after every press, the cells in reading order (row 0 first, columns left to right): a numbered cell as its number in text, a flag or a mine as one short mark in text (F, *, or another plain symbol), and a hidden or empty cell as nothing; the canvas draws nothing else. Flags and mines are simple marks, not emoji. The page fits a phone with no sideways scrolling. A reload of the page starts a new game: every cell is hidden, no flag is set, Flag mode is off and the status reads "Playing", so nothing from the last load is kept. The keyboard is welcome but not checked: Tab moves between cells, Enter or Space opens one, and F flags it.
    The page runs its own code only: no eval, no Function(), no timer given as text, and no network request (fetch, XMLHttpRequest, WebSocket, EventSource, sendBeacon or importScripts). It loads nothing from another site.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    ```html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minesweeper</title>
    <style>
      * { box-sizing: border-box; }
      body {
        font-family: system-ui, sans-serif;
        background: #fdf8e8;
        margin: 0;
        padding: 16px;
        line-height: 1.5;
        overflow-x: hidden;
      }
      h1 {
        font-size: 1.5rem;
        margin: 0 0 8px 0;
        text-align: center;
      }
      p {
        text-align: center;
        color: #444;
        margin: 0 0 16px 0;
      }
      .panel {
        background: white;
        padding: 16px;
        border-radius: 12px;
        max-width: 360px;
        margin: 0 auto;
      }
      [role="status"] {
        font-size: 1.1rem;
        text-align: center;
        margin-bottom: 12px;
        padding: 6px;
      }
      [role="status"] .won { color: #198754; }
      [role="status"] .lost { color: #dc3545; }
      #flag-mode {
        font-family: inherit;
        font-size: 1rem;
        padding: 6px 12px;
        cursor: pointer;
        display: block;
        margin: 0 auto 12px auto;
        border: 1px solid #999;
        background: #fff;
      }
      #flag-mode[aria-pressed="true"] {
        color: #d63384;
        border-color: #d63384;
      }
      #board {
        display: block;
        margin: 0 auto;
        width: 100%;
        max-width: 324px;
        height: auto;
        aspect-ratio: 1 / 1;
        cursor: pointer;
        touch-action: none;
        background: transparent;
      }
    </style>
    </head>
    <body>
    <h1>Minesweeper</h1>
    <p>Open all safe cells without opening a mine. Use Flag mode or right-click to mark mines.</p>
    <div class="panel">
      <div role="status" id="status">Mines left 10 <span class="">Playing</span></div>
      <button id="flag-mode" aria-pressed="false">Flag mode: off</button>
      <canvas id="board" width="324" height="324"></canvas>
    </div>
    
    <script id="game">
    function createGame() {
      const N = 9;
      const MINE_COUNT = 10;
      const layout = [
        ".........",
        "..***..*.",
        "*...*....",
        "...*.....",
        ".........",
        ".........",
        "......*..",
        ".*.......",
        "........*"
      ];
    
      const mine = [];
      const revealed = [];
      const flagged = [];
      for (let r = 0; r < N; r++) {
        mine[r] = [];
        revealed[r] = [];
        flagged[r] = [];
        for (let c = 0; c < N; c++) {
          mine[r][c] = layout[r][c] === "*";
          revealed[r][c] = false;
          flagged[r][c] = false;
        }
      }
    
      let status = "playing";
    
      function countMines(r, c) {
        let n = 0;
        for (let dr = -1; dr <= 1; dr++) {
          for (let dc = -1; dc <= 1; dc++) {
            if (dr === 0 && dc === 0) continue;
            const rr = r + dr;
            const cc = c + dc;
            if (rr >= 0 && rr < N && cc >= 0 && cc < N && mine[rr][cc]) {
              n++;
            }
          }
        }
        return n;
      }
    
      function reveal(r, c) {
        if (revealed[r][c] || flagged[r][c]) return;
        revealed[r][c] = true;
        if (countMines(r, c) === 0) {
          const stack = [[r, c]];
          while (stack.length > 0) {
            const [cr, cc] = stack.pop();
            for (let dr = -1; dr <= 1; dr++) {
              for (let dc = -1; dc <= 1; dc++) {
                if (dr === 0 && dc === 0) continue;
                const nr = cr + dr;
                const nc = cc + dc;
                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;
                if (revealed[nr][nc] || flagged[nr][nc]) continue;
                revealed[nr][nc] = true;
                if (countMines(nr, nc) === 0) {
                  stack.push([nr, nc]);
                }
              }
            }
          }
        }
      }
    
      function checkWin() {
        for (let r = 0; r < N; r++) {
          for (let c = 0; c < N; c++) {
            if (!mine[r][c] && !revealed[r][c]) {
              return false;
            }
          }
        }
        return true;
      }
    
      function countFlagged() {
        let n = 0;
        for (let r = 0; r < N; r++) {
          for (let c = 0; c < N; c++) {
            if (flagged[r][c]) n++;
          }
        }
        return n;
      }
    
      function cellChar(r, c) {
        if (status === "won") {
          if (mine[r][c]) return "F";
          const n = countMines(r, c);
          return n === 0 ? "." : String(n);
        }
        if (status === "lost") {
          if (mine[r][c]) return "*";
          if (flagged[r][c]) return "F";
          if (revealed[r][c]) {
            const n = countMines(r, c);
            return n === 0 ? "." : String(n);
          }
          return "#";
        }
        if (flagged[r][c]) return "F";
        if (revealed[r][c]) {
          const n = countMines(r, c);
          return n === 0 ? "." : String(n);
        }
        return "#";
      }
    
      return {
        press(move) {
          if (status !== "playing") return;
          const kind = move[0];
          const r = move[1];
          const c = move[2];
          if (r < 0 || r >= N || c < 0 || c >= N) return;
          if (kind === "open") {
            if (flagged[r][c] || revealed[r][c]) return;
            if (mine[r][c]) {
              status = "lost";
              return;
            }
            reveal(r, c);
            if (checkWin()) status = "won";
          } else if (kind === "flag") {
            if (revealed[r][c]) return;
            flagged[r][c] = !flagged[r][c];
          }
        },
        state() {
          const cells = [];
          for (let r = 0; r < N; r++) {
            let row = "";
            for (let c = 0; c < N; c++) {
              row += cellChar(r, c);
            }
            cells.push(row);
          }
          let mines_left = MINE_COUNT - countFlagged();
          if (status === "won") mines_left = 0;
          return { cells, status, mines_left };
        }
      };
    }
    </script>
    
    <script>
    (function() {
      const game = createGame();
      const statusEl = document.getElementById("status");
      const flagBtn = document.getElementById("flag-mode");
      const canvas = document.getElementById("board");
      const ctx = canvas.getContext("2d");
    
      let flagMode = false;
    
      function render() {
        const { cells, status, mines_left } = game.state();
        let word = "Playing";
        let cls = "";
        if (status === "won") { word = "Won"; cls = "won"; }
        else if (status === "lost") { word = "Lost"; cls = "lost"; }
    
        statusEl.innerHTML = "Mines left " + mines_left + " <span class=\"" + cls + "\">" + word + "</span>";
    
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.font = "24px system-ui, sans-serif";
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
    
        for (let r = 0; r < 9; r++) {
          const row = cells[r];
          for (let c = 0; c < 9; c++) {
            const ch = row[c];
            if (ch === "#" || ch === ".") continue;
            const x = (c + 0.5) * 36;
            const y = (r + 0.5) * 36;
            if (ch === "F") {
              ctx.fillStyle = "#d63384";
            } else if (ch === "*") {
              ctx.fillStyle = "#000000";
            } else {
              ctx.fillStyle = "#1a1a1a";
            }
            ctx.fillText(ch, x, y);
          }
        }
      }
    
      function cellFromEvent(event) {
        const rect = canvas.getBoundingClientRect();
        const scaleX = canvas.width / rect.width;
        const scaleY = canvas.height / rect.height;
        const x = event.offsetX * scaleX;
        const y = event.offsetY * scaleY;
        let col = Math.floor(x / 36);
        let row = Math.floor(y / 36);
        if (col < 0) col = 0;
        if (col > 8) col = 8;
        if (row < 0) row = 0;
        if (row > 8) row = 8;
        return [row, col];
      }
    
      canvas.addEventListener("click", function(event) {
        if (game.state().status !== "playing") return;
        const [r, c] = cellFromEvent(event);
        if (flagMode) {
          game.press(["flag", r, c]);
        } else {
          game.press(["open", r, c]);
        }
        render();
      });
    
      canvas.addEventListener("contextmenu", function(event) {
        event.preventDefault();
        if (game.state().status !== "playing") return;
        const [r, c] = cellFromEvent(event);
        game.press(["flag", r, c]);
        render();
      });
    
      flagBtn.addEventListener("click", function() {
        flagMode = !flagMode;
        flagBtn.setAttribute("aria-pressed", flagMode ? "true" : "false");
        flagBtn.textContent = flagMode ? "Flag mode: on" : "Flag mode: off";
      });
    
      render();
    })();
    </script>
    </body>
    </html>
    ```
Building apps 3 of 4
  • Step sequencerFailed

    19,251 tokens: 1,322 read, 17,929 written · 1 min 53 s · 159 tok/s

    Build a web page called "Step sequencer": three rows labelled Kick, Snare and Hat, of 16 step buttons each, a Play button and a Stop button, and drums made with the Web Audio API, with no sound files.
    
    In <script id="game">, define createGame() returning an object with press(cmd) and state(). The page calls createGame() at load or on the first press. The logic keeps the pattern, whether it is playing, the playhead and the hits. The page makes the sound. Do not use eval or Function, and never run text as code: give a timer a function, not a string.
    
    The starting pattern, one row per track. Steps are numbered from 1 in the rows below: each row is 16 characters, 1 for on and 0 for off. The first character is step 1 on the page and step 0 for press():
    kick   1000100010001000
    snare  0000100100001001
    hat    1010101010101110
    
    The rules, exactly:
    1. At the start, playing is false, playhead is 0 and hits is [].
    2. press([track, step]) toggles one cell: track 0 is kick, 1 snare, 2 hat; step is 0 to 15, where 0 is the first step. Toggling changes the pattern and nothing else.
    3. press('play') does nothing when playing is already true. Otherwise it sets playing to true, and hits becomes the list of track numbers (0 kick, 1 snare, 2 hat) whose cell at the playhead is 1, in ascending order ([] when there are none). So the step under the playhead sounds as play starts.
    4. press('stop') sets playing to false, playhead to 0 and hits to [].
    5. press('tick') does nothing unless playing is true. When it is, playhead goes on by one, and after 15 it goes back to 0. hits becomes the list of track numbers whose cell at the new playhead is 1, in ascending order ([] when there are none).
    6. Any other cmd does nothing: a list that is not exactly two whole numbers (such as [0, 1, 2], [1], [] or [true, 0]), null, a number, true or false, a word other than play, stop or tick, and a track or step outside the ranges above.
    Track and step are whole numbers.
    
    state() returns {playing, playhead, hits, pattern}: playing is true or false; playhead is 0 to 15; hits lists the track numbers set by the last tick or by the play that started playback, in ascending order ([] at the start and after stop); pattern is three strings of 16 characters, kick first, each character 1 or 0.
    
    The page:
    - Each step button is a real button with the attributes data-track (0, 1 or 2) and data-step (0 to 15), and aria-pressed set to true or false to match its state. A click calls press([track, step]), and after every press, the page draws from state().
    - A step that is on has the class on, and the stylesheet fills it dark; a step that is off has no class on.
    - Play has the id play and Stop the id stop. Play calls press('play') and starts one timer that calls press('tick') every 125 ms: 120 quarter-note beats a minute, four steps to a beat. Stop calls press('stop') and clears the timer. Each play and each tick sounds the hits that state() then reports, and nothing else sounds.
    - Play has the disabled attribute while playing, and Stop has it while stopped.
    - A status line with the id status reads "Stopped", or "Playing, step N of 16" with N the playhead plus 1. Give it a fixed height, so the grid does not move when its text changes.
    - A span with the id announce, set to aria-live polite, is empty until playback starts for the first time. From then on it says "Playing" when playback starts and "Stopped" when it stops, and changes at no other time.
    - The cells in the playhead column have the class playhead while playing, and no cell has it while stopped.
    - The numbers 1 to 16, as text, sit above the grid, and the playhead's number is pink. Under 720 px each step shows its number.
    - When the page becomes hidden, it presses Stop, so nothing sounds in a background tab.
    - Each track in hits plays its drum: kick is a falling sine tone, snare a short noise burst with a low body tone, hat a short high noise burst. Tones use oscillators; noise bursts use buffer sources playing a buffer of random samples: the kick is one oscillator, the snare one buffer source and one oscillator, the hat one buffer source. Hits that land together must not clip, so put a gain or a limiter before the output. Create the AudioContext inside the first click (browsers need a click before they make sound), and resume it if it is suspended.
    - Flat and plain: a light background, dark ink, no shadows or gradients, Play the one pink button (#b31f57), and the playhead cell outlined in pink where you are. At 1280 px the 16 steps sit in one row; under 720 px they form two bars of 8. The page never scrolls sideways.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and drives the sequencer through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Step sequencer</title>
    <style>
    * { box-sizing: border-box; }
    body {
      margin: 0;
      padding: 16px;
      background: #f5f5f5;
      color: #111;
      font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
      overflow-x: hidden;
    }
    h1 { margin: 0 0 12px; font-size: 1.25rem; }
    #controls {
      display: flex;
      gap: 8px;
      align-items: center;
      flex-wrap: wrap;
      margin-bottom: 12px;
    }
    button {
      border: 1px solid #111;
      background: #fff;
      color: #111;
      padding: 6px 14px;
      font-size: 1rem;
      cursor: pointer;
    }
    button:disabled { opacity: 0.5; cursor: not-allowed; }
    #play {
      background: #b31f57;
      color: #fff;
      border-color: #b31f57;
    }
    #play:disabled { opacity: 0.7; }
    #status {
      margin-left: auto;
      min-width: 210px;
      height: 1.2em;
      font-weight: 600;
    }
    #announce { margin-left: 10px; }
    #sequencer { max-width: 960px; margin: 0 auto; }
    #number-bar {
      display: grid;
      grid-template-columns: repeat(16, 1fr);
      gap: 4px;
      margin-bottom: 6px;
    }
    #number-bar span {
      text-align: center;
      font-size: 0.8rem;
    }
    #number-bar span.current { color: #b31f57; font-weight: bold; }
    .track {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
    }
    .track-label {
      width: 52px;
      text-align: right;
      font-size: 0.9rem;
      flex-shrink: 0;
    }
    .steps {
      display: grid;
      grid-template-columns: repeat(16, 1fr);
      gap: 4px;
      flex: 1;
    }
    .steps button {
      height: 44px;
      border: 1px solid #111;
      background: #ddd;
      padding: 0;
      font-size: 0;
      cursor: pointer;
    }
    .steps button.on { background: #333; }
    .steps button.playhead { outline: 3px solid #b31f57; }
    @media (max-width: 719px) {
      #number-bar { display: none; }
      .steps { grid-template-columns: repeat(8, 1fr); }
      .steps button { font-size: 0.7rem; }
    }
    </style>
    </head>
    <body>
    <h1>Step sequencer</h1>
    <div id="controls">
      <button id="play">Play</button>
      <button id="stop">Stop</button>
      <div id="status">Stopped</div>
      <span id="announce" aria-live="polite"></span>
    </div>
    <div id="sequencer">
      <div id="number-bar"></div>
      <div id="grid"></div>
    </div>
    
    <script id="game">
    function createGame() {
      const pattern = [
        '1000100010001000'.split('').map(Number),
        '0000100100001001'.split('').map(Number),
        '1010101010101110'.split('').map(Number)
      ];
      let playing = false;
      let playhead = 0;
      let hits = [];
    
      function hitsAt(head) {
        const out = [];
        for (let t = 0; t < 3; t++) {
          if (pattern[t][head] === 1) out.push(t);
        }
        return out;
      }
    
      return {
        press(cmd) {
          if (Array.isArray(cmd) && cmd.length === 2) {
            const track = cmd[0];
            const step = cmd[1];
            if (
              Number.isInteger(track) && Number.isInteger(step) &&
              track >= 0 && track <= 2 &&
              step >= 0 && step <= 15
            ) {
              pattern[track][step] = pattern[track][step] === 1 ? 0 : 1;
            }
            return;
          }
          if (cmd === 'play') {
            if (playing) return;
            playing = true;
            hits = hitsAt(playhead);
            return;
          }
          if (cmd === 'stop') {
            playing = false;
            playhead = 0;
            hits = [];
            return;
          }
          if (cmd === 'tick') {
            if (!playing) return;
            playhead = (playhead + 1) % 16;
            hits = hitsAt(playhead);
            return;
          }
        },
        state() {
          return {
            playing,
            playhead,
            hits: hits.slice(),
            pattern: pattern.map(row => row.join(''))
          };
        }
      };
    }
    </script>
    
    <script>
    (function() {
      const tracks = ['Kick', 'Snare', 'Hat'];
      const grid = document.getElementById('grid');
      const numberBar = document.getElementById('number-bar');
    
      for (let i = 0; i < 16; i++) {
        const span = document.createElement('span');
        span.dataset.step = i;
        span.textContent = i + 1;
        numberBar.appendChild(span);
      }
    
      for (let t = 0; t < 3; t++) {
        const track = document.createElement('div');
        track.className = 'track';
        const label = document.createElement('div');
        label.className = 'track-label';
        label.textContent = tracks[t];
        const steps = document.createElement('div');
        steps.className = 'steps';
        for (let s = 0; s < 16; s++) {
          const btn = document.createElement('button');
          btn.type = 'button';
          btn.dataset.track = t;
          btn.dataset.step = s;
          btn.textContent = s + 1;
          btn.setAttribute('aria-pressed', 'false');
          steps.appendChild(btn);
        }
        track.appendChild(label);
        track.appendChild(steps);
        grid.appendChild(track);
      }
    
      let game = null;
      let timer = null;
      let started = false;
      let ctx = null;
      let master = null;
      let noiseHat = null;
      let noiseSnare = null;
    
      function ensureGame() {
        if (!game) game = createGame();
      }
    
      function ensureAudio() {
        if (ctx) return ctx;
        const Ctor = window.AudioContext || window.webkitAudioContext;
        if (!Ctor) return null;
        ctx = new Ctor();
        if (ctx.state === 'suspended') ctx.resume();
        master = ctx.createGain();
        master.gain.value = 0.4;
        master.connect(ctx.destination);
    
        const hatLen = Math.ceil(ctx.sampleRate * 0.05);
        noiseHat = ctx.createBuffer(1, hatLen, ctx.sampleRate);
        {
          const d = noiseHat.getChannelData(0);
          for (let i = 0; i < hatLen; i++) d[i] = Math.random() * 2 - 1;
        }
        const snareLen = Math.ceil(ctx.sampleRate * 0.1);
        noiseSnare = ctx.createBuffer(1, snareLen, ctx.sampleRate);
        {
          const d = noiseSnare.getChannelData(0);
          for (let i = 0; i < snareLen; i++) d[i] = Math.random() * 2 - 1;
        }
        return ctx;
      }
    
      function playKick(now) {
        const osc = ctx.createOscillator();
        const g = ctx.createGain();
        osc.type = 'sine';
        osc.frequency.setValueAtTime(150, now);
        osc.frequency.exponentialRampToValueAtTime(30, now + 0.2);
        g.gain.setValueAtTime(0.6, now);
        g.gain.exponentialRampToValueAtTime(0.001, now + 0.2);
        osc.connect(g);
        g.connect(master);
        osc.start(now);
        osc.stop(now + 0.2);
      }
    
      function playSnare(now) {
        const noise = ctx.createBufferSource();
        noise.buffer = noiseSnare;
        const g = ctx.createGain();
        g.gain.setValueAtTime(0.4, now);
        g.gain.exponentialRampToValueAtTime(0.001, now + 0.1);
        noise.connect(g);
        g.connect(master);
        noise.start(now);
        noise.stop(now + 0.1);
    
        const osc = ctx.createOscillator();
        const og = ctx.createGain();
        osc.type = 'sine';
        osc.frequency.setValueAtTime(120, now);
        osc.frequency.exponentialRampToValueAtTime(50, now + 0.15);
        og.gain.setValueAtTime(0.4, now);
        og.gain.exponentialRampToValueAtTime(0.001, now + 0.15);
        osc.connect(og);
        og.connect(master);
        osc.start(now);
        osc.stop(now + 0.15);
      }
    
      function playHat(now) {
        const noise = ctx.createBufferSource();
        noise.buffer = noiseHat;
        const g = ctx.createGain();
        g.gain.setValueAtTime(0.3, now);
        g.gain.exponentialRampToValueAtTime(0.001, now + 0.05);
        noise.connect(g);
        g.connect(master);
        noise.start(now);
        noise.stop(now + 0.05);
      }
    
      function playDrum(track) {
        if (!ctx) ensureAudio();
        if (!ctx) return;
        const now = ctx.currentTime;
        if (track === 0) playKick(now);
        else if (track === 1) playSnare(now);
        else if (track === 2) playHat(now);
      }
    
      function soundHits(hits) {
        hits.forEach(t => playDrum(t));
      }
    
      function draw() {
        const s = game.state();
        document.querySelectorAll('.steps button').forEach(btn => {
          const t = +btn.dataset.track;
          const st = +btn.dataset.step;
          const on = s.pattern[t][st] === '1';
          btn.classList.toggle('on', on);
          btn.setAttribute('aria-pressed', on ? 'true' : 'false');
          btn.classList.toggle('playhead', s.playing && st === s.playhead);
        });
        document.querySelectorAll('#number-bar span').forEach(span => {
          const st = +span.dataset.step;
          span.classList.toggle('current', s.playing && st === s.playhead);
        });
        document.getElementById('status').textContent = s.playing
          ? 'Playing, step ' + (s.playhead + 1) + ' of 16'
          : 'Stopped';
        document.getElementById('play').disabled = s.playing;
        document.getElementById('stop').disabled = !s.playing;
      }
    
      document.getElementById('play').addEventListener('click', function() {
        ensureAudio();
        ensureGame();
        game.press('play');
        const s = game.state();
        soundHits(s.hits);
        draw();
        if (!timer) {
          timer = setInterval(function() {
            game.press('tick');
            const s2 = game.state();
            soundHits(s2.hits);
            draw();
          }, 125);
        }
        if (!started) {
          started = true;
          document.getElementById('announce').textContent = 'Playing';
        }
      });
    
      document.getElementById('stop').addEventListener('click', function() {
        ensureGame();
        game.press('stop');
        if (timer) {
          clearInterval(timer);
          timer = null;
        }
        draw();
        document.getElementById('announce').textContent = 'Stopped';
      });
    
      document.querySelectorAll('.steps button').forEach(function(btn) {
        btn.addEventListener('click', function() {
          ensureAudio();
          ensureGame();
          const t = +btn.dataset.track;
          const s = +btn.dataset.step;
          game.press([t, s]);
          draw();
        });
      });
    
      document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
          ensureGame();
          game.press('stop');
          if (timer) {
            clearInterval(timer);
            timer = null;
          }
          draw();
          document.getElementById('announce').textContent = 'Stopped';
        }
      });
    
      ensureGame();
      draw();
    })();
    </script>
    </body>
    </html>
  • Grow a branching plantPassed

    19,153 tokens: 1,253 read, 17,900 written · 2 min 15 s · 132 tok/s

    Build a plant that grows by a rewrite rule (an L-system) as one web page: a heading, a canvas that draws the plant, a Grow button and a Reset button.
    
    In <script id="game">, define createGame() returning an object with grow() and state(). grow() takes no argument. state() returns {generation, text, segments}: generation is a number, text is a string, and segments is a list with one [x1, y1, x2, y2] entry for each F in text, in the order the Fs appear in text. [x1, y1] is the cell a segment starts from and [x2, y2] the cell it ends on.
    
    The rules, exactly:
    1. A pen starts at [0, 0] facing north, which is heading 6. Headings are numbered 0 to 7 clockwise, each one a step [dx, dy] with y growing downward: 0 [1, 0] east, 1 [1, 1] south-east, 2 [0, 1] south, 3 [-1, 1] south-west, 4 [-1, 0] west, 5 [-1, -1] north-west, 6 [0, -1] north, 7 [1, -1] north-east.
    2. The text starts as F, at generation 0. The pen reads the text from left to right. F moves the pen one step along its heading and adds the segment [x1, y1, x2, y2] for that step. + adds 1 to the heading and - subtracts 1, both modulo 8. [ saves the pen's position and heading. ] restores the last saved position and heading and forgets them. Any other symbol does nothing.
    3. grow() rewrites the text in one pass: every F becomes F[[++F[+F]]-F[--F]]F, and every other symbol stays as it is. The Fs that the rule adds are not rewritten in that pass. Then generation goes up by 1.
    4. segments is what the pen draws over the new text, starting again at [0, 0] facing north, as in rule 1.
    5. At the start, generation is 0, text is "F" and segments is [[0, 0, 0, -1]].
    6. grow() at generation 4 changes nothing: generation, text and segments stay as they are.
    
    The site calls grow() five times in a row, and reads state() before the first call and after each call, so every state must match these rules. The fifth call is made at generation 4. Keep the rule in the game script as one string, written exactly as rule 3 gives it: the site also runs the script with another rule in its place, and its states must follow that rule.
    
    The page: a heading (an <h1>) reading exactly "Grow a branching plant". Below it, one canvas draws each segment as a line from its start point to its end point, with the context's own moveTo, lineTo and stroke (not Path2D). The canvas draws nothing else: no other shapes, no text and no images. The drawing has the shape the segments give, with north up on the canvas: one scale on both axes, fitted to the canvas and centred. Each drawing starts by clearing the whole canvas (clearRect over all of it, or setting the canvas's width), so only the new plant is on it. Each press of Grow draws the whole plant again, at once, with one lineTo for each segment: no animation frames and no delays. The plant is drawn when the page loads, and Reset draws the stem again within a tenth of a second.
    Grow is a <button id="grow"> reading exactly "Grow". A press calls grow(), then draws and shows the new state, and Grow is disabled at generation 4. Reset is a <button id="reset"> reading exactly "Reset". A press calls createGame() for a new plant, draws it, and enables Grow again. Wire both with addEventListener('click', ...).
    A status line, an element with role="status", reads "Generation g of 4, n segments", where g is the generation and n the number of segments (the word is "segment" when n is 1), and it changes after each press.
    
    Look: plain and tidy, like a small app. A light, warm off-white page, the canvas in a white card with a thin border, the plant in dark ink, Grow as the main button and Reset as an outlined button under the card. The page must work at 390 px and at 1280 px wide with no sideways scrolling.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not use document, window, localStorage, sessionStorage or any timer, because the site runs that script on its own and plays the game through createGame(). The script is at most 20,000 characters. Wire the page in another <script>. Neither script may use eval or Function, reach Function through a constructor, or give a timer text to run; and neither may read window, self, globalThis, top, parent, frames or this with square brackets. A constructor() method in a class is fine, and so is a constructor key in an object; reading a constructor property, as x.constructor or x['constructor'], is not. A timer is given a function: one written in the call, or one the page declares by name. Square brackets take a number or a name, never quoted text, and window is used only as window.name.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grow a branching plant</title>
    <style>
      body {
        background: #faf6f0;
        color: #222;
        font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        margin: 0;
        padding: 16px;
        box-sizing: border-box;
      }
      h1 {
        font-size: 1.5rem;
        margin: 0 0 16px;
        text-align: center;
      }
      .card {
        background: #fff;
        border: 1px solid #c9b8a8;
        border-radius: 8px;
        padding: 16px;
        max-width: 100%;
        box-sizing: border-box;
      }
      canvas {
        display: block;
        width: 100%;
        height: auto;
        background: #fff;
        border-radius: 4px;
      }
      .controls {
        margin-top: 12px;
        text-align: center;
      }
      button {
        font-family: inherit;
        font-size: 1rem;
        padding: 8px 14px;
        border-radius: 6px;
        cursor: pointer;
      }
      #grow {
        background: #8a6d3b;
        color: #fff;
        border: none;
      }
      #grow:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }
      #reset {
        background: transparent;
        color: #8a6d3b;
        border: 1px solid #8a6d3b;
        margin-top: 8px;
        display: inline-block;
      }
      [role="status"] {
        margin-top: 10px;
        text-align: center;
        font-size: 0.95rem;
        color: #555;
      }
    </style>
    </head>
    <body>
    <h1>Grow a branching plant</h1>
    <div class="card">
    <canvas id="canvas" width="600" height="600"></canvas>
    </div>
    <div class="controls">
    <button id="grow">Grow</button>
    <button id="reset">Reset</button>
    </div>
    <div role="status">Generation 0 of 4, 1 segment</div>
    <script id="game">
    function createGame() {
      const headings = [
        [1, 0], [1, 1], [0, 1], [-1, 1],
        [-1, 0], [-1, -1], [0, -1], [1, -1]
      ];
      const RULE = "F[[++F[+F]]-F[--F]]F";
      let generation = 0;
      let text = "F";
      let segments = [[0, 0, 0, -1]];
    
      function interpret(t) {
        let x = 0;
        let y = 0;
        let h = 6;
        const stack = [];
        const out = [];
        const n = t.length;
        for (let i = 0; i < n; i++) {
          const c = t[i];
          if (c === "F") {
            const step = headings[h];
            const x2 = x + step[0];
            const y2 = y + step[1];
            out.push([x, y, x2, y2]);
            x = x2;
            y = y2;
          } else if (c === "+") {
            h = (h + 1) % 8;
          } else if (c === "-") {
            h = (h + 7) % 8;
          } else if (c === "[") {
            stack.push([x, y, h]);
          } else if (c === "]") {
            const s = stack.pop();
            if (s !== undefined) {
              x = s[0];
              y = s[1];
              h = s[2];
            }
          }
        }
        return out;
      }
    
      return {
        grow: function () {
          if (generation === 4) {
            return;
          }
          let next = "";
          const m = text.length;
          for (let i = 0; i < m; i++) {
            if (text[i] === "F") {
              next += RULE;
            } else {
              next += text[i];
            }
          }
          text = next;
          generation += 1;
          segments = interpret(text);
        },
        state: function () {
          return {
            generation: generation,
            text: text,
            segments: segments.slice()
          };
        }
      };
    }
    </script>
    <script>
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
    const growBtn = document.getElementById("grow");
    const resetBtn = document.getElementById("reset");
    const statusEl = document.querySelector('[role="status"]');
    
    let game = createGame();
    
    function updateStatus() {
      const state = game.state();
      const n = state.segments.length;
      const word = n === 1 ? "segment" : "segments";
      statusEl.textContent = "Generation " + state.generation + " of 4, " + n + " " + word;
      growBtn.disabled = state.generation >= 4;
    }
    
    function draw() {
      const state = game.state();
      const segs = state.segments;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    
      if (segs.length === 0) {
        updateStatus();
        return;
      }
    
      let minX = Infinity;
      let maxX = -Infinity;
      let minY = Infinity;
      let maxY = -Infinity;
      for (let i = 0; i < segs.length; i++) {
        const seg = segs[i];
        const x1 = seg[0];
        const y1 = seg[1];
        const x2 = seg[2];
        const y2 = seg[3];
        if (x1 < minX) minX = x1;
        if (x2 < minX) minX = x2;
        if (x1 > maxX) maxX = x1;
        if (x2 > maxX) maxX = x2;
        if (y1 < minY) minY = y1;
        if (y2 < minY) minY = y2;
        if (y1 > maxY) maxY = y1;
        if (y2 > maxY) maxY = y2;
      }
    
      const width = maxX - minX;
      const height = maxY - minY;
      const canvasW = canvas.width;
      const canvasH = canvas.height;
      const margin = 10;
      let scaleX = width === 0 ? Infinity : (canvasW - 2 * margin) / width;
      let scaleY = height === 0 ? Infinity : (canvasH - 2 * margin) / height;
      let scale = Math.min(scaleX, scaleY);
      if (scale === Infinity) {
        scale = 1;
      }
    
      const centerX = (minX + maxX) / 2;
      const centerY = (minY + maxY) / 2;
      const cx = canvasW / 2;
      const cy = canvasH / 2;
    
      ctx.strokeStyle = "#1a1a1a";
      ctx.lineWidth = 2;
      ctx.beginPath();
      for (let i = 0; i < segs.length; i++) {
        const seg = segs[i];
        const sx1 = cx + (seg[0] - centerX) * scale;
        const sy1 = cy + (seg[1] - centerY) * scale;
        const sx2 = cx + (seg[2] - centerX) * scale;
        const sy2 = cy + (seg[3] - centerY) * scale;
        ctx.moveTo(sx1, sy1);
        ctx.lineTo(sx2, sy2);
      }
      ctx.stroke();
    
      updateStatus();
    }
    
    growBtn.addEventListener("click", function () {
      game.grow();
      draw();
    });
    
    resetBtn.addEventListener("click", function () {
      game = createGame();
      draw();
    });
    
    draw();
    </script>
    </body>
    </html>
  • Falling sandPassed

    20,731 tokens: 1,168 read, 19,563 written · 2 min 10 s · 151 tok/s

    Build a page called Falling sand: a 40 by 30 board drawn on a canvas. Sand falls one frame at a time and slides off the edges of piles. Pressing or dragging on the board pours sand, Play runs the frames, and Step runs one.
    
    In <script id="game">, define createGame(). It returns an object with play(move) and state(). move is "step" (run one frame) or [x, y] (pour one grain of sand into column x, row y). state() returns {frame, cells}: frame is the number of frames run so far (a pour is not a frame), and cells is 30 rows of 40 numbers, top row first: 0 is empty, 1 is sand, 2 is wall. Column x runs 0 to 39, left to right; row y runs 0 to 29, top to bottom.
    
    The start, exactly (both ends of each run are included):
    1. frame is 0. Row 29 is all wall.
    2. Walls: column 22, rows 15 to 19; row 22, columns 6 to 10; column 35, rows 21 to 25.
    3. Sand: column 24, row 0; row 1, columns 19 to 29; row 2, columns 18 to 30; row 3, columns 17 to 31; row 4, columns 16 to 32; row 5, columns 17 to 31; row 6, columns 18 to 30; row 7, columns 19 to 29; column 24, row 8.
    4. Every other cell is empty.
    
    The rules, exactly:
    1. A pour [x, y] puts one grain in that cell if it is empty; a cell holding sand or wall, or outside the grid, is not empty, so the pour does nothing.
    2. A step runs one frame, using frame as it is before the step, then frame goes up by 1. A frame scans the rows from row 28 up to row 0. Within a row it scans the columns from left to right when frame is even, and from right to left when frame is odd.
    3. Each sand cell the scan reaches moves at most once: to (x, y+1) if that cell is empty; otherwise to (x-1, y+1) if that is empty; otherwise to (x+1, y+1) if that is empty; otherwise it stays. Anything outside the grid counts as wall.
    4. Each check reads the cells as they are at that moment: a grain that has moved leaves its cell empty, and a cell an earlier grain filled in this frame is not empty.
    
    The site plays a list of moves through play() and checks state() after each one. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>. Do not run a string as code: no eval, no Function (not even as a function's constructor property), no timer given a string, no javascript: address, and no script element made from text. Network requests are refused, and the game script is at most 20,000 characters.
    
    The page: a canvas with the id board and the width and height attributes 640 and 480. The board may be shown at any size and place on the page: a press or drag finds its cell from where the board is on screen not from its 640 by 480 pixels. A press on the board pours one grain into the cell under the pointer. A drag pours into every cell on the straight line from the cell the pointer left to the cell it reached, both ends included (Bresenham's line algorithm). Buttons with the ids play, step and reset. play runs one frame about every 50 ms, and its label reads Pause while it runs; pressing it again pauses, and the label reads Play. step runs one frame. reset calls createGame() again, back to the start, and stops Play if it is running. After each pour, after each frame that Play or Step runs, and after Reset, the board is cleared or filled once, then each grain of sand is drawn with fillRect in its own cell; empty cells are not drawn one by one. One line under the board, with the id status, reads "Frame N, M grains of sand" ("1 grain of sand" for one), N is the frame and M the grains.
    
    Not checked, but wanted: keyboard pouring (arrow keys move a pour cursor when the board has focus; Space or Enter pours at it); a live region with the id say that announces Play, Pause, Step and Reset; reduced motion (prefers-reduced-motion: reduce): a press of Play runs one frame; off screen, Play pauses for real (no frame runs, the label reads Play) and resumes on return only if it was playing, and a press of Play then does nothing, while Step still runs one frame.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Falling Sand</title>
    <style>
      body { font-family: system-ui, sans-serif; display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 16px; }
      #board { border: 1px solid #444; background: #faf6ec; cursor: crosshair; display: block; }
      #status { font-family: ui-monospace, monospace; font-size: 14px; }
      .controls { display: flex; gap: 8px; }
      button { padding: 6px 14px; font-size: 14px; cursor: pointer; }
      #say { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); border: 0; white-space: nowrap; }
    </style>
    </head>
    <body>
    <canvas id="board" width="640" height="480"></canvas>
    <div id="status"></div>
    <div id="say" aria-live="polite"></div>
    <div class="controls">
      <button id="play">Play</button>
      <button id="step">Step</button>
      <button id="reset">Reset</button>
    </div>
    
    <script id="game">
    function createGame() {
      const W = 40;
      const H = 30;
      let frame = 0;
      let cells = [];
    
      function init() {
        cells = [];
        for (let y = 0; y < H; y++) {
          const row = [];
          for (let x = 0; x < W; x++) row.push(0);
          cells.push(row);
        }
        for (let x = 0; x < W; x++) cells[H - 1][x] = 2;
        for (let y = 15; y <= 19; y++) cells[y][22] = 2;
        for (let x = 6; x <= 10; x++) cells[22][x] = 2;
        for (let y = 21; y <= 25; y++) cells[y][35] = 2;
        cells[0][24] = 1;
        for (let x = 19; x <= 29; x++) cells[1][x] = 1;
        for (let x = 18; x <= 30; x++) cells[2][x] = 1;
        for (let x = 17; x <= 31; x++) cells[3][x] = 1;
        for (let x = 16; x <= 32; x++) cells[4][x] = 1;
        for (let x = 17; x <= 31; x++) cells[5][x] = 1;
        for (let x = 18; x <= 30; x++) cells[6][x] = 1;
        for (let x = 19; x <= 29; x++) cells[7][x] = 1;
        cells[8][24] = 1;
      }
      init();
    
      return {
        play(move) {
          if (move === 'step') {
            const f = frame;
            const leftToRight = (f % 2 === 0);
            for (let y = H - 2; y >= 0; y--) {
              if (leftToRight) {
                for (let x = 0; x < W; x++) {
                  if (cells[y][x] === 1) {
                    if (cells[y + 1][x] === 0) {
                      cells[y][x] = 0;
                      cells[y + 1][x] = 1;
                    } else if (x > 0 && cells[y + 1][x - 1] === 0) {
                      cells[y][x] = 0;
                      cells[y + 1][x - 1] = 1;
                    } else if (x < W - 1 && cells[y + 1][x + 1] === 0) {
                      cells[y][x] = 0;
                      cells[y + 1][x + 1] = 1;
                    }
                  }
                }
              } else {
                for (let x = W - 1; x >= 0; x--) {
                  if (cells[y][x] === 1) {
                    if (cells[y + 1][x] === 0) {
                      cells[y][x] = 0;
                      cells[y + 1][x] = 1;
                    } else if (x > 0 && cells[y + 1][x - 1] === 0) {
                      cells[y][x] = 0;
                      cells[y + 1][x - 1] = 1;
                    } else if (x < W - 1 && cells[y + 1][x + 1] === 0) {
                      cells[y][x] = 0;
                      cells[y + 1][x + 1] = 1;
                    }
                  }
                }
              }
            }
            frame += 1;
          } else if (Array.isArray(move) && move.length === 2) {
            const x = move[0];
            const y = move[1];
            if (typeof x === 'number' && typeof y === 'number' &&
                x >= 0 && x < W && y >= 0 && y < H && cells[y][x] === 0) {
              cells[y][x] = 1;
            }
          }
        },
        state() {
          const copy = [];
          for (let y = 0; y < H; y++) copy.push(cells[y].slice());
          return { frame: frame, cells: copy };
        }
      };
    }
    </script>
    
    <script>
    const board = document.getElementById('board');
    const ctx = board.getContext('2d');
    const statusEl = document.getElementById('status');
    const sayEl = document.getElementById('say');
    const playBtn = document.getElementById('play');
    const stepBtn = document.getElementById('step');
    const resetBtn = document.getElementById('reset');
    
    const COLS = 40;
    const ROWS = 30;
    const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)');
    
    let game = createGame();
    let playing = false;
    let timerId = null;
    let wasPlayingBeforeHidden = false;
    let isDragging = false;
    let lastCell = null;
    let cursorX = 0;
    let cursorY = 0;
    
    function announce(text) {
      sayEl.textContent = text;
    }
    
    function render() {
      const st = game.state();
      ctx.clearRect(0, 0, board.width, board.height);
      ctx.fillStyle = '#c9a86b';
      let count = 0;
      const cells = st.cells;
      for (let y = 0; y < ROWS; y++) {
        const row = cells[y];
        for (let x = 0; x < COLS; x++) {
          if (row[x] === 1) {
            ctx.fillRect(x * 16, y * 16, 16, 16);
            count++;
          }
        }
      }
      statusEl.textContent = `Frame ${st.frame}, ${count} grain${count === 1 ? '' : 's'} of sand`;
    }
    
    function pause() {
      playing = false;
      playBtn.textContent = 'Play';
      if (timerId) {
        clearTimeout(timerId);
        timerId = null;
      }
    }
    
    function tick() {
      if (!playing) return;
      game.play('step');
      render();
      timerId = setTimeout(tick, 50);
    }
    
    function onPlayClick() {
      if (document.hidden) return;
      if (prefersReduced.matches) {
        game.play('step');
        render();
        announce('Step');
        return;
      }
      if (playing) {
        pause();
        announce('Pause');
      } else {
        playing = true;
        playBtn.textContent = 'Pause';
        announce('Play');
        tick();
      }
    }
    
    playBtn.addEventListener('click', onPlayClick);
    stepBtn.addEventListener('click', () => {
      game.play('step');
      render();
      announce('Step');
    });
    resetBtn.addEventListener('click', () => {
      pause();
      wasPlayingBeforeHidden = false;
      game = createGame();
      cursorX = 0;
      cursorY = 0;
      render();
      announce('Reset');
    });
    
    function cellFromPoint(cx, cy) {
      const rect = board.getBoundingClientRect();
      if (cx < rect.left || cy < rect.top || cx >= rect.right || cy >= rect.bottom) return null;
      const x = Math.floor(((cx - rect.left) / rect.width) * COLS);
      const y = Math.floor(((cy - rect.top) / rect.height) * ROWS);
      return { x, y };
    }
    
    function pour(x, y) {
      game.play([x, y]);
    }
    
    board.addEventListener('pointerdown', (e) => {
      if (e.button !== 0) return;
      const cell = cellFromPoint(e.clientX, e.clientY);
      if (!cell) return;
      isDragging = true;
      lastCell = cell;
      pour(cell.x, cell.y);
      render();
      announce('Pour');
    });
    
    board.addEventListener('pointermove', (e) => {
      if (!isDragging) return;
      const cell = cellFromPoint(e.clientX, e.clientY);
      if (!cell) return;
      if (cell.x === lastCell.x && cell.y === lastCell.y) return;
      const line = bresenham(lastCell.x, lastCell.y, cell.x, cell.y);
      for (const p of line) pour(p[0], p[1]);
      lastCell = cell;
      render();
    });
    
    board.addEventListener('pointerup', () => {
      isDragging = false;
      lastCell = null;
    });
    board.addEventListener('pointercancel', () => {
      isDragging = false;
      lastCell = null;
    });
    board.addEventListener('pointerleave', () => {
      isDragging = false;
      lastCell = null;
    });
    
    function bresenham(x0, y0, x1, y1) {
      const points = [];
      const dx = Math.abs(x1 - x0);
      const dy = Math.abs(y1 - y0);
      const sx = x0 < x1 ? 1 : -1;
      const sy = y0 < y1 ? 1 : -1;
      let err = dx - dy;
      while (true) {
        points.push([x0, y0]);
        if (x0 === x1 && y0 === y1) break;
        const e2 = 2 * err;
        if (e2 > -dy) { err -= dy; x0 += sx; }
        if (e2 < dx) { err += dx; y0 += sy; }
      }
      return points;
    }
    
    board.tabIndex = 0;
    board.addEventListener('keydown', (e) => {
      if (e.key === 'ArrowLeft') { cursorX = Math.max(0, cursorX - 1); e.preventDefault(); }
      else if (e.key === 'ArrowRight') { cursorX = Math.min(COLS - 1, cursorX + 1); e.preventDefault(); }
      else if (e.key === 'ArrowUp') { cursorY = Math.max(0, cursorY - 1); e.preventDefault(); }
      else if (e.key === 'ArrowDown') { cursorY = Math.min(ROWS - 1, cursorY + 1); e.preventDefault(); }
      else if (e.key === ' ' || e.key === 'Enter') {
        pour(cursorX, cursorY);
        render();
        announce('Pour');
        e.preventDefault();
      }
    });
    
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        if (playing) {
          wasPlayingBeforeHidden = true;
          pause();
          playBtn.textContent = 'Play';
        }
      } else {
        if (wasPlayingBeforeHidden) {
          wasPlayingBeforeHidden = false;
          playing = true;
          playBtn.textContent = 'Pause';
          announce('Play');
          tick();
        }
      }
    });
    
    render();
    </script>
    </body>
    </html>
  • Focus timerPassed

    14,299 tokens: 1,111 read, 13,188 written · 1 min 32 s · 144 tok/s

    Build a focus timer as one web page. Work periods alternate with breaks, and after every few finished work periods the break is long. The page shows the name of the period, the time left, an SVG ring that empties as the time runs down, and how many work periods are done.
    
    In <script id="game">, define createGame(). It returns an object with two methods, tick(cmd) and state(). The page's own timer calls tick() once a second, and its buttons call tick('start'), tick('pause'), tick('skip') and tick('reset'). Those four exact lowercase words are commands: they change the timer and pass no time. Any other value passes one second, and only while the timer is running: no argument, null, undefined, a number, true, false, an empty text, any other text such as 'Start' or 'tick', or an object. state() returns {phase, left, running, done}: phase is 'work', 'short' or 'long'; left is the whole number of seconds left in this period; running is true or false; done is a number. The script in <script id="game"> is at most 20,000 characters.
    
    This run's lengths: work 1800 seconds (30 minutes), short break 300 seconds (5 minutes), long break 1200 seconds (20 minutes). A long break follows every 3rd finished work period.
    
    The rules, exactly:
    1. The timer starts in work, with left 1800, running false and done 0.
    2. 'start' sets running to true, and 'pause' sets it to false. Neither changes anything else.
    3. While running, each passed second lowers left by 1. While paused, passed seconds change nothing.
    4. When left reaches 0, the period is over at once, so state() never shows 0. The next period starts with its full length and paused (running false). Seconds passed after that change nothing until 'start'.
    5. A work period that ends this way adds 1 to done. Then a long break comes when done is a multiple of 3, otherwise a short break.
    6. 'skip' ends the current period at once, whatever left is, and the next period starts paused. A skipped work period does not add to done, and the break after it is a short break whatever done is. A skipped break is followed by work.
    7. After any break comes work. A break never adds to done.
    8. 'reset' sets left back to the full length of the current period and sets running to false. It does not change the phase or done.
    
    The page:
    - A heading, "Focus timer".
    - The name of the period, alone in an element with the id phase: Focus, Short break or Long break.
    - The time left, as mm:ss with two digits each, alone in an element with the id time. At the start of this run's work period it reads 30:00.
    - An SVG ring around the time: a circle with pathLength="100" and stroke-dasharray="100". Set its stroke-dashoffset attribute to 100 times (1 minus left divided by the full length of the current period) on every redraw. The arc is full, with an offset of 0, at the start of a period, and it is empty, with an offset of 100, when the time is up. A track circle without a stroke-dashoffset may sit under it.
    - Four buttons in one row, with the ids start, pause, skip and reset, labelled Start, Pause, Skip and Reset. Each calls tick() with its command. Start is disabled while the timer runs, and Pause is disabled while it is paused. Skip and Reset are always enabled. Below 390 px they may wrap into two rows of two.
    - The count in an element with the id count, in words: "Focus periods done: 3".
    - The page's own timer calls tick() once a second, with no argument. After every call, the page redraws from state(). When a period ends, the page may play a short chime with the Web Audio API.
    - Look: a light, warm off-white page with one white card, dark ink text and muted grey for the small labels. One accent colour, used for the Start button only. Flat fills, no gradients or shadows, no outside fonts or images: use the system font. It must look tidy at 390 px and at 1280 px wide, with no sideways scrolling.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the timer's logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and drives the timer through createGame(). Do not use eval, Function or any other way of running text as code: no string given to a timer, and no script element or event-handler attribute made from text while the page runs. Put the wiring in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Focus timer</title>
    <style>
    * {
      box-sizing: border-box;
    }
    html {
      max-width: 100%;
      overflow-x: hidden;
    }
    body {
      margin: 0;
      padding: 24px;
      background: #fdf7ee;
      color: #2e241c;
      font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      display: flex;
      justify-content: center;
      min-height: 100vh;
    }
    .card {
      background: #ffffff;
      padding: 32px 24px;
      width: min(92%, 520px);
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 20px;
    }
    h1 {
      margin: 0;
      font-size: 1.5rem;
      letter-spacing: 0.02em;
    }
    #phase {
      font-size: 1.25rem;
      font-weight: 600;
      color: #5c4a3a;
    }
    .time-wrap {
      position: relative;
      width: 220px;
      height: 220px;
    }
    .time-wrap svg {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      display: block;
    }
    #time {
      position: absolute;
      inset: 0;
      margin: 0;
      display: grid;
      place-items: center;
      font-size: clamp(1.5rem, 8vw, 2.6rem);
      font-variant-numeric: tabular-nums;
      line-height: 1;
      pointer-events: none;
    }
    .track {
      stroke: #e8dcc8;
      stroke-width: 10;
      fill: none;
      stroke-dasharray: 100;
    }
    #ring {
      stroke: #5c4a3a;
      stroke-width: 10;
      fill: none;
      stroke-dasharray: 100;
      stroke-dashoffset: 0;
      transform: rotate(-90deg);
      transform-origin: 50% 50%;
    }
    #count {
      font-size: 0.95rem;
      color: #8a7d6e;
    }
    .buttons {
      display: flex;
      gap: 8px;
      justify-content: center;
      width: 100%;
      flex-wrap: wrap;
    }
    .buttons button {
      flex: 0 0 48%;
      padding: 12px 8px;
      font-size: 1rem;
      border: 1px solid #c9b8a4;
      background: #ffffff;
      color: #2e241c;
      cursor: pointer;
      border-radius: 6px;
    }
    .buttons button:disabled {
      opacity: 0.55;
      cursor: not-allowed;
    }
    #start {
      background: #c98a4a;
      border-color: #c98a4a;
      color: #ffffff;
    }
    #start:disabled {
      background: #d8bb9e;
      border-color: #d8bb9e;
      color: #ffffff;
      opacity: 0.7;
    }
    @media (max-width: 390px) {
      .card {
        width: min(96%, 390px);
        padding: 24px 16px;
      }
      .buttons button {
        flex: 0 0 calc(50% - 4px);
      }
    }
    </style>
    </head>
    <body>
    <div class="card">
      <h1>Focus timer</h1>
      <div id="phase">Focus</div>
      <div class="time-wrap">
        <svg viewBox="0 0 100 100" width="220" height="220">
          <circle class="track" cx="50" cy="50" r="40" pathLength="100" stroke-dasharray="100"></circle>
          <circle id="ring" cx="50" cy="50" r="40" pathLength="100" stroke-dasharray="100" stroke-dashoffset="0" transform="rotate(-90 50 50)"></circle>
        </svg>
        <div id="time">30:00</div>
      </div>
      <div id="count">Focus periods done: 0</div>
      <div class="buttons">
        <button id="start">Start</button>
        <button id="pause">Pause</button>
        <button id="skip">Skip</button>
        <button id="reset">Reset</button>
      </div>
    </div>
    <script id="game">
    function createGame() {
      var WORK = 1800;
      var SHORT = 300;
      var LONG = 1200;
    
      var phase = 'work';
      var running = false;
      var done = 0;
      var left = WORK;
    
      function lengthFor(p) {
        if (p === 'work') return WORK;
        if (p === 'short') return SHORT;
        return LONG;
      }
    
      function endPeriod(skipped) {
        if (phase === 'work') {
          if (!skipped) {
            done += 1;
          }
          phase = skipped ? 'short' : (done % 3 === 0 ? 'long' : 'short');
        } else {
          phase = 'work';
        }
        left = lengthFor(phase);
        running = false;
      }
    
      return {
        tick: function (cmd) {
          if (cmd === 'start') {
            running = true;
            return;
          }
          if (cmd === 'pause') {
            running = false;
            return;
          }
          if (cmd === 'skip') {
            endPeriod(true);
            return;
          }
          if (cmd === 'reset') {
            left = lengthFor(phase);
            running = false;
            return;
          }
          if (!running) return;
          left -= 1;
          if (left <= 0) {
            endPeriod(false);
          }
        },
        state: function () {
          return { phase: phase, left: left, running: running, done: done };
        }
      };
    }
    </script>
    <script>
    var game = createGame();
    
    var phaseEl = document.getElementById('phase');
    var timeEl = document.getElementById('time');
    var ringEl = document.getElementById('ring');
    var countEl = document.getElementById('count');
    var startBtn = document.getElementById('start');
    var pauseBtn = document.getElementById('pause');
    var skipBtn = document.getElementById('skip');
    var resetBtn = document.getElementById('reset');
    
    var audioCtx = null;
    var prev = null;
    
    function lengthForPhase(p) {
      return p === 'work' ? 1800 : p === 'short' ? 300 : 1200;
    }
    
    function formatTime(s) {
      var m = Math.floor(s / 60);
      var sec = s % 60;
      return String(m).padStart(2, '0') + ':' + String(sec).padStart(2, '0');
    }
    
    function ensureAudio() {
      if (audioCtx) return;
      var Ctx = window.AudioContext || window.webkitAudioContext;
      if (!Ctx) return;
      audioCtx = new Ctx();
    }
    
    function chime() {
      ensureAudio();
      if (!audioCtx) return;
      if (audioCtx.state === 'suspended') {
        audioCtx.resume();
      }
      var t = audioCtx.currentTime;
    
      var osc1 = audioCtx.createOscillator();
      var gain1 = audioCtx.createGain();
      osc1.type = 'sine';
      osc1.frequency.setValueAtTime(660, t);
      osc1.frequency.exponentialRampToValueAtTime(990, t + 0.2);
      gain1.gain.setValueAtTime(0.08, t);
      gain1.gain.exponentialRampToValueAtTime(0.001, t + 0.3);
      osc1.connect(gain1);
      gain1.connect(audioCtx.destination);
      osc1.start(t);
      osc1.stop(t + 0.3);
    
      var osc2 = audioCtx.createOscillator();
      var gain2 = audioCtx.createGain();
      osc2.type = 'sine';
      osc2.frequency.setValueAtTime(880, t);
      osc2.frequency.exponentialRampToValueAtTime(1320, t + 0.2);
      gain2.gain.setValueAtTime(0.06, t);
      gain2.gain.exponentialRampToValueAtTime(0.001, t + 0.3);
      osc2.connect(gain2);
      gain2.connect(audioCtx.destination);
      osc2.start(t);
      osc2.stop(t + 0.3);
    }
    
    function render(s) {
      phaseEl.textContent = s.phase === 'work' ? 'Focus' : s.phase === 'short' ? 'Short break' : 'Long break';
      timeEl.textContent = formatTime(s.left);
      var total = lengthForPhase(s.phase);
      var offset = 100 * (1 - s.left / total);
      ringEl.setAttribute('stroke-dashoffset', String(offset));
      countEl.textContent = 'Focus periods done: ' + s.done;
      startBtn.disabled = s.running;
      pauseBtn.disabled = !s.running;
    }
    
    function handleCommand(cmd) {
      ensureAudio();
      game.tick(cmd);
      var s = game.state();
      if (prev && prev.phase !== s.phase) chime();
      prev = s;
      render(s);
    }
    
    startBtn.addEventListener('click', function () { handleCommand('start'); });
    pauseBtn.addEventListener('click', function () { handleCommand('pause'); });
    skipBtn.addEventListener('click', function () { handleCommand('skip'); });
    resetBtn.addEventListener('click', function () { handleCommand('reset'); });
    
    setInterval(function () {
      game.tick(undefined);
      var s = game.state();
      if (prev && prev.phase !== s.phase) chime();
      prev = s;
      render(s);
    }, 1000);
    
    render(game.state());
    prev = game.state();
    </script>
    </body>
    </html>
Writing code 3 of 3
  • Merge intervalsPassed

    1,221 tokens: 168 read, 1,053 written · 7 s · 145 tok/s

    Write a JavaScript function mergeIntervals(intervals). intervals is an array of [start, end] pairs of integers with start <= end, in any order, possibly empty. Return a new array of the merged intervals sorted by start: intervals that overlap or touch (one ends where the next starts) become one. Do not change the input array or its pairs.
    
    mergeIntervals([[8, 10], [1, 3], [2, 6], [6, 7]]) returns [[1, 7], [8, 10]].
    
    Reply with one ```js code block holding plain JavaScript (no imports, no exports, no DOM, no timers). The site runs it with hidden tests.
    ```js
    function mergeIntervals(intervals) {
      const sorted = intervals.map(pair => [pair[0], pair[1]])
        .sort((a, b) => a[0] - b[0]);
    
      const merged = [];
    
      for (const [start, end] of sorted) {
        const last = merged[merged.length - 1];
        if (!last || start > last[1]) {
          merged.push([start, end]);
        } else if (end > last[1]) {
          last[1] = end;
        }
      }
    
      return merged;
    }
    ```
  • An LRU cachePassed

    1,381 tokens: 173 read, 1,208 written · 8 s · 150 tok/s

    Write a JavaScript class LRUCache: a least-recently-used cache of integer keys and values.
    
    - new LRUCache(capacity): capacity is an integer of at least 1.
    - get(key) returns the value stored for key, or -1 if there is none. A get that finds the key makes it the most recently used.
    - put(key, value) stores the value (replacing any value already there) and makes key the most recently used. If that leaves more than capacity keys, the least recently used key is removed.
    
    get and put should take constant time on average.
    
    Reply with one ```js code block holding plain JavaScript (no imports, no exports, no DOM, no timers). The site runs it with hidden tests.
    ```js
    class LRUCache {
      constructor(capacity) {
        this.capacity = capacity;
        this.map = new Map();
        this.head = null;
        this.tail = null;
      }
    
      _removeNode(node) {
        if (node.prev) node.prev.next = node.next;
        else this.head = node.next;
        if (node.next) node.next.prev = node.prev;
        else this.tail = node.prev;
        node.prev = null;
        node.next = null;
      }
    
      _addToHead(node) {
        node.prev = null;
        node.next = this.head;
        if (this.head) this.head.prev = node;
        this.head = node;
        if (!this.tail) this.tail = node;
      }
    
      _moveToHead(node) {
        this._removeNode(node);
        this._addToHead(node);
      }
    
      _popTail() {
        const tail = this.tail;
        this._removeNode(tail);
        return tail;
      }
    
      get(key) {
        const node = this.map.get(key);
        if (!node) return -1;
        this._moveToHead(node);
        return node.value;
      }
    
      put(key, value) {
        const node = this.map.get(key);
        if (node) {
          node.value = value;
          this._moveToHead(node);
          return;
        }
        const newNode = { key, value, prev: null, next: null };
        this.map.set(key, newNode);
        this._addToHead(newNode);
        if (this.map.size > this.capacity) {
          const removed = this._popTail();
          this.map.delete(removed.key);
        }
      }
    }
    ```
  • Evaluate arithmeticPassed

    3,501 tokens: 204 read, 3,297 written · 23 s · 141 tok/s

    Write a JavaScript function evaluate(expr) that returns the value of an arithmetic expression given as a string. The expression has non-negative integers, the operators + - * /, parentheses, unary minus (as in -3, - -3, 2 * -3 or -(1 + 2)) and spaces anywhere between tokens. * and / bind tighter than + and -, and operators of the same kind group from the left. / is integer division that truncates toward zero: 7 / 2 is 3 and -7 / 2 is -3. Dividing by zero must throw an Error. Do not use eval or Function.
    
    evaluate("2 + 3 * (4 - 6) / 4") returns 1.
    
    Reply with one ```js code block holding plain JavaScript (no imports, no exports, no DOM, no timers). The site runs it with hidden tests.
    ```js
    function evaluate(expr) {
      let pos = 0;
      const n = expr.length;
    
      function nextToken() {
        while (pos < n && expr[pos] === ' ') pos++;
        if (pos >= n) return { type: 'EOF' };
        const ch = expr[pos];
        if (ch >= '0' && ch <= '9') {
          let val = 0;
          while (pos < n && expr[pos] >= '0' && expr[pos] <= '9') {
            val = val * 10 + (expr[pos].charCodeAt(0) - 48);
            pos++;
          }
          return { type: 'NUM', value: val };
        }
        pos++;
        switch (ch) {
          case '+': return { type: 'PLUS' };
          case '-': return { type: 'MINUS' };
          case '*': return { type: 'STAR' };
          case '/': return { type: 'SLASH' };
          case '(': return { type: 'LPAREN' };
          case ')': return { type: 'RPAREN' };
          default: throw new Error('Invalid character: ' + ch);
        }
      }
    
      let token = nextToken();
    
      function eat(type) {
        if (token.type !== type) throw new Error('Unexpected token');
        token = nextToken();
      }
    
      function parseExpr() {
        let val = parseTerm();
        while (token.type === 'PLUS' || token.type === 'MINUS') {
          const op = token.type;
          eat(op);
          const rhs = parseTerm();
          if (op === 'PLUS') val = val + rhs;
          else val = val - rhs;
        }
        return val;
      }
    
      function parseTerm() {
        let val = parseFactor();
        while (token.type === 'STAR' || token.type === 'SLASH') {
          const op = token.type;
          eat(op);
          const rhs = parseFactor();
          if (op === 'STAR') {
            val = val * rhs;
          } else {
            if (rhs === 0) throw new Error('Division by zero');
            val = Math.trunc(val / rhs);
          }
        }
        return val;
      }
    
      function parseFactor() {
        if (token.type === 'PLUS') {
          eat('PLUS');
          return parseFactor();
        }
        if (token.type === 'MINUS') {
          eat('MINUS');
          return -parseFactor();
        }
        return parsePrimary();
      }
    
      function parsePrimary() {
        if (token.type === 'NUM') {
          const val = token.value;
          eat('NUM');
          return val;
        }
        if (token.type === 'LPAREN') {
          eat('LPAREN');
          const val = parseExpr();
          eat('RPAREN');
          return val;
        }
        throw new Error('Unexpected token');
      }
    
      const result = parseExpr();
      if (token.type !== 'EOF') throw new Error('Unexpected trailing tokens');
      return result;
    }
    ```
Fixing code 2 of 2
  • Fix the bookings modulePassed

    2,375 tokens: 631 read, 1,744 written · 12 s · 142 tok/s

    This JavaScript module has one bug. Guests are charged the weekend rate for Sunday nights and the weekday rate for Friday nights.
    
    Find it and fix it without changing anything else.
    
    ```js
    // Bookings for one holiday flat. A booking is { guest, checkIn, checkOut } with dates as "YYYY-MM-DD".
    // A guest sleeps the nights from checkIn up to, but not including, checkOut: checkOut is the day they leave,
    // and another guest may check in that same day.
    
    function dayNumber(date) {
      const [y, m, d] = date.split('-').map(Number);
      return Date.UTC(y, m - 1, d) / 86400000;
    }
    
    function toDate(day) {
      return new Date(day * 86400000).toISOString().slice(0, 10);
    }
    
    function nights(booking) {
      return dayNumber(booking.checkOut) - dayNumber(booking.checkIn);
    }
    
    function overlaps(a, b) {
      return dayNumber(a.checkIn) < dayNumber(b.checkOut) && dayNumber(b.checkIn) < dayNumber(a.checkOut);
    }
    
    function canBook(bookings, request) {
      if (nights(request) < 1) return false;
      for (const booking of bookings) {
        if (overlaps(booking, request)) return false;
      }
      return true;
    }
    
    function isBooked(bookings, day) {
      return bookings.some((b) => dayNumber(b.checkIn) <= day && day < dayNumber(b.checkOut));
    }
    
    // The nights from `from` up to, but not including, `to` that someone has booked.
    function bookedNights(bookings, from, to) {
      let count = 0;
      for (let day = dayNumber(from); day < dayNumber(to); day++) {
        if (isBooked(bookings, day)) count++;
      }
      return count;
    }
    
    // The first night on or after `from` that nobody has booked, as "YYYY-MM-DD".
    function firstFreeNight(bookings, from) {
      let day = dayNumber(from);
      while (isBooked(bookings, day)) day++;
      return toDate(day);
    }
    
    // The price in cents: Friday and Saturday nights at rates.weekend, every other night at rates.weekday.
    function price(booking, rates) {
      let total = 0;
      for (let day = dayNumber(booking.checkIn); day < dayNumber(booking.checkOut); day++) {
        const weekday = new Date(day * 86400000).getUTCDay();
        total += weekday === 6 || weekday === 0 ? rates.weekend : rates.weekday;
      }
      return total;
    }
    ```
    
    Reply with the whole corrected module in one ```js code block, with the same function names.
    ```js
    // Bookings for one holiday flat. A booking is { guest, checkIn, checkOut } with dates as "YYYY-MM-DD".
    // A guest sleeps the nights from checkIn up to, but not including, checkOut: checkOut is the day they leave,
    // and another guest may check in that same day.
    
    function dayNumber(date) {
      const [y, m, d] = date.split('-').map(Number);
      return Date.UTC(y, m - 1, d) / 86400000;
    }
    
    function toDate(day) {
      return new Date(day * 86400000).toISOString().slice(0, 10);
    }
    
    function nights(booking) {
      return dayNumber(booking.checkOut) - dayNumber(booking.checkIn);
    }
    
    function overlaps(a, b) {
      return dayNumber(a.checkIn) < dayNumber(b.checkOut) && dayNumber(b.checkIn) < dayNumber(a.checkOut);
    }
    
    function canBook(bookings, request) {
      if (nights(request) < 1) return false;
      for (const booking of bookings) {
        if (overlaps(booking, request)) return false;
      }
      return true;
    }
    
    function isBooked(bookings, day) {
      return bookings.some((b) => dayNumber(b.checkIn) <= day && day < dayNumber(b.checkOut));
    }
    
    // The nights from `from` up to, but not including, `to` that someone has booked.
    function bookedNights(bookings, from, to) {
      let count = 0;
      for (let day = dayNumber(from); day < dayNumber(to); day++) {
        if (isBooked(bookings, day)) count++;
      }
      return count;
    }
    
    // The first night on or after `from` that nobody has booked, as "YYYY-MM-DD".
    function firstFreeNight(bookings, from) {
      let day = dayNumber(from);
      while (isBooked(bookings, day)) day++;
      return toDate(day);
    }
    
    // The price in cents: Friday and Saturday nights at rates.weekend, every other night at rates.weekday.
    function price(booking, rates) {
      let total = 0;
      for (let day = dayNumber(booking.checkIn); day < dayNumber(booking.checkOut); day++) {
        const weekday = new Date(day * 86400000).getUTCDay();
        total += weekday === 5 || weekday === 6 ? rates.weekend : rates.weekday;
      }
      return total;
    }
    ```
  • Fix the CSV readerPassed

    3,442 tokens: 488 read, 2,954 written · 20 s · 147 tok/s

    This JavaScript module has one bug. A doubled quote inside a quoted field is read wrongly: the line "a""b",c comes back as one field, a"b,c, instead of two fields, a"b and c.
    
    Find it and fix it without changing anything else.
    
    ```js
    // Reads CSV the way spreadsheets write it: fields are separated by commas, a field may be wrapped in
    // double quotes so it can hold commas, and "" inside a quoted field stands for one double quote.
    // Fields are not trimmed. Empty lines are skipped.
    
    function parseLine(line) {
      const fields = [];
      let field = '';
      let quoted = false;
      for (let i = 0; i < line.length; i++) {
        const ch = line[i];
        if (quoted) {
          if (ch === '"') {
            if (line[i + 1] === '"') {
              field += '"';
            } else {
              quoted = false;
            }
          } else {
            field += ch;
          }
        } else if (ch === '"') {
          quoted = true;
        } else if (ch === ',') {
          fields.push(field);
          field = '';
        } else {
          field += ch;
        }
      }
      fields.push(field);
      return fields;
    }
    
    function parseCSV(text) {
      return text.split(/\r?\n/).filter((line) => line !== '').map(parseLine);
    }
    
    // Each row after the header as an object keyed by the header's names; a missing field is ''.
    function toObjects(text) {
      const [header, ...rows] = parseCSV(text);
      return rows.map((row) => {
        const record = {};
        header.forEach((name, i) => {
          record[name] = i < row.length ? row[i] : '';
        });
        return record;
      });
    }
    
    // The sum of a column's numbers; fields that are not numbers count as 0.
    function sumColumn(text, name) {
      return toObjects(text).reduce((total, record) => total + (Number(record[name]) || 0), 0);
    }
    ```
    
    Reply with the whole corrected module in one ```js code block, with the same function names.
    ```js
    // Reads CSV the way spreadsheets write it: fields are separated by commas, a field may be wrapped in
    // double quotes so it can hold commas, and "" inside a quoted field stands for one double quote.
    // Fields are not trimmed. Empty lines are skipped.
    
    function parseLine(line) {
      const fields = [];
      let field = '';
      let quoted = false;
      for (let i = 0; i < line.length; i++) {
        const ch = line[i];
        if (quoted) {
          if (ch === '"') {
            if (line[i + 1] === '"') {
              field += '"';
              i++;
            } else {
              quoted = false;
            }
          } else {
            field += ch;
          }
        } else if (ch === '"') {
          quoted = true;
        } else if (ch === ',') {
          fields.push(field);
          field = '';
        } else {
          field += ch;
        }
      }
      fields.push(field);
      return fields;
    }
    
    function parseCSV(text) {
      return text.split(/\r?\n/).filter((line) => line !== '').map(parseLine);
    }
    
    // Each row after the header as an object keyed by the header's names; a missing field is ''.
    function toObjects(text) {
      const [header, ...rows] = parseCSV(text);
      return rows.map((row) => {
        const record = {};
        header.forEach((name, i) => {
          record[name] = i < row.length ? row[i] : '';
        });
        return record;
      });
    }
    
    // The sum of a column's numbers; fields that are not numbers count as 0.
    function sumColumn(text, name) {
      return toObjects(text).reduce((total, record) => total + (Number(record[name]) || 0), 0);
    }
    ```
Planning and data 3 of 3
  • A query over hidden dataPassed

    699 tokens: 245 read, 454 written · 8 s · 58.2 tok/s

    Write one SQLite query that answers the question below. The site runs it on its own copy of these tables, filled with rows you have not seen.
    
    ```sql
    CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL);
    CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers(id),
                         placed TEXT NOT NULL,  -- 'YYYY-MM-DD'
                         status TEXT NOT NULL); -- 'delivered', 'cancelled' or 'pending'
    CREATE TABLE items (order_id INTEGER NOT NULL REFERENCES orders(id), product TEXT NOT NULL,
                        quantity INTEGER NOT NULL, price_cents INTEGER NOT NULL);  -- price_cents: for one unit
    ```
    
    Question: For each city, the total value (quantity times price_cents, summed) of the items in delivered orders placed in 2024. Columns: city, total. Highest total first. Leave out cities with no such items.
    
    Reply with only the query, in one ```sql code block: one SELECT statement (WITH is fine), nothing that changes the database.
    ```sql
    SELECT c.city,
           SUM(i.quantity * i.price_cents) AS total
    FROM customers c
    JOIN orders o ON o.customer_id = c.id
    JOIN items i ON i.order_id = o.id
    WHERE o.status = 'delivered'
      AND o.placed >= '2024-01-01'
      AND o.placed <= '2024-12-31'
    GROUP BY c.city
    ORDER BY total DESC;
    ```
  • Schedule five meetingsPassed

    4,300 tokens: 270 read, 4,030 written · 30 s · 136 tok/s

    Five people each have one meeting today: Ana, Cleo, Dev, Fay, Hal. The five meetings are at different times, 09:00, 10:00, 11:00, 13:00, 14:00 (in that order: 10:00 is right after 09:00, 13:00 right after 11:00), and in different rooms. The list of rooms, in order: Cedar, Elm, Maple, Oak, Pine.
    
    1. Fay meets earlier than Ana.
    2. Dev meets earlier than Hal.
    3. Hal's meeting is in the slot right after Cleo's.
    4. Hal is not in Maple.
    5. Whoever is in Oak meets earlier than Dev.
    6. Ana's and Cleo's rooms are not next to each other on the list of rooms.
    7. Whoever is in Cedar meets earlier than Cleo.
    8. Whoever is in Pine meets earlier than Dev.
    
    Exactly one schedule fits every clue. Work it out, then end with exactly five lines, one per person, in this form:
    Ana: 09:00, Oak
    Ana: 10:00, Pine
    Cleo: 13:00, Maple
    Dev: 11:00, Cedar
    Fay: 09:00, Oak
    Hal: 14:00, Elm
  • A replacement in ten calls or fewerPassed

    15,102 tokens: 13,948 read, 1,154 written · 15 s · 77.4 tok/s

    Hi, it's cal.reyes@example.com. My kettle arrived with a cracked lid. Can you sort it out?
    1. system
      You are the support agent of Tidewell Home, working through its tools, and you may make at most 10 tool calls for one request. When an item arrives damaged: confirm which order it came in, send a replacement from the north warehouse if it has the item, else from south, else from east (check each in that order, and only as far as needed), and take the damaged item back with a return. If the return is refused, open a damage claim for the order with open_claim. Then reply to the customer with what you did, giving any reference numbers and the date the replacement ships.
    2. user
      Hi, it's cal.reyes@example.com. My kettle arrived with a cracked lid. Can you sort it out?
    3. assistant
      lookup_account({"email":"cal.reyes@example.com"})
    4. tool
      {"account_id": "AC-457", "name": "Cal Reyes"}
    5. assistant
      list_orders({"account_id":"AC-457"})
    6. tool
      {"orders": [{"order_id": "R-5128", "placed": "2026-10-04", "status": "delivered"}, {"order_id": "R-5611", "placed": "2026-10-28", "status": "delivered"}, {"order_id": "R-5804", "placed": "2026-10-23", "status": "in transit"}]}
    7. assistant
      get_order({"order_id":"R-5128"})
    8. tool
      {"items": [{"name": "Oak table lamp", "quantity": 1, "sku": "lamp-oak"}], "order_id": "R-5128"}
    9. assistant
      get_order({"order_id":"R-5611"})
    10. tool
      {"items": [{"name": "Steel kettle", "quantity": 1, "sku": "kettle-steel"}, {"name": "Grey mug", "quantity": 2, "sku": "mug-grey"}], "order_id": "R-5611"}
    11. assistant
      check_stock({"sku":"kettle-steel","warehouse":"north"})
    12. tool
      {"available": 0, "sku": "kettle-steel", "warehouse": "north"}
    13. assistant
      check_stock({"sku":"kettle-steel","warehouse":"south"})
    14. tool
      {"available": 4, "sku": "kettle-steel", "warehouse": "south"}
    15. assistant
      reserve_item({"order_id":"R-5611","sku":"kettle-steel","warehouse":"south"})
    16. tool
      {"reservation_id": "RS-4310", "ships_on": "2026-11-09"}
    17. assistant
      create_return({"order_id":"R-5611","reason":"damaged item"})
    18. tool
      {"error": "damaged items are not returned: open a damage claim with open_claim instead"}
    19. assistant
      open_claim({"order_id":"R-5611","reason":"cracked lid on kettle"})
    20. tool
      {"claim_id": "CL-2190", "order_id": "R-5611", "status": "open"}
    21. assistant
      Hi Cal,
      
      I found your account and located the order with the steel kettle (order **R-5611**). Here's what I've done:
      
      1. **Replacement shipped**: Reserved one steel kettle from our **south warehouse**. Reservation **RS-4310** — it ships on **2026-11-09**.
      2. **Damage claim opened**: Since damaged items aren't sent back with a return label, I opened a damage claim for your order instead. Claim **CL-2190** is now open.
      
      No return label is needed — the claim covers the damaged item. You should receive your replacement kettle by the ship date above.
      
      Is there anything else I can help with?

Comments

Sign in or create an account to comment.