Qwen3.8-Flash-Next run

M4 Max 128 GB · llama.cpp · every run of this model · uwu · 2026-11-07

Race this run Get the model from Hugging Face: ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF

Run Qwen3.8-Flash-Next on your computer to see the two side by side.

A full run: 50 tasks, 82 points

Score
2,312 Silver Speed times the share of points, times 100. Gold starts at 3,000: 31.2 tok/s with these answers. How scores work24 tok/s × 96.3% of points
  1. Bronze0
  2. Silver1,500
  3. Gold3,000
  4. Platinum6,000
  5. Diamond10,000
#1 of 1 on M4 Max 128 GB · #1 among Apple silicon
Tasks passed
49/50
Points
79/82Harder tasks count 3. How scores work
Tokens
528,55130,778 read, 497,773 written.
Speed
24 tok/sTokens a second, as the runner measured it. The site checks only that the machine could reach it. How speeds are checked
Writing speed
24 tok/sWhile writing only: prompt reading is left out. As the runner measured it.

This setup, checked

No other runs of Qwen3.8-Flash-Next on M4 Max 128 GB yet.

Qwen3.8-Flash-Next on M4 Max 128 GB: 49 of 50 tasks in 529k tokens at 24 tok/s, a Silver score of 2,312, in the resyn benchmark. https://resyn.cloud/suite/4829af452c2e8773d92ae9b2eee922abCompare another runComment

Run details
Model file
Not a listed file
Where it ran
llama.cpp
How
Run through the model's API (resyn.cloud in the browser)
Model the API reported
Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002
Time
5 h 50 min
Settings
seed=42, temperature=0, top_p=1
Suite
resyn-tasks@6
Flag this run

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

Failed 1

  • Step sequencerFailed

    100,813 tokens: 1,365 read, 99,448 written · 1 h 15 min · 22 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   1000100010001100
    snare  0000100100001100
    hat    1011101010111010
    
    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">
    <title>Step sequencer</title>
    <style>
      :root {
        --pink: #b31f57;
        --ink: #111111;
        --paper: #f8f8f8;
        --surface: #ffffff;
        --line: #111111;
        --label: 4.5rem;
      }
    
      * {
        box-sizing: border-box;
      }
    
      html, body {
        overflow-x: hidden;
      }
    
      body {
        margin: 1rem;
        background: var(--paper);
        color: var(--ink);
        font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif;
        line-height: 1.3;
      }
    
      h1 {
        margin: 0 0 0.75rem;
        font-size: 1.5rem;
      }
    
      #status,
      #announce {
        height: 1.75rem;
        line-height: 1.75rem;
        margin: 0;
        white-space: nowrap;
        overflow: hidden;
      }
    
      #announce {
        display: block;
      }
    
      #controls {
        margin: 0.75rem 0;
      }
    
      button {
        font: inherit;
        border: 1px solid var(--line);
        background: var(--surface);
        color: var(--ink);
        padding: 0.35rem 0.65rem;
        border-radius: 0;
        cursor: pointer;
      }
    
      button:focus {
        outline: 2px solid var(--pink);
        outline-offset: 2px;
      }
    
      #play {
        background: var(--pink);
        color: #ffffff;
        border-color: var(--pink);
        min-width: 5rem;
      }
    
      #play:disabled {
        background: var(--pink);
        color: #ffffff;
        border-color: var(--pink);
        opacity: 0.45;
        cursor: default;
      }
    
      #stop:disabled {
        opacity: 0.45;
        cursor: default;
      }
    
      #sequencer {
        width: 100%;
        margin-top: 0.75rem;
      }
    
      .header,
      .track {
        display: grid;
        width: 100%;
        grid-template-columns: var(--label) repeat(16, minmax(0, 1fr));
        gap: 4px;
        align-items: center;
      }
    
      .header {
        margin-bottom: 4px;
      }
    
      .hnum {
        text-align: center;
        font-size: 0.8rem;
      }
    
      .hnum.playhead {
        color: var(--pink);
      }
    
      .track {
        margin-bottom: 4px;
      }
    
      .track-label {
        font-weight: 600;
        font-size: 0.9rem;
      }
    
      .step {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 34px;
        padding: 0;
      }
    
      .step.on {
        background: var(--ink);
      }
    
      .step.playhead {
        outline: 2px solid var(--pink);
        outline-offset: -1px;
      }
    
      .step .num {
        display: none;
        font-size: 0.75rem;
        color: var(--ink);
      }
    
      .step.on .num {
        color: var(--surface);
      }
    
      .step.playhead .num {
        color: var(--pink);
      }
    
      @media (max-width: 720px) {
        :root {
          --label: 3.25rem;
        }
    
        .header {
          display: none;
        }
    
        .track {
          grid-template-columns: var(--label) repeat(8, minmax(0, 1fr));
          grid-template-rows: auto auto;
        }
    
        .track-label {
          grid-row: span 2;
          align-self: start;
        }
    
        .step {
          height: 38px;
        }
    
        .step .num {
          display: block;
        }
      }
    
      @media (max-width: 380px) {
        :root {
          --label: 2.75rem;
        }
      }
    </style>
    </head>
    <body>
    <h1>Step sequencer</h1>
    
    <p id="status">Stopped</p>
    <span id="announce" aria-live="polite"></span>
    
    <p id="controls">
      <button id="play" type="button">Play</button>
      <button id="stop" type="button" disabled>Stop</button>
    </p>
    
    <div id="sequencer"></div>
    
    <script id="game">
    function createGame() {
      const patternStrings = [
        "1000100010001100",
        "0000100100001100",
        "1011101010111010"
      ];
    
      const pattern = patternStrings.map(function (row) {
        return row.split("");
      });
    
      let playing = false;
      let playhead = 0;
      let hits = [];
    
      function hitsAt(step) {
        const list = [];
        if (pattern[0][step] === "1") {
          list.push(0);
        }
        if (pattern[1][step] === "1") {
          list.push(1);
        }
        if (pattern[2][step] === "1") {
          list.push(2);
        }
        return list;
      }
    
      function press(command) {
        if (command === "play") {
          if (!playing) {
            playing = true;
            hits = hitsAt(playhead);
          }
          return;
        }
    
        if (command === "stop") {
          playing = false;
          playhead = 0;
          hits = [];
          return;
        }
    
        if (command === "tick") {
          if (!playing) {
            return;
          }
          playhead = playhead + 1;
          if (playhead > 15) {
            playhead = 0;
          }
          hits = hitsAt(playhead);
          return;
        }
    
        if (Array.isArray(command) && command.length === 2) {
          const track = command[0];
          const step = command[1];
    
          if (
            Number.isInteger(track) &&
            Number.isInteger(step) &&
            track >= 0 &&
            track <= 2 &&
            step >= 0 &&
            step <= 15
          ) {
            if (pattern[track][step] === "1") {
              pattern[track][step] = "0";
            } else {
              pattern[track][step] = "1";
            }
          }
        }
      }
    
      function state() {
        return {
          playing: playing,
          playhead: playhead,
          hits: hits.slice(),
          pattern: [
            pattern[0].join(""),
            pattern[1].join(""),
            pattern[2].join("")
          ]
        };
      }
    
      return {
        press: press,
        state: state
      };
    }
    </script>
    
    <script>
    (function () {
      const game = createGame();
    
      const status = document.getElementById("status");
      const announce = document.getElementById("announce");
      const playButton = document.getElementById("play");
      const stopButton = document.getElementById("stop");
      const grid = document.getElementById("sequencer");
    
      const trackNames = ["Kick", "Snare", "Hat"];
    
      const header = document.createElement("div");
      header.className = "header";
      header.setAttribute("aria-hidden", "true");
    
      const headerLabel = document.createElement("span");
      headerLabel.className = "header-label";
      header.appendChild(headerLabel);
    
      for (let step = 0; step < 16; step++) {
        const numberHeader = document.createElement("span");
        numberHeader.className = "hnum";
        numberHeader.dataset.step = String(step);
        numberHeader.textContent = String(step + 1);
        header.appendChild(numberHeader);
      }
    
      grid.appendChild(header);
    
      for (let track = 0; track < 3; track++) {
        const row = document.createElement("div");
        row.className = "track";
    
        const label = document.createElement("span");
        label.className = "track-label";
        label.textContent = trackNames[track];
        row.appendChild(label);
    
        for (let step = 0; step < 16; step++) {
          const button = document.createElement("button");
          button.type = "button";
          button.className = "step";
          button.dataset.track = String(track);
          button.dataset.step = String(step);
          button.setAttribute("aria-label", trackNames[track] + " step " + String(step + 1));
          button.setAttribute("aria-pressed", "false");
    
          const number = document.createElement("span");
          number.className = "num";
          number.textContent = String(step + 1);
          button.appendChild(number);
    
          row.appendChild(button);
        }
    
        grid.appendChild(row);
      }
    
      const stepButtons = Array.from(grid.querySelectorAll(".step"));
      const numbers = Array.from(grid.querySelectorAll(".hnum"));
    
      let previousPlaying = false;
      let timer = null;
    
      let audioContext = null;
      let masterGain = null;
      let noiseBuffer = null;
      const activeSources = new Set();
      const DEFAULT_MASTER_GAIN = 0.25;
    
      function updateAnnounce(playing) {
        if (playing && !previousPlaying) {
          announce.textContent = "Playing";
        } else if (!playing && previousPlaying) {
          announce.textContent = "Stopped";
        }
        previousPlaying = playing;
      }
    
      function draw() {
        const state = game.state();
    
        stepButtons.forEach(function (button) {
          const track = Number(button.dataset.track);
          const step = Number(button.dataset.step);
          const on = state.pattern[track].charAt(step) === "1";
    
          button.classList.toggle("on", on);
          button.setAttribute("aria-pressed", on ? "true" : "false");
          button.classList.toggle("playhead", state.playing && step === state.playhead);
        });
    
        numbers.forEach(function (number) {
          const step = Number(number.dataset.step);
          number.classList.toggle("playhead", state.playing && step === state.playhead);
        });
    
        status.textContent = state.playing
          ? "Playing, step " + String(state.playhead + 1) + " of 16"
          : "Stopped";
    
        playButton.disabled = state.playing;
        stopButton.disabled = !state.playing;
    
        updateAnnounce(state.playing);
      }
    
      function startTimer() {
        if (timer !== null) {
          return;
        }
        timer = window.setInterval(onTick, 125);
      }
    
      function clearTimer() {
        if (timer !== null) {
          window.clearInterval(timer);
          timer = null;
        }
      }
    
      function onTick() {
        game.press("tick");
        const state = game.state();
        draw();
        playHits(state.hits);
      }
    
      function createNoiseBuffer(context) {
        const length = Math.floor(context.sampleRate * 0.5);
        const buffer = context.createBuffer(1, length, context.sampleRate);
        const data = buffer.getChannelData(0);
    
        for (let i = 0; i < length; i++) {
          data[i] = Math.random() * 2 - 1;
        }
    
        return buffer;
      }
    
      function ensureAudio() {
        if (!audioContext) {
          const AudioContextConstructor = window.AudioContext || window.webkitAudioContext;
          if (!AudioContextConstructor) {
            return null;
          }
    
          try {
            audioContext = new AudioContextConstructor();
            masterGain = audioContext.createGain();
            masterGain.gain.value = DEFAULT_MASTER_GAIN;
            masterGain.connect(audioContext.destination);
            noiseBuffer = createNoiseBuffer(audioContext);
          } catch (error) {
            audioContext = null;
            masterGain = null;
            noiseBuffer = null;
            return null;
          }
        }
    
        if (audioContext.state === "suspended" && typeof audioContext.resume === "function") {
          try {
            audioContext.resume().catch(function () {});
          } catch (error) {}
        }
    
        return audioContext;
      }
    
      function restoreGain() {
        try {
          if (audioContext && masterGain) {
            const now = audioContext.currentTime;
            masterGain.gain.cancelScheduledValues(now);
            masterGain.gain.setValueAtTime(DEFAULT_MASTER_GAIN, now);
          }
        } catch (error) {}
      }
    
      function stopAllSounds() {
        if (audioContext && masterGain) {
          let now = 0;
    
          try {
            now = audioContext.currentTime;
          } catch (error) {}
    
          try {
            masterGain.gain.cancelScheduledValues(now);
            masterGain.gain.setValueAtTime(0, now);
          } catch (error) {}
    
          activeSources.forEach(function (source) {
            try {
              source.onended = null;
              source.disconnect();
              source.stop(now);
            } catch (error) {}
          });
    
          activeSources.clear();
        }
      }
    
      function registerSource(source) {
        activeSources.add(source);
        source.onended = function () {
          activeSources.delete(source);
        };
      }
    
      function playKick(time) {
        const oscillator = audioContext.createOscillator();
        const gain = audioContext.createGain();
    
        oscillator.type = "sine";
        oscillator.frequency.setValueAtTime(170, time);
        oscillator.frequency.exponentialRampToValueAtTime(45, time + 0.18);
    
        gain.gain.setValueAtTime(0.0001, time);
        gain.gain.exponentialRampToValueAtTime(0.7, time + 0.01);
        gain.gain.exponentialRampToValueAtTime(0.0001, time + 0.3);
    
        oscillator.connect(gain);
        gain.connect(masterGain);
    
        registerSource(oscillator);
    
        oscillator.start(time);
        oscillator.stop(time + 0.35);
      }
    
      function playSnare(time) {
        const noise = audioContext.createBufferSource();
        const noiseGain = audioContext.createGain();
        const filter = audioContext.createBiquadFilter();
    
        noise.buffer = noiseBuffer;
        filter.type = "bandpass";
        filter.frequency.value = 1800;
        filter.Q.value = 0.8;
    
        noiseGain.gain.setValueAtTime(0.0001, time);
        noiseGain.gain.exponentialRampToValueAtTime(0.35, time + 0.005);
        noiseGain.gain.exponentialRampToValueAtTime(0.0001, time + 0.12);
    
        noise.connect(filter);
        filter.connect(noiseGain);
        noiseGain.connect(masterGain);
    
        registerSource(noise);
    
        noise.start(time);
        noise.stop(time + 0.15);
    
        const body = audioContext.createOscillator();
        const bodyGain = audioContext.createGain();
    
        body.type = "sine";
        body.frequency.setValueAtTime(180, time);
        body.frequency.exponentialRampToValueAtTime(110, time + 0.08);
    
        bodyGain.gain.setValueAtTime(0.0001, time);
        bodyGain.gain.exponentialRampToValueAtTime(0.25, time + 0.006);
        bodyGain.gain.exponentialRampToValueAtTime(0.0001, time + 0.15);
    
        body.connect(bodyGain);
        bodyGain.connect(masterGain);
    
        registerSource(body);
    
        body.start(time);
        body.stop(time + 0.2);
      }
    
      function playHat(time) {
        const noise = audioContext.createBufferSource();
        const gain = audioContext.createGain();
        const filter = audioContext.createBiquadFilter();
    
        noise.buffer = noiseBuffer;
        filter.type = "highpass";
        filter.frequency.value = 7000;
        filter.Q.value = 0.7;
    
        gain.gain.setValueAtTime(0.0001, time);
        gain.gain.exponentialRampToValueAtTime(0.18, time + 0.003);
        gain.gain.exponentialRampToValueAtTime(0.0001, time + 0.05);
    
        noise.connect(filter);
        filter.connect(gain);
        gain.connect(masterGain);
    
        registerSource(noise);
    
        noise.start(time);
        noise.stop(time + 0.06);
      }
    
      function playHits(hits) {
        try {
          if (!audioContext || !noiseBuffer || !masterGain) {
            return;
          }
    
          if (audioContext.state === "suspended" && typeof audioContext.resume === "function") {
            try {
              audioContext.resume().catch(function () {});
            } catch (error) {}
          }
    
          const time = audioContext.currentTime + 0.001;
    
          for (let i = 0; i < hits.length; i++) {
            const track = hits[i];
    
            if (track === 0) {
              playKick(time);
            } else if (track === 1) {
              playSnare(time);
            } else if (track === 2) {
              playHat(time);
            }
          }
        } catch (error) {}
      }
    
      function unlockAudioOnce() {
        ensureAudio();
        document.removeEventListener("click", unlockAudioOnce);
      }
    
      document.addEventListener("click", unlockAudioOnce);
    
      playButton.addEventListener("click", function () {
        ensureAudio();
    
        const wasPlaying = game.state().playing;
        game.press("play");
        const state = game.state();
    
        draw();
    
        if (!wasPlaying && state.playing) {
          restoreGain();
          startTimer();
          playHits(state.hits);
        }
      });
    
      stopButton.addEventListener("click", function () {
        game.press("stop");
        clearTimer();
        stopAllSounds();
        draw();
      });
    
      stepButtons.forEach(function (button) {
        button.addEventListener("click", function () {
          const track = Number(button.dataset.track);
          const step = Number(button.dataset.step);
    
          game.press([track, step]);
          draw();
        });
      });
    
      document.addEventListener("visibilitychange", function () {
        if (document.hidden) {
          game.press("stop");
          clearTimer();
          stopAllSounds();
          draw();
        }
      });
    
      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

    940 tokens: 149 read, 791 written · 2 min 16 s · 22.8 tok/s

    Summarize this in one sentence of at most 30 words.
    
    Starting April 7, the Larchmont Public Library will open at 7:20 a.m. instead of 10:55 a.m. on weekdays. The change follows a survey in which 77% of respondents asked for earlier hours. Weekend hours stay the same. The library will hire four part-time staff to cover the extra time, paid for by a county grant.
    After 77% asked for earlier openings, Larchmont Public Library will open weekdays at 7:20 a.m. starting April 7, hiring grant-funded part-time staff while weekend hours remain unchanged.
  • Meeting notes in three bulletsPassed

    641 tokens: 235 read, 406 written · 17 s · 26.4 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: Rafael, Ivy, Kim, Tomas.
    - Kim reported that the payment provider fixed the login bug; no action needed.
    - The launch date moves from November 14 to November 17 because the legal review is taking longer.
    - Tomas showed the new onboarding screens. Everyone liked them. Small copy changes only.
    - The marketing budget of $15,000 was approved by finance on Monday.
    - Rafael will own end-to-end testing from now on; Ivy hands over the test plan by Thursday.
    - Next sync is moved to Sunday at 10:00.
    - Coffee machine on floor 2 is broken again.
    - Launch date moves from November 14 to November 17 due to longer legal review.
    - Rafael owns end-to-end testing; Ivy hands over the test plan by Thursday.
    - Finance approved the $15,000 marketing budget on Monday.
  • Review sentiment and complaintPassed

    302 tokens: 160 read, 142 written · 6 s · 25.6 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 blender every day for a month. Honestly, the motor is powerful for its size and it has never once overheated. But the pulse button that came in the box cracked after two weeks, and support took 9 days to reply. I bought a replacement pulse button myself. Would I buy it again? Probably, but I'm annoyed.
    Sentiment: mixed
    Complaint: Cracked pulse button and slow support
  • Faithful summary of a studyPassed

    864 tokens: 179 read, 685 written · 24 s · 29.8 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, 510 adults with chronic migraine took either Soltide or a placebo for 12 weeks. Those on Soltide had 2.9 fewer headache days per month on average, compared with 0.4 fewer days for placebo. Nausea was the most common side effect, reported by 25% of the drug group. The authors note the trial lasted only 12 weeks and call for longer studies before any recommendation is made.
    In a 12-week randomized trial, 510 adults with chronic migraine took Soltide or placebo. Soltide averaged 2.9 fewer monthly headache days versus 0.4 fewer for placebo. Nausea was most common in the drug group at 25%. Authors note the short trial and call for longer studies before recommendation.
  • Action items from an email threadPassed

    639 tokens: 257 read, 382 written · 15 s · 28.2 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: Priya
    Hi all, quick recap of what's still open for the autumn summit. I'll send the revised contract to the hotel by Monday.
    
    From: Felix
    I can book the venue for the dinner if that helps?
    
    From: Zara
    Thanks Felix, 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: Laura
    I'll update the budget sheet with the new hotel price tonight.
    
    From: Priya
    Great. Oh, and I'll email the caterer about the vegetarian options. Felix, could you just double-check the date on the invitations? Actually never mind, I checked them this morning, they're correct.
    
    - Priya: send the revised contract to the hotel by Monday
    - Zara: book the venue for the dinner
    - Laura: update the budget sheet with the new hotel price tonight
    - Priya: email the caterer about the vegetarian options
Extracting 5 of 5
  • Fields from an email as JSONPassed

    263 tokens: 158 read, 105 written · 4 s · 29.8 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 Laura Mensah from Summit Dental. We'd love to visit your workshop. Could we meet on the 7th of June 2026, any time after lunch? We'll be nine people in total, including me. Best, Laura
    {
      "name": "Laura Mensah",
      "company": "Summit Dental",
      "meeting_date": "2026-06-07",
      "attendees": 9
    }
  • Every email address, oncePassed

    462 tokens: 182 read, 280 written · 10 s · 31.8 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 info@harbor-events.net for general questions, or to speakers@harbor-events.net if you are presenting. Our designer (ana.t@north-arc.io) made the poster. Billing questions: accounts@harbor-events.net. Again, presenters use speakers@harbor-events.net. Please don't write to ben at harbor dot net, that inbox is closed.
    info@harbor-events.net
    speakers@harbor-events.net
    ana.t@north-arc.io
    accounts@harbor-events.net
  • A list as CSVPassed

    354 tokens: 143 read, 211 written · 7 s · 35 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.
    
    Apples - 18 @ $7.35
    Olive oil (1 l) - 6 @ $4.90
    Milk (1 l) - 4 @ $6.50
    Peanut butter - 5 @ $5.40
    item,qty,price
    Apples,18,7.35
    Olive oil (1 l),6,4.90
    Milk (1 l),4,6.50
    Peanut butter,5,5.40
  • The real deadlinePassed

    305 tokens: 142 read, 163 written · 7 s · 25.6 tok/s

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

    579 tokens: 321 read, 258 written · 11 s · 27.9 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-10-05 09:24:00 INFO  server started on port 8080
    2025-10-05 09:27:51 WARN  config key "retries" is deprecated
    2025-10-05 09:32:35 INFO  user luis logged in
    2025-10-05 09:35:25 ERROR database connection lost
    2025-10-05 09:37:39 INFO  retrying in 30s
    2025-10-05 09:38:06 INFO  database reconnected
    2025-10-05 09:41:54 DEBUG cache hit ratio 0.98
    2025-10-05 09:43:03 ERROR payment webhook returned 504
    [
      {
        "time": "09:27:51",
        "level": "WARN",
        "message": "config key \"retries\" is deprecated"
      },
      {
        "time": "09:35:25",
        "level": "ERROR",
        "message": "database connection lost"
      },
      {
        "time": "09:43:03",
        "level": "ERROR",
        "message": "payment webhook returned 504"
      }
    ]
Following instructions 5 of 5
  • Exactly one wordPassed

    97 tokens: 63 read, 34 written · 2 s · 24.4 tok/s

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

    490 tokens: 132 read, 358 written · 12 s · 31.5 tok/s

    Write exactly three lines about a fjord. Use the word fjord in every line. Start every line with the letter l, and do not use any of these words: stadium, glacier, tundra, station, island, spring, pond, sea, castle or bakery. Every line must be entirely lowercase, and the third line must end with a question mark. Output only the three lines.
    lone fjord lies below quiet cliffs.
    long fjord reflects soft light.
    low fjord whispers to moon?
  • Exact JSON shapePassed

    231 tokens: 104 read, 127 written · 5 s · 29.4 tok/s

    Return a JSON object with exactly two keys: "words", a list of exactly 4 different lowercase words that each start with the letter k and use only the plain letters a to z, and "count", the number 4. Output only the JSON.
    {
      "words": [
        "kite",
        "kettle",
        "king",
        "kangaroo"
      ],
      "count": 4
    }
  • Sort a listPassed

    191 tokens: 86 read, 105 written · 4 s · 27.7 tok/s

    Sort these words alphabetically, ignoring case. Output only the sorted words, on one line separated by commas: Spinach, Potato, lemon, Carrot, grape.
    Carrot, grape, lemon, Potato, Spinach
  • A name with three rulesPassed

    445 tokens: 113 read, 332 written · 11 s · 30.8 tok/s

    Suggest a product name for a solar-powered pump. Rules: exactly two words, both capitalized, using only the plain letters A to Z, the first word starts with the letter N, the second word starts with the letter M, and the letter q must not appear anywhere. Output only the name.
    Nova Motor
Reasoning 5 of 5
  • Unit pricePassed

    223 tokens: 94 read, 129 written · 6 s · 25.1 tok/s

    A shop sells pencils at 4 for $1.20. How much do 18 pencils cost, in dollars? Work it out, then end with a line "ANSWER: <number>".
    4 pencils cost $1.20, so 1 pencil costs $1.20 ÷ 4 = $0.30.
    
    18 pencils cost 18 × $0.30 = $5.40.
    
    ANSWER: 5.40
  • Day and datePassed

    1,425 tokens: 110 read, 1,315 written · 54 s · 24.5 tok/s

    Today is Thursday, 19 February 2026. What day of the week, and what date, is it 348 days from today? Work it out, then end with a line "ANSWER: <day of the week>, <YYYY-MM-DD>".
    348 days from Thursday, 19 February 2026 is 49 weeks and 5 days later, so the weekday is Tuesday.
    
    For the date:
    - 19 February 2026 is day 50 of 2026.
    - There are 316 days from 19 February 2026 to 1 January 2027.
    - Remaining days after 1 January 2027: 348 − 316 = 32 days.
    - 1 January 2027 plus 32 days is 2 February 2027.
    
    ANSWER: Tuesday, 2027-02-02
  • Who owns each petPassed

    527 tokens: 240 read, 287 written · 10 s · 32.6 tok/s

    Five people, Ivy, Cal, Hal, Gus and Ben, each own exactly one of these pets: a cat, a dog, a fish, a bird and a rabbit. Each pet has one owner. Clues:
    - Cal owns the fish or the bird.
    - Gus does not own the bird.
    - Ben owns the cat.
    - Ivy owns the fish or the bird.
    - Cal owns the dog or the fish.
    - Hal does not own the cat.
    - Hal does not own the rabbit.
    - Gus does not own the dog.
    - Gus does not own the cat.
    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.
    Ben owns the cat. Since Cal must own the fish or bird and also the dog or fish, Cal owns the fish. Then Ivy must own the bird. Hal cannot own the rabbit, so Hal owns the dog, leaving Gus with the rabbit.
    
    ANSWER: Ben, Hal, Cal, Ivy, Gus
  • Arrival timePassed

    208 tokens: 106 read, 102 written · 6 s · 19.3 tok/s

    A train leaves at 15:15 and the trip takes 4 hours 35 minutes. At what time does it arrive? Work it out, then end with a line "ANSWER: <HH:MM>" in 24-hour time.
    15:15 + 4 hours 35 minutes = 19:50
    
    ANSWER: 19:50
  • Filling a tankPassed

    291 tokens: 126 read, 165 written · 7 s · 27 tok/s

    A tank holds 702 liters and starts empty. Pipe A adds 6 liters an hour, pipe B adds 27 liters an hour, and a drain takes 7 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 = 6 + 27 − 7 = 26 liters per hour.
    
    Time to fill = 702 ÷ 26 = 27 hours.
    
    ANSWER: 27
Reading code 4 of 4
  • What does it printPassed

    497 tokens: 125 read, 372 written · 15 s · 25.9 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][:3]
    
    print(f([5, 30, 35, 16, 13, 25]))
    The function sorts the list in ascending order, reverses it to descending order, and takes the first three elements:
    
    - Sorted: `[5, 13, 16, 25, 30, 35]`
    - Reversed: `[35, 30, 25, 16, 13, 5]`
    - First three: `[35, 30, 25]`
    
    ANSWER: 35, 30, 25
  • Trace a loopPassed

    861 tokens: 135 read, 726 written · 28 s · 26.9 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 % 2 == 0 or i % 3 == 0:
                total += i
        return total
    
    print(g(76))
    The program sums all numbers from 1 to 76 that are divisible by 2 or 3.
    
    Using inclusion-exclusion:
    
    - Sum of numbers divisible by 2:  
      \(2 + 4 + \cdots + 76 = 2(1 + 2 + \cdots + 38) = 1482\)
    
    - Sum of numbers divisible by 3:  
      \(3 + 6 + \cdots + 75 = 3(1 + 2 + \cdots + 25) = 975\)
    
    - Numbers divisible by both 2 and 3 are divisible by 6:  
      \(6 + 12 + \cdots + 72 = 6(1 + 2 + \cdots + 12) = 468\)
    
    So the result is:
    
    \[
    1482 + 975 - 468 = 1989
    \]
    
    ANSWER: 1989
  • Find the bugPassed

    682 tokens: 151 read, 531 written · 19 s · 28.9 tok/s

    The function add_up should return the sum of all the numbers in a list. 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 add_up(items):
        acc = 0
        for i in range(len(items) - 1):
            acc += items[i]
        return acc
    The loop runs from `0` up to `len(items) - 2`, so it skips the last item. The range should use `len(items)` so it includes every index.
    
    ANSWER:     for i in range(len(items)):
  • Run a query in your headPassed

    343 tokens: 185 read, 158 written · 8 s · 22.5 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      | 125
    2  | ana      | 40
    3  | ana      | 55
    4  | ben      | 80
    5  | cal      | 20
    6  | cal      | 55
    
    Query:
    SELECT customer, SUM(amount) AS total
    FROM orders
    GROUP BY customer
    HAVING SUM(amount) > 100
    ORDER BY total DESC;
    ben,205
Using tools 5 of 5
  • Call one toolPassed

    1,003 tokens: 774 read, 229 written · 11 s · 28.2 tok/s

    What's the weather in Oslo right now, in celsius?
    1. user
      What's the weather in Oslo right now, in celsius?
    2. assistant
      get_weather({"city":"Oslo","unit":"celsius"})
    3. tool
      {"city":"Oslo","conditions":"snowing","temperature":15,"unit":"celsius"}
    4. assistant
      It's currently snowing in Oslo, with a temperature of **15 °C**.
      
      One caveat: snow at 15 °C is physically inconsistent, so the reading may be unreliable (possibly a stale or mixed data source). I'd double-check before planning around it.
  • Don't call a tool when none is neededPassed

    494 tokens: 455 read, 39 written · 3 s · 28.2 tok/s

    What is 23 times 12?
    1. user
      What is 23 times 12?
    2. assistant
      23 × 12 = 276
  • Two calls for two answersPassed

    1,128 tokens: 901 read, 227 written · 9 s · 30.9 tok/s

    Convert 115 USD to EUR and to JPY.
    1. user
      Convert 115 USD to EUR and to JPY.
    2. assistant
      convert_currency({"amount":115,"from":"USD","to":"EUR"})
      convert_currency({"amount":115,"from":"USD","to":"JPY"})
    3. tool
      {"amount":106.28,"currency":"EUR"}
    4. tool
      {"amount":17059,"currency":"JPY"}
    5. assistant
      Using today's exchange rates:
      
      - **115 USD = 106.28 EUR**
      - **115 USD = 17,059 JPY**
  • Chain two toolsPassed

    1,560 tokens: 1,367 read, 193 written · 8 s · 30.6 tok/s

    What is the status of each order for the customer with the email sam.ortiz@example.com?
    1. user
      What is the status of each order for the customer with the email sam.ortiz@example.com?
    2. assistant
      find_customer({"email":"sam.ortiz@example.com"})
    3. tool
      {"customer_id":"C-4410","name":"Sam Ortiz"}
    4. assistant
      get_orders({"customer_id":"C-4410"})
    5. tool
      {"orders":[{"order_id":"A-70","status":"processing"},{"order_id":"A-97","status":"cancelled"}]}
    6. assistant
      Sam Ortiz (customer ID C-4410) has 2 orders:
      
      | Order ID | Status |
      |---|---|
      | A-70 | processing |
      | A-97 | cancelled |
  • Handle a failed call honestlyPassed

    1,174 tokens: 851 read, 323 written · 14 s · 25.8 tok/s

    Book a table for 2 people at Luigi's tonight at 20:00. 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:00. 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:00"})
    3. tool
      {"available_times":["19:30","21:30"],"error":"fully booked at that time"}
    4. assistant
      I couldn't book that time — **Luigi's is fully booked at 20:00 tonight**, so no reservation has been made.
      
      The available times that came back were:
      - **19:30**
      - **21:30**
      
      Would you like me to book either of these instead, or would you prefer I try a different restaurant?
Building pages 5 of 5
  • A small websitePassed

    3,959 tokens: 226 read, 3,733 written · 2 min 17 s · 27.5 tok/s

    Build a one-page website for a bakery called "Sugar & Sons". 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 Brioche, Banana bread, Pain au chocolat and Scone; 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">
    <title>Sugar &amp; Sons</title>
    <style>
      body {
        margin: 0;
        font-family: Georgia, "Times New Roman", serif;
        background-color: #fff8f2;
        color: #3d2c24;
        line-height: 1.5;
      }
    
      header {
        padding: 32px 20px 20px;
        background-color: #bd6a57;
        color: #fff8f2;
        border-bottom: 6px solid #f0c48f;
      }
    
      h1 {
        margin: 0 0 10px;
        font-size: 2.8rem;
        letter-spacing: 0.5px;
      }
    
      .tagline {
        margin: 0;
        font-style: italic;
      }
    
      nav {
        margin-top: 24px;
        display: flex;
        flex-wrap: wrap;
        gap: 14px;
      }
    
      nav a {
        color: #fff8f2;
        text-decoration: none;
        padding: 8px 14px;
        border-radius: 4px;
        background-color: #9b4f40;
        border: 1px solid #f0c48f;
      }
    
      nav a:hover,
      nav a:focus {
        background-color: #f0c48f;
        color: #3d2c24;
      }
    
      nav a.active {
        background-color: #f0c48f;
        color: #3d2c24;
        font-weight: bold;
      }
    
      main {
        max-width: 960px;
        margin: 0 auto;
        padding: 32px 20px;
      }
    
      section {
        margin-bottom: 36px;
        padding: 24px;
        background-color: #ffffff;
        border: 1px solid #e3cfc2;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(61, 44, 36, 0.08);
      }
    
      section h2 {
        margin-top: 0;
        font-size: 1.8rem;
        color: #7d483b;
      }
    
      #menu ul {
        list-style: none;
        margin: 0;
        padding: 0;
      }
    
      #menu li {
        margin: 0 0 12px;
        padding: 14px 16px;
        background-color: #fff3e7;
        border-left: 5px solid #bd6a57;
        border-radius: 4px;
      }
    
      #menu li strong {
        color: #7d483b;
        font-size: 1.05rem;
      }
    
      .menu-note {
        margin-top: 18px;
        font-size: 0.95rem;
        color: #654a3b;
      }
    
      footer {
        margin-top: 40px;
        padding: 32px 20px;
        background-color: #3d2c24;
        color: #fff8f2;
        border-top: 8px solid #bd6a57;
      }
    
      footer h2 {
        margin-top: 0;
        font-size: 1.6rem;
      }
    
      footer ul {
        list-style: none;
        margin: 0;
        padding: 0;
      }
    
      footer li {
        padding: 8px 0;
        border-bottom: 1px solid #5c463a;
      }
    
      .year {
        margin-top: 18px;
        font-size: 0.95rem;
        color: #f0c48f;
      }
    
      @media (max-width: 600px) {
        h1 {
          font-size: 2.1rem;
        }
    
        section {
          padding: 18px;
        }
      }
    </style>
    </head>
    <body>
    <header>
      <h1>Sugar &amp; Sons</h1>
      <p class="tagline">A neighbourhood bakery with slow-risen bread and small-batch treats.</p>
      <nav aria-label="Main navigation">
        <a href="#menu">Menu</a>
        <a href="#about">About</a>
        <a href="#visit">Visit</a>
      </nav>
    </header>
    
    <main>
      <section id="menu">
        <h2>Today’s Menu</h2>
        <ul>
          <li><strong>Brioche</strong> — Soft, golden loaf with a rich crumb and gentle sweetness.</li>
          <li><strong>Banana bread</strong> — Comforting slice made with ripe bananas and a moist texture.</li>
          <li><strong>Pain au chocolat</strong> — Flaky viennoiserie with two chocolate batons folded inside.</li>
          <li><strong>Scone</strong> — Crumbly, buttery bake best served with jam and cream.</li>
        </ul>
        <p class="menu-note">Daily specials may change depending on season and supply.</p>
      </section>
    
      <section id="about">
        <h2>About Sugar &amp; Sons</h2>
        <p>
          Sugar &amp; Sons began as a family recipe book, a small oven, and a belief that bread
          should be simple, honest, and worth slowing down for. Every loaf is shaped by hand,
          and every bake is made in small batches so the counter stays warm, fresh, and full of
          familiar smells.
        </p>
      </section>
    
      <section id="visit">
        <h2>Visit the Bakery</h2>
        <p>
          Find us on the corner for morning coffee, fresh bread, and something sweet to carry
          home. If the door is open, the kitchen is already running.
        </p>
      </section>
    </main>
    
    <footer>
      <h2>Opening Hours</h2>
      <ul>
        <li><strong>Monday:</strong> 7:00 AM – 4:00 PM</li>
        <li><strong>Tuesday:</strong> 7:00 AM – 4:00 PM</li>
        <li><strong>Wednesday:</strong> 7:00 AM – 4:00 PM</li>
        <li><strong>Thursday:</strong> 7:00 AM – 4:00 PM</li>
        <li><strong>Friday:</strong> 7:00 AM – 4:00 PM</li>
        <li><strong>Saturday:</strong> 7:30 AM – 3:00 PM</li>
        <li><strong>Sunday:</strong> 8:00 AM – 1:00 PM</li>
      </ul>
      <p class="year">&copy; <span id="year"></span> Sugar &amp; Sons</p>
    </footer>
    
    <script>
      const navLinks = document.querySelectorAll("nav a");
    
      navLinks.forEach(function (link) {
        link.addEventListener("click", function () {
          navLinks.forEach(function (item) {
            item.classList.remove("active");
          });
          link.classList.add("active");
        });
      });
    
      document.getElementById("year").textContent = new Date().getFullYear();
    </script>
    </body>
    </html>
  • A pricing table with a togglePassed

    4,719 tokens: 238 read, 4,481 written · 2 min 30 s · 30.1 tok/s

    Build a pricing page with three plans, in this order: Premium at $24 a month or $240 a year, Max at $27 a month or $270 a year and Pro at $37 a month or $370 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>
      :root {
        --bg: #0f172a;
        --panel: #111827;
        --panel-2: #172033;
        --text: #f8fafc;
        --muted: #cbd5e1;
        --accent: #38bdf8;
        --accent-2: #818cf8;
        --border: rgba(148, 163, 184, 0.22);
        --shadow: 0 18px 45px rgba(2, 6, 23, 0.45);
      }
    
      * {
        box-sizing: border-box;
      }
    
      body {
        margin: 0;
        min-height: 100vh;
        font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        color: var(--text);
        background:
          radial-gradient(circle at top left, rgba(56, 189, 248, 0.18), transparent 30%),
          radial-gradient(circle at top right, rgba(129, 140, 248, 0.16), transparent 28%),
          linear-gradient(135deg, #020617 0%, var(--bg) 55%, #111827 100%);
      }
    
      main {
        width: min(1120px, calc(100% - 40px));
        margin: 0 auto;
        padding: 72px 0 96px;
      }
    
      .header {
        max-width: 720px;
        margin-bottom: 36px;
      }
    
      .eyebrow {
        display: inline-block;
        margin: 0 0 16px;
        color: var(--accent);
        font-size: 14px;
        letter-spacing: 0.18em;
        text-transform: uppercase;
        font-weight: 700;
      }
    
      h1 {
        margin: 0 0 14px;
        font-size: clamp(34px, 5vw, 56px);
        line-height: 1.05;
        letter-spacing: -0.04em;
      }
    
      .subhead {
        margin: 0;
        color: var(--muted);
        line-height: 1.7;
        font-size: 17px;
      }
    
      .toolbar {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 16px;
        margin: 28px 0 30px;
      }
    
      #billing-toggle {
        appearance: none;
        border: 1px solid rgba(56, 189, 248, 0.45);
        background: linear-gradient(135deg, rgba(56, 189, 248, 0.18), rgba(129, 140, 248, 0.16));
        color: var(--text);
        border-radius: 999px;
        padding: 13px 18px;
        font-size: 15px;
        font-weight: 700;
        cursor: pointer;
        box-shadow: 0 12px 30px rgba(2, 6, 23, 0.32);
        transition: transform 180ms ease, box-shadow 180ms ease, background 180ms ease;
      }
    
      #billing-toggle:hover {
        transform: translateY(-2px);
        box-shadow: 0 16px 34px rgba(2, 6, 23, 0.38);
        background: linear-gradient(135deg, rgba(56, 189, 248, 0.24), rgba(129, 140, 248, 0.22));
      }
    
      #billing-toggle:active {
        transform: translateY(1px);
      }
    
      .note {
        color: var(--muted);
        font-size: 15px;
      }
    
      .plans {
        display: grid;
        grid-template-columns: repeat(3, minmax(0, 1fr));
        gap: 22px;
      }
    
      .plan {
        position: relative;
        overflow: hidden;
        padding: 30px;
        border: 1px solid var(--border);
        border-radius: 24px;
        background: linear-gradient(180deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0.03));
        box-shadow: var(--shadow);
      }
    
      .plan::before {
        content: "";
        position: absolute;
        inset: 0;
        background: linear-gradient(180deg, rgba(56, 189, 248, 0.10), transparent 42%);
        pointer-events: none;
      }
    
      .plan > * {
        position: relative;
        z-index: 1;
      }
    
      .plan h2 {
        margin: 0 0 12px;
        font-size: 28px;
        line-height: 1.1;
        letter-spacing: -0.03em;
      }
    
      .tagline {
        margin: 0 0 24px;
        color: var(--muted);
        line-height: 1.6;
      }
    
      .price {
        margin: 0 0 18px;
        font-size: 42px;
        line-height: 1;
        font-weight: 800;
        letter-spacing: -0.04em;
        color: var(--text);
      }
    
      .billing-label {
        margin: 0 0 22px;
        color: var(--accent);
        font-size: 14px;
        font-weight: 700;
        letter-spacing: 0.08em;
        text-transform: uppercase;
      }
    
      .features {
        margin: 0 0 26px;
        padding: 0;
        list-style: none;
      }
    
      .features li {
        margin: 12px 0;
        color: var(--muted);
        line-height: 1.5;
        padding-left: 28px;
        position: relative;
      }
    
      .features li::before {
        content: "✓";
        position: absolute;
        left: 0;
        color: var(--accent);
        font-weight: 800;
      }
    
      .cta {
        display: inline-block;
        padding: 12px 18px;
        border-radius: 14px;
        border: 1px solid var(--border);
        background: rgba(255, 255, 255, 0.07);
        color: var(--text);
        font-weight: 700;
        text-decoration: none;
      }
    
      .featured {
        border-color: rgba(129, 140, 248, 0.42);
        background:
          radial-gradient(circle at top right, rgba(56, 189, 248, 0.15), transparent 40%),
          linear-gradient(180deg, rgba(129, 140, 248, 0.14), rgba(255, 255, 255, 0.03));
      }
    
      .badge {
        position: absolute;
        top: 18px;
        right: 18px;
        padding: 7px 12px;
        border-radius: 999px;
        font-size: 12px;
        font-weight: 800;
        letter-spacing: 0.08em;
        text-transform: uppercase;
        color: #0f172a;
        background: linear-gradient(135deg, var(--accent), var(--accent-2));
      }
    
      @media (max-width: 980px) {
        .plans {
          grid-template-columns: 1fr;
        }
      }
    </style>
    </head>
    <body>
      <main>
        <div class="header">
          <p class="eyebrow">Simple plans</p>
          <h1>Choose the plan that fits your workflow</h1>
          <p class="subhead">Transparent pricing for every stage. Toggle between monthly and yearly billing to compare costs.</p>
        </div>
    
        <div class="toolbar">
          <button id="billing-toggle">Switch to yearly</button>
          <span class="note">Prices update instantly.</span>
        </div>
    
        <section class="plans">
          <article class="plan">
            <h2>Premium</h2>
            <p class="tagline">A focused option for individuals getting started.</p>
            <div class="price" data-monthly="$24 / month" data-yearly="$240 / year">$24 / month</div>
            <p class="billing-label">Current billing</p>
            <ul class="features">
              <li>Essential planning tools</li>
              <li>Standard dashboard</li>
              <li>Email support</li>
            </ul>
            <span class="cta">Choose Premium</span>
          </article>
    
          <article class="plan featured">
            <span class="badge">Popular</span>
            <h2>Max</h2>
            <p class="tagline">A balanced plan for growing teams and active projects.</p>
            <div class="price" data-monthly="$27 / month" data-yearly="$270 / year">$27 / month</div>
            <p class="billing-label">Current billing</p>
            <ul class="features">
              <li>Advanced reporting</li>
              <li>Team collaboration</li>
              <li>Priority support</li>
            </ul>
            <span class="cta">Choose Max</span>
          </article>
    
          <article class="plan">
            <h2>Pro</h2>
            <p class="tagline">A powerful option for demanding workflows and scale.</p>
            <div class="price" data-monthly="$37 / month" data-yearly="$370 / year">$37 / month</div>
            <p class="billing-label">Current billing</p>
            <ul class="features">
              <li>Full automation suite</li>
              <li>Advanced controls</li>
              <li>Dedicated assistance</li>
            </ul>
            <span class="cta">Choose Pro</span>
          </article>
        </section>
      </main>
    
      <script>
        (function () {
          var button = document.getElementById("billing-toggle");
          var prices = document.querySelectorAll(".price");
          var yearly = false;
    
          button.addEventListener("click", function () {
            yearly = !yearly;
    
            for (var i = 0; i < prices.length; i++) {
              prices[i].textContent = yearly
                ? prices[i].getAttribute("data-yearly")
                : prices[i].getAttribute("data-monthly");
            }
    
            button.textContent = yearly ? "Switch to monthly" : "Switch to yearly";
          });
        }());
      </script>
    </body>
    </html>
  • An accessible sign-up formPassed

    4,169 tokens: 288 read, 3,881 written · 2 min 9 s · 30.3 tok/s

    Build a sign-up form for Pine Studio. 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>Pine Studio Sign Up</title>
      <style>
        :root {
          --ink: #18302b;
          --muted: #5f756f;
          --pine: #215d52;
          --pine-deep: #143a32;
          --sage: #d8e7df;
          --paper: #f8f7f3;
          --error: #a33f33;
          --focus: #7fb5a6;
        }
    
        * {
          box-sizing: border-box;
        }
    
        body {
          margin: 0;
          min-height: 100vh;
          font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
          color: var(--ink);
          background:
            linear-gradient(135deg, #eef3ef 0%, #f8f7f3 45%, #e7efe8 100%);
        }
    
        body::before {
          content: "";
          position: fixed;
          inset: 0;
          pointer-events: none;
          background:
            radial-gradient(circle at 12% 18%, rgba(131, 175, 156, 0.28), transparent 28rem),
            radial-gradient(circle at 88% 10%, rgba(184, 207, 189, 0.22), transparent 24rem),
            repeating-linear-gradient(
              90deg,
              rgba(33, 93, 82, 0.035) 0,
              rgba(33, 93, 82, 0.035) 1px,
              transparent 1px,
              transparent 112px
            );
        }
    
        main {
          position: relative;
          min-height: 100vh;
          display: grid;
          place-items: center;
          padding: 2rem 1rem;
        }
    
        .page {
          width: min(100%, 820px);
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 1.25rem;
          align-items: stretch;
        }
    
        .identity,
        .signup-panel {
          background: rgba(255, 255, 255, 0.82);
          border: 1px solid rgba(33, 93, 82, 0.18);
          box-shadow: 0 24px 60px rgba(24, 48, 43, 0.12);
        }
    
        .identity {
          padding: 2rem 2rem 2.25rem;
          border-radius: 28px 8px 28px 8px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          overflow: hidden;
          position: relative;
        }
    
        .identity::after {
          content: "";
          position: absolute;
          width: 28rem;
          height: 28rem;
          right: -12rem;
          bottom: -14rem;
          border-radius: 50%;
          background: linear-gradient(160deg, rgba(33, 93, 82, 0.22), rgba(190, 214, 198, 0.08));
          pointer-events: none;
        }
    
        .brand {
          margin: 0;
          font-size: clamp(2.6rem, 6vw, 4.6rem);
          line-height: 0.92;
          letter-spacing: -0.06em;
          color: var(--pine-deep);
          font-weight: 800;
        }
    
        .brand span {
          display: block;
          color: var(--pine);
        }
    
        .eyebrow {
          margin: 0 0 1.75rem;
          font-size: 0.82rem;
          font-weight: 700;
          letter-spacing: 0.18em;
          text-transform: uppercase;
          color: var(--muted);
        }
    
        .lede {
          max-width: 36ch;
          margin: 1.25rem 0 2rem;
          color: var(--muted);
          font-size: 1.02rem;
          line-height: 1.55;
        }
    
        .mark {
          display: inline-flex;
          align-items: center;
          gap: 0.75rem;
          font-weight: 700;
          color: var(--pine);
          letter-spacing: 0.02em;
          z-index: 1;
        }
    
        .pine-shape {
          width: 42px;
          height: 42px;
          border-radius: 14px;
          background: linear-gradient(145deg, #2e6b5e, #153b34);
          position: relative;
          box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.18);
        }
    
        .pine-shape::before,
        .pine-shape::after {
          content: "";
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          width: 0;
          height: 0;
          border-style: solid;
        }
    
        .pine-shape::before {
          top: 8px;
          border-width: 0 12px 18px 12px;
          border-color: transparent transparent rgba(223, 238, 229, 0.86) transparent;
        }
    
        .pine-shape::after {
          top: 17px;
          border-width: 0 15px 20px 15px;
          border-color: transparent transparent rgba(126, 174, 153, 0.55) transparent;
        }
    
        .signup-panel {
          padding: 2rem;
          border-radius: 8px 28px 8px 28px;
        }
    
        .form-title {
          margin: 0 0 0.5rem;
          font-size: 1.35rem;
          letter-spacing: -0.02em;
          color: var(--pine-deep);
        }
    
        .form-intro {
          margin: 0 0 1.75rem;
          color: var(--muted);
          line-height: 1.5;
        }
    
        form {
          display: grid;
          gap: 1rem;
        }
    
        .field {
          display: grid;
          gap: 0.5rem;
        }
    
        label {
          font-size: 0.9rem;
          font-weight: 700;
          color: var(--pine-deep);
        }
    
        input {
          width: 100%;
          padding: 0.9rem 1rem;
          border: 1px solid rgba(33, 93, 82, 0.24);
          border-radius: 14px;
          background: #fffdf9;
          color: var(--ink);
          font: inherit;
          transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
        }
    
        input:focus {
          outline: none;
          border-color: var(--pine);
          box-shadow: 0 0 0 4px rgba(127, 181, 166, 0.22);
          background: #ffffff;
        }
    
        input[aria-invalid="true"] {
          border-color: var(--error);
          box-shadow: 0 0 0 4px rgba(163, 63, 51, 0.12);
        }
    
        .actions {
          margin-top: 0.5rem;
        }
    
        button {
          width: 100%;
          border: 0;
          border-radius: 16px;
          padding: 1rem 1.25rem;
          background: linear-gradient(135deg, var(--pine), var(--pine-deep));
          color: white;
          font: inherit;
          font-weight: 800;
          letter-spacing: 0.02em;
          cursor: pointer;
          box-shadow: 0 14px 28px rgba(20, 58, 50, 0.18);
          transition: transform 140ms ease, box-shadow 140ms ease, background 140ms ease;
        }
    
        button:hover {
          transform: translateY(-1px);
          box-shadow: 0 18px 32px rgba(20, 58, 50, 0.22);
        }
    
        button:active {
          transform: translateY(1px);
          box-shadow: 0 10px 20px rgba(20, 58, 50, 0.16);
        }
    
        button:focus-visible,
        input:focus-visible {
          outline: 2px solid var(--focus);
          outline-offset: 2px;
        }
    
        .status {
          min-height: 4.25rem;
          margin: 1.1rem 0 0;
          padding: 1rem 1.1rem;
          border: 1px solid rgba(33, 93, 82, 0.16);
          border-radius: 16px;
          background: rgba(226, 236, 229, 0.52);
          color: var(--ink);
          font-size: 0.95rem;
          line-height: 1.5;
        }
    
        .status.has-error {
          border-color: rgba(163, 63, 51, 0.3);
          background: rgba(255, 239, 236, 0.76);
          color: #7f2f27;
        }
    
        .rules {
          display: flex;
          flex-wrap: wrap;
          gap: 0.5rem;
          margin-top: 1rem;
        }
    
        .rule {
          padding: 0.45rem 0.7rem;
          border-radius: 999px;
          background: rgba(33, 93, 82, 0.08);
          color: var(--pine-deep);
          font-size: 0.82rem;
          font-weight: 700;
        }
    
        @media (max-width: 760px) {
          .page {
            grid-template-columns: 1fr;
          }
    
          .identity,
          .signup-panel {
            border-radius: 24px;
          }
        }
      </style>
    </head>
    <body>
      <main>
        <section class="page">
          <div class="identity">
            <div>
              <p class="eyebrow">Create your account</p>
              <h1 class="brand">Pine <span>Studio</span></h1>
              <p class="lede">Join a calm, practical workspace built for focused project teams.</p>
            </div>
            <div class="mark" aria-hidden="true">
              <span class="pine-shape"></span>
              <span>Join today</span>
            </div>
          </div>
    
          <div class="signup-panel">
            <h2 class="form-title">Sign up</h2>
            <p class="form-intro">Enter your details to create your Pine Studio account.</p>
    
            <form id="signup" novalidate>
              <div class="field">
                <label for="name">Name</label>
                <input id="name" name="name" autocomplete="name">
              </div>
    
              <div class="field">
                <label for="email">Email</label>
                <input id="email" name="email" type="email" autocomplete="email">
              </div>
    
              <div class="field">
                <label for="password">Password</label>
                <input id="password" name="password" type="password" minlength="8" autocomplete="new-password">
              </div>
    
              <div class="actions">
                <button type="submit">Create account</button>
              </div>
    
              <div class="rules">
                <span class="rule">8+ character password</span>
                <span class="rule">Valid email required</span>
              </div>
            </form>
    
            <p id="status" role="status"></p>
          </div>
        </section>
      </main>
    
      <script>
        const form = document.getElementById("signup");
        const status = document.getElementById("status");
        const nameInput = document.getElementById("name");
        const emailInput = document.getElementById("email");
        const passwordInput = document.getElementById("password");
    
        const isValidEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
    
        const clearStatus = () => {
          status.textContent = "";
          status.classList.remove("has-error");
        };
    
        const showError = (message) => {
          status.textContent = message;
          status.classList.add("has-error");
        };
    
        form.addEventListener("submit", (event) => {
          event.preventDefault();
    
          clearStatus();
    
          const name = nameInput.value.trim();
          const email = emailInput.value.trim();
          const password = passwordInput.value;
    
          if (!isValidEmail(email)) {
            showError("The email address is not valid.");
            return;
          }
    
          if (password.length < 8) {
            showError("The password must be at least 8 characters long.");
            return;
          }
    
          clearStatus();
        });
      </script>
    </body>
    </html>
  • A to-do app that remembersPassed

    3,375 tokens: 220 read, 3,155 written · 3 min 37 s · 20.6 tok/s

    Build a to-do list app called "Camp jobs". 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">
      <title>Camp jobs</title>
      <style>
        body {
          margin: 0;
          padding: 24px;
          background: #f4f7fb;
          color: #1f2937;
          font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
        }
    
        .app {
          max-width: 640px;
          margin: 0 auto;
          background: #ffffff;
          border: 1px solid #d8e1ec;
          border-radius: 12px;
          padding: 24px;
          box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08);
        }
    
        h1 {
          margin: 0 0 16px;
          font-size: 28px;
          line-height: 1.2;
        }
    
        .controls {
          display: flex;
          gap: 10px;
          margin-bottom: 20px;
        }
    
        #new-task {
          flex: 1;
          min-width: 0;
          padding: 10px 12px;
          border: 1px solid #c6d3e3;
          border-radius: 8px;
          font: inherit;
          background: #ffffff;
          color: #111827;
        }
    
        #new-task:focus,
        #add:focus,
        .remove:focus {
          outline: 2px solid #2563eb;
          outline-offset: 2px;
        }
    
        #add {
          padding: 10px 16px;
          border: 0;
          border-radius: 8px;
          background: #2563eb;
          color: #ffffff;
          font: inherit;
          font-weight: 600;
          cursor: pointer;
        }
    
        #add:hover {
          background: #1d4ed8;
        }
    
        #tasks {
          margin: 0;
          padding: 0;
          list-style: none;
        }
    
        #tasks li {
          display: flex;
          gap: 12px;
          align-items: center;
          justify-content: space-between;
          padding: 12px 14px;
          border: 1px solid #dce5f1;
          border-radius: 8px;
          margin-bottom: 10px;
          background: #fbfcfe;
        }
    
        #tasks li span {
          flex: 1;
          min-width: 0;
          overflow-wrap: anywhere;
        }
    
        .remove {
          padding: 8px 10px;
          border: 0;
          border-radius: 6px;
          background: #fee2e2;
          color: #991b1b;
          font: inherit;
          font-weight: 600;
          cursor: pointer;
        }
    
        .remove:hover {
          background: #fecaca;
        }
    
        .empty {
          color: #6b7280;
          margin: 12px 0 0;
        }
      </style>
    </head>
    <body>
      <main class="app">
        <h1>Camp jobs</h1>
    
        <div class="controls">
          <input id="new-task" type="text" placeholder="Add a camp job" autocomplete="off">
          <button id="add" type="button">Add</button>
        </div>
    
        <ul id="tasks"></ul>
        <p class="empty" id="empty-note">No jobs yet.</p>
      </main>
    
      <script>
        const input = document.getElementById("new-task");
        const addButton = document.getElementById("add");
        const list = document.getElementById("tasks");
        const emptyNote = document.getElementById("empty-note");
    
        let tasks = loadTodos();
    
        renderAll();
    
        addButton.addEventListener("click", addTask);
    
        input.addEventListener("keydown", function (event) {
          if (event.key === "Enter") {
            addTask();
          }
        });
    
        list.addEventListener("click", function (event) {
          const button = event.target.closest(".remove");
          if (!button) {
            return;
          }
    
          const item = button.closest("li");
          if (!item) {
            return;
          }
    
          const index = Number(item.dataset.index);
          if (!Number.isInteger(index)) {
            return;
          }
    
          tasks.splice(index, 1);
          saveTodos();
          renderAll();
        });
    
        function addTask() {
          const text = input.value.trim();
          if (text === "") {
            return;
          }
    
          tasks.push(text);
          saveTodos();
    
          const item = createTaskItem(text, tasks.length - 1);
          list.appendChild(item);
    
          input.value = "";
          input.focus();
          updateEmptyNote();
        }
    
        function renderAll() {
          list.innerHTML = "";
    
          tasks.forEach(function (task, index) {
            list.appendChild(createTaskItem(task, index));
          });
    
          updateEmptyNote();
        }
    
        function createTaskItem(text, index) {
          const item = document.createElement("li");
          item.dataset.index = String(index);
    
          const label = document.createElement("span");
          label.textContent = text;
    
          const removeButton = document.createElement("button");
          removeButton.type = "button";
          removeButton.className = "remove";
          removeButton.textContent = "Remove";
          removeButton.setAttribute("aria-label", "Remove task: " + text);
    
          item.appendChild(label);
          item.appendChild(removeButton);
    
          return item;
        }
    
        function updateEmptyNote() {
          emptyNote.textContent = tasks.length === 0 ? "No jobs yet." : "Add another job above.";
        }
    
        function saveTodos() {
          try {
            localStorage.setItem("todos", JSON.stringify(tasks));
          } catch (error) {
            emptyNote.textContent = "Could not save tasks in this browser.";
          }
        }
    
        function loadTodos() {
          try {
            const saved = localStorage.getItem("todos");
            if (saved === null) {
              return [];
            }
    
            const parsed = JSON.parse(saved);
    
            if (Array.isArray(parsed)) {
              return parsed.map(String);
            }
    
            return [];
          } catch (error) {
            return [];
          }
        }
      </script>
    </body>
    </html>
  • A bar chart in SVGPassed

    4,917 tokens: 272 read, 4,645 written · 2 min 42 s · 29.1 tok/s

    Draw an inline SVG bar chart of tea sold, in this order: Wed 24, Thu 44, Fri 8, Sat 26 and Sun 22. 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>Tea Sold</title>
    </head>
    <body>
    <svg width="320" height="130" role="img" aria-label="Bar chart showing tea sold: Wednesday 24, Thursday 44, Friday 8, Saturday 26, Sunday 22">
      <title>Tea sold from Wednesday to Sunday</title>
    
      <rect class="bar" x="20" y="66" width="40" height="24" fill="#4c7f5d"></rect>
      <rect class="bar" x="80" y="46" width="40" height="44" fill="#4c7f5d"></rect>
      <rect class="bar" x="140" y="82" width="40" height="8" fill="#4c7f5d"></rect>
      <rect class="bar" x="200" y="64" width="40" height="26" fill="#4c7f5d"></rect>
      <rect class="bar" x="260" y="68" width="40" height="22" fill="#4c7f5d"></rect>
    
      <text x="40" y="106" text-anchor="middle" font-family="sans-serif" font-size="14" fill="#222222">Wed</text>
      <text x="100" y="106" text-anchor="middle" font-family="sans-serif" font-size="14" fill="#222222">Thu</text>
      <text x="160" y="106" text-anchor="middle" font-family="sans-serif" font-size="14" fill="#222222">Fri</text>
      <text x="220" y="106" text-anchor="middle" font-family="sans-serif" font-size="14" fill="#222222">Sat</text>
      <text x="280" y="106" text-anchor="middle" font-family="sans-serif" font-size="14" fill="#222222">Sun</text>
    </svg>
    </body>
    </html>
Building games 4 of 4
  • Build 2048Passed

    21,752 tokens: 501 read, 21,251 written · 15 min 9 s · 23.5 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, 4, 2, 0]
    [0, 0, 0, 8]
    [0, 0, 2, 4]
    [0, 0, 2, 32]
    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">
    <title>2048</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body {
        margin: 0;
        font-family: Arial, sans-serif;
        background: #faf8ef;
        color: #776e65;
      }
      .wrap {
        max-width: 460px;
        margin: 0 auto;
        padding: 18px;
      }
      .top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
        margin-bottom: 14px;
      }
      h1 {
        margin: 0;
        font-size: 2rem;
        color: #776e65;
      }
      .score-box {
        background: #bbada0;
        color: #fff;
        padding: 8px 12px;
        border-radius: 6px;
        min-width: 90px;
        text-align: center;
      }
      .label {
        display: block;
        font-size: 0.75rem;
        text-transform: uppercase;
      }
      #score {
        font-weight: bold;
      }
      button {
        border: 0;
        border-radius: 6px;
        background: #8f7a66;
        color: #f9f6f2;
        padding: 8px 12px;
        font: inherit;
        cursor: pointer;
      }
      button:hover {
        background: #9b8772;
      }
      .board {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 8px;
        width: min(400px, calc(100vw - 36px));
        height: min(400px, calc(100vw - 36px));
        background: #bbada0;
        padding: 8px;
        border-radius: 8px;
      }
      .cell {
        width: 100%;
        height: 100%;
        background: #cdc1b4;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
      }
      .tile {
        color: #fff;
        font-size: min(7vw, 1.9rem);
      }
      .tile[data-value="2"] { background: #eee4da; color: #776e65; }
      .tile[data-value="4"] { background: #ede0c8; color: #776e65; }
      .tile[data-value="8"] { background: #f2b179; }
      .tile[data-value="16"] { background: #f59563; }
      .tile[data-value="32"] { background: #f67c5f; }
      .tile[data-value="64"] { background: #f65e3b; }
      .tile[data-value="128"],
      .tile[data-value="256"],
      .tile[data-value="512"] {
        background: #edcf72;
        font-size: min(6vw, 1.55rem);
      }
      .tile[data-value="1024"],
      .tile[data-value="2048"] {
        background: #edc22e;
        font-size: min(5vw, 1.25rem);
      }
      .tile[data-value="4096"],
      .tile[data-value="8192"],
      .tile[data-value="16384"],
      .tile[data-value="32768"],
      .tile[data-value="65536"] {
        background: #3c3a32;
        font-size: min(4vw, 1rem);
      }
      .tile:not([data-value]) {
        background: #3c3a32;
        font-size: min(4vw, 1rem);
      }
      .status {
        min-height: 1.5rem;
        margin-top: 10px;
        font-weight: bold;
        color: #e0705f;
      }
      .help {
        margin-top: 8px;
        color: #8f7a66;
      }
    </style>
    </head>
    <body>
      <main class="wrap">
        <header class="top">
          <h1>2048</h1>
          <div class="score-box">
            <span class="label">score</span>
            <span id="score">0</span>
          </div>
          <button id="restart" type="button">Restart</button>
        </header>
    
        <div id="board" class="board" aria-label="2048 board"></div>
        <div id="status" class="status"></div>
        <p class="help">Use the arrow keys.</p>
      </main>
    
      <script id="game">
        function createGame() {
          var board = [
            [32, 4, 2, 0],
            [0, 0, 0, 8],
            [0, 0, 2, 4],
            [0, 0, 2, 32]
          ];
          var score = 0;
    
          function cloneBoard(b) {
            var out = [];
            var r, c;
            for (r = 0; r < 4; r++) {
              var row = [];
              for (c = 0; c < 4; c++) {
                row.push(b[r][c]);
              }
              out.push(row);
            }
            return out;
          }
    
          function addTwo() {
            var r, c;
            for (r = 0; r < 4; r++) {
              for (c = 0; c < 4; c++) {
                if (board[r][c] === 0) {
                  board[r][c] = 2;
                  return true;
                }
              }
            }
            return false;
          }
    
          addTwo();
          addTwo();
    
          function slide(line) {
            var values = [];
            var i;
            for (i = 0; i < line.length; i++) {
              if (line[i] !== 0) {
                values.push(line[i]);
              }
            }
    
            var out = [];
            var gain = 0;
    
            i = 0;
            while (i < values.length) {
              if (i + 1 < values.length && values[i] === values[i + 1]) {
                var merged = values[i] * 2;
                out.push(merged);
                gain += merged;
                i += 2;
              } else {
                out.push(values[i]);
                i += 1;
              }
            }
    
            while (out.length < line.length) {
              out.push(0);
            }
    
            return { line: out, gain: gain };
          }
    
          function slideBoard(b, dir) {
            var next = cloneBoard(b);
            var gain = 0;
            var r, c, i, line, res;
    
            if (dir === "left") {
              for (r = 0; r < 4; r++) {
                res = slide(next[r].slice());
                next[r] = res.line;
                gain += res.gain;
              }
            } else if (dir === "right") {
              for (r = 0; r < 4; r++) {
                line = next[r].slice().reverse();
                res = slide(line);
                next[r] = res.line.slice().reverse();
                gain += res.gain;
              }
            } else if (dir === "up") {
              for (c = 0; c < 4; c++) {
                line = [];
                for (r = 0; r < 4; r++) {
                  line.push(next[r][c]);
                }
    
                res = slide(line);
    
                for (r = 0; r < 4; r++) {
                  next[r][c] = res.line[r];
                }
    
                gain += res.gain;
              }
            } else if (dir === "down") {
              for (c = 0; c < 4; c++) {
                line = [];
                for (r = 3; r >= 0; r--) {
                  line.push(next[r][c]);
                }
    
                res = slide(line);
    
                for (r = 3, i = 0; r >= 0; r--, i++) {
                  next[r][c] = res.line[i];
                }
    
                gain += res.gain;
              }
            }
    
            return { board: next, gain: gain };
          }
    
          function boardsEqual(a, b) {
            var r, c;
            for (r = 0; r < 4; r++) {
              for (c = 0; c < 4; c++) {
                if (a[r][c] !== b[r][c]) {
                  return false;
                }
              }
            }
            return true;
          }
    
          function canMove() {
            var dirs = ["left", "right", "up", "down"];
            var i, res;
            for (i = 0; i < dirs.length; i++) {
              res = slideBoard(board, dirs[i]);
              if (!boardsEqual(board, res.board)) {
                return true;
              }
            }
            return false;
          }
    
          function state() {
            return {
              board: cloneBoard(board),
              score: score,
              over: !canMove()
            };
          }
    
          function move(dir) {
            if (!canMove()) {
              return false;
            }
    
            var res = slideBoard(board, dir);
    
            if (boardsEqual(board, res.board)) {
              return false;
            }
    
            board = res.board;
            score += res.gain;
            addTwo();
    
            return true;
          }
    
          return {
            move: move,
            state: state
          };
        }
      </script>
    
      <script>
        (function () {
          var game = createGame();
    
          var boardEl = document.getElementById("board");
          var scoreEl = document.getElementById("score");
          var statusEl = document.getElementById("status");
          var restartEl = document.getElementById("restart");
    
          var keyDirections = {
            ArrowLeft: "left",
            ArrowRight: "right",
            ArrowUp: "up",
            ArrowDown: "down"
          };
    
          function render() {
            var current = game.state();
    
            scoreEl.textContent = current.score;
            statusEl.textContent = current.over ? "Game over" : "";
    
            boardEl.innerHTML = "";
    
            for (var r = 0; r < 4; r++) {
              for (var c = 0; c < 4; c++) {
                var value = current.board[r][c];
                var cell = document.createElement("div");
    
                if (value === 0) {
                  cell.className = "cell";
                } else {
                  cell.className = "cell tile";
                  cell.setAttribute("data-value", String(value));
                  cell.textContent = String(value);
                }
    
                boardEl.appendChild(cell);
              }
            }
          }
    
          function handleKey(event) {
            var dir = keyDirections[event.key];
            if (!dir) {
              return;
            }
    
            event.preventDefault();
            game.move(dir);
            render();
          }
    
          function restart() {
            game = createGame();
            render();
          }
    
          document.addEventListener("keydown", handleKey);
          restartEl.addEventListener("click", restart);
    
          render();
        })();
      </script>
    </body>
    </html>
  • Build SnakePassed

    17,042 tokens: 497 read, 16,545 written · 9 min 39 s · 28.7 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 [[5, 3], [5, 2], [5, 1]], moving down, food at [4, 2], 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">
      <title>Snake</title>
      <style>
        * {
          box-sizing: border-box;
        }
    
        body {
          margin: 0;
          min-height: 100vh;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #0f172a;
          color: #e2e8f0;
          font-family: ui-sans-serif, system-ui, sans-serif;
        }
    
        main {
          padding: 24px;
          background: #111827;
          border-radius: 18px;
          box-shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
        }
    
        h1 {
          margin: 0 0 16px;
          font-size: 1.25rem;
          font-weight: 700;
          letter-spacing: 0.02em;
        }
    
        .board {
          display: grid;
          grid-template-columns: repeat(10, 34px);
          grid-template-rows: repeat(10, 34px);
          gap: 2px;
          padding: 4px;
          border-radius: 12px;
          background: #1f2937;
          border: 1px solid #334155;
        }
    
        .cell {
          width: 34px;
          height: 34px;
          border-radius: 6px;
          background: #0b1220;
        }
    
        .cell.food {
          background: #f43f5e;
        }
    
        .cell.body {
          background: #22c55e;
        }
    
        .cell.head {
          background: #86efac;
          box-shadow: inset 0 0 0 2px #4ade80;
        }
    
        .meta {
          margin-top: 14px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 12px;
          font-size: 0.95rem;
        }
    
        #status {
          font-variant-numeric: tabular-nums;
        }
    
        #restart {
          border: 0;
          border-radius: 10px;
          padding: 8px 12px;
          background: #334155;
          color: #e2e8f0;
          cursor: pointer;
          font: inherit;
        }
    
        #restart:hover {
          background: #475569;
        }
      </style>
    </head>
    <body>
      <main>
        <h1>Snake</h1>
        <div id="board" class="board"></div>
        <div class="meta">
          <span id="status">Score: 0 · Arrow keys to move</span>
          <button id="restart" type="button">Restart</button>
        </div>
      </main>
    
      <script id="game">
    function createGame() {
      var SIZE = 10;
      var snake = [[5, 3], [5, 2], [5, 1]];
      var food = [4, 2];
      var score = 0;
      var over = false;
      var direction = "down";
    
      function isDirection(d) {
        return d === "up" || d === "down" || d === "left" || d === "right";
      }
    
      function isOpposite(a, b) {
        return (a === "up" && b === "down") ||
               (a === "down" && b === "up") ||
               (a === "left" && b === "right") ||
               (a === "right" && b === "left");
      }
    
      function deltaFor(d) {
        if (d === "up") return [0, -1];
        if (d === "down") return [0, 1];
        if (d === "left") return [-1, 0];
        return [1, 0];
      }
    
      function sameCell(a, b) {
        return a[0] === b[0] && a[1] === b[1];
      }
    
      function nextFood(head) {
        var occupied = {};
        for (var i = 0; i < snake.length; i++) {
          occupied[snake[i][0] + "," + snake[i][1]] = true;
        }
    
        var startIndex = head[1] * SIZE + head[0];
    
        for (var offset = 1; offset <= SIZE * SIZE; offset++) {
          var index = (startIndex + offset) % (SIZE * SIZE);
          var x = index % SIZE;
          var y = Math.floor(index / SIZE);
    
          if (!occupied[x + "," + y]) {
            return [x, y];
          }
        }
    
        return [head[0], head[1]];
      }
    
      function applyMove(moveDirection) {
        var head = snake[0];
        var delta = deltaFor(moveDirection);
        var x = head[0] + delta[0];
        var y = head[1] + delta[1];
    
        if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) {
          over = true;
          return;
        }
    
        var next = [x, y];
        var eats = sameCell(next, food);
        var collisionCheckLimit = eats ? snake.length : snake.length - 1;
    
        for (var i = 0; i < collisionCheckLimit; i++) {
          if (sameCell(snake[i], next)) {
            over = true;
            return;
          }
        }
    
        if (eats) {
          snake.unshift(next);
          score++;
          food = nextFood(next);
        } else {
          snake.pop();
          snake.unshift(next);
        }
      }
    
      function step(dir) {
        if (over) return;
        if (!isDirection(dir)) return;
    
        if (!isOpposite(dir, direction)) {
          direction = dir;
        }
    
        applyMove(direction);
      }
    
      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 SIZE = 10;
      var game = createGame();
      var board = document.getElementById("board");
      var status = document.getElementById("status");
      var restart = document.getElementById("restart");
      var cells = [];
    
      for (var y = 0; y < SIZE; y++) {
        for (var x = 0; x < SIZE; x++) {
          var cell = document.createElement("div");
          cell.className = "cell";
          board.appendChild(cell);
          cells.push(cell);
        }
      }
    
      function render() {
        var st = game.state();
        var foodKey = st.food[0] + "," + st.food[1];
    
        for (var index = 0; index < cells.length; index++) {
          var cx = index % SIZE;
          var cy = Math.floor(index / SIZE);
          var cls = "cell";
    
          for (var s = 0; s < st.snake.length; s++) {
            if (st.snake[s][0] === cx && st.snake[s][1] === cy) {
              cls += s === 0 ? " head" : " body";
              break;
            }
          }
    
          if (cx + "," + cy === foodKey && cls.indexOf("head") === -1 && cls.indexOf("body") === -1) {
            cls += " food";
          }
    
          cells[index].className = cls;
        }
    
        if (st.over) {
          status.textContent = "Score: " + st.score + " · Game over. Restart?";
        } else {
          status.textContent = "Score: " + st.score + " · Arrow keys to move";
        }
      }
    
      var keyMap = {
        ArrowUp: "up",
        ArrowDown: "down",
        ArrowLeft: "left",
        ArrowRight: "right"
      };
    
      document.addEventListener("keydown", function (event) {
        var dir = keyMap[event.key];
        if (!dir) return;
    
        event.preventDefault();
        game.step(dir);
        render();
      });
    
      restart.addEventListener("click", function () {
        game = createGame();
        render();
      });
    
      render();
    })();
      </script>
    </body>
    </html>
  • Box-pushing puzzlePassed

    44,914 tokens: 1,171 read, 43,743 written · 40 min 36 s · 18 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">
      <title>Box-pushing puzzle</title>
      <style>
        body {
          margin: 1rem;
          font-family: system-ui, sans-serif;
          background: #f7f7f7;
          color: #111;
        }
    
        h1 {
          margin: 0 0 0.75rem;
          font-size: 1.5rem;
        }
    
        #board {
          display: grid;
          grid-template-columns: repeat(8, 3rem);
          grid-template-rows: repeat(7, 3rem);
          border: 2px solid #444;
        }
    
        .cell {
          box-sizing: border-box;
          border: 1px solid #d8d8d8;
          background: #fff;
          color: #111;
          display: flex;
          align-items: center;
          justify-content: center;
          font-family: monospace;
          font-weight: 700;
          font-size: 1.5rem;
        }
    
        .wall {
          background: #23272a;
          color: #fff;
        }
    
        .empty-floor {
          background: #fff;
        }
    
        .empty-goal {
          box-shadow: inset 0 0 0 3px #555;
        }
    
        .box {
          background: #fff;
        }
    
        .box-on-goal {
          box-shadow: inset 0 0 0 3px #555, inset 0 0 0 6px #fff, inset 0 0 0 9px #555;
        }
    
        .player {
          background: #dce7ff;
        }
    
        .player-on-goal {
          background: #dce7ff;
          box-shadow: inset 0 0 0 3px #555, inset 0 0 0 6px #fff, inset 0 0 0 9px #555;
        }
    
        #controls {
          margin-top: 1rem;
        }
    
        .pad {
          display: grid;
          grid-template-columns: repeat(3, 4.5rem);
          grid-template-rows: repeat(2, 2.5rem);
          grid-template-areas:
            ". up ."
            "left down right";
          gap: 0.25rem;
        }
    
        .pad button {
          width: 100%;
          height: 100%;
        }
    
        button {
          border: 1px solid #777;
          background: #fff;
          border-radius: 4px;
          font: inherit;
          cursor: pointer;
        }
    
        .up { grid-area: up; }
        .left { grid-area: left; }
        .down { grid-area: down; }
        .right { grid-area: right; }
    
        #restart {
          margin-top: 0.5rem;
        }
    
        #status {
          margin-top: 0.75rem;
        }
      </style>
    </head>
    <body>
      <h1>Box-pushing puzzle</h1>
    
      <div id="board"></div>
    
      <div id="controls">
        <div class="pad">
          <button type="button" class="up" data-dir="up">Up</button>
          <button type="button" class="left" data-dir="left">Left</button>
          <button type="button" class="down" data-dir="down">Down</button>
          <button type="button" class="right" data-dir="right">Right</button>
        </div>
        <button type="button" id="restart">Restart</button>
      </div>
    
      <p>Steps: <span id="steps">0</span></p>
      <p>Pushes: <span id="pushes">0</span></p>
      <p id="status">Not finished yet</p>
    
      <script id="game">
    function createGame() {
      const level = [
        "########",
        "#+#   ##",
        "# *    #",
        "#      #",
        "# $    #",
        "#      #",
        "########"
      ];
    
      const W = 8;
      const H = 7;
      const size = W * H;
    
      const walls = new Array(size).fill(false);
      const goals = new Array(size).fill(false);
      const boxes = [];
    
      let player = null;
      let steps = 0;
      let pushes = 0;
      let solved = false;
    
      for (let y = 0; y < H; y++) {
        const row = level[y];
        for (let x = 0; x < W; x++) {
          const ch = row[x];
          const i = y * W + x;
    
          if (ch === "#") {
            walls[i] = true;
          } else if (ch === ".") {
            goals[i] = true;
          } else if (ch === "*") {
            goals[i] = true;
            boxes.push([x, y]);
          } else if (ch === "$") {
            boxes.push([x, y]);
          } else if (ch === "@") {
            player = [x, y];
          } else if (ch === "+") {
            goals[i] = true;
            player = [x, y];
          }
        }
      }
    
      function boxAt(x, y) {
        for (let i = 0; i < boxes.length; i++) {
          if (boxes[i][0] === x && boxes[i][1] === y) {
            return i;
          }
        }
        return -1;
      }
    
      function everyBoxOnGoal() {
        for (let i = 0; i < boxes.length; i++) {
          if (!goals[boxes[i][1] * W + boxes[i][0]]) {
            return false;
          }
        }
        return true;
      }
    
      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 (walls[ny * W + nx]) {
          return;
        }
    
        const movingBox = boxAt(nx, ny);
    
        if (movingBox !== -1) {
          const bx = nx + dx;
          const by = ny + dy;
    
          if (bx < 0 || bx >= W || by < 0 || by >= H) {
            return;
          }
    
          if (walls[by * W + bx]) {
            return;
          }
    
          if (boxAt(bx, by) !== -1) {
            return;
          }
    
          boxes[movingBox] = [bx, by];
          player = [nx, ny];
          steps += 1;
          pushes += 1;
          solved = everyBoxOnGoal();
          return;
        }
    
        player = [nx, ny];
        steps += 1;
        solved = everyBoxOnGoal();
      }
    
      function state() {
        const sortedBoxes = boxes.map(function (b) {
          return [b[0], b[1]];
        });
    
        sortedBoxes.sort(function (a, b) {
          return a[1] - b[1] || a[0] - b[0];
        });
    
        return {
          player: [player[0], player[1]],
          boxes: sortedBoxes,
          pushes: pushes,
          steps: steps,
          solved: solved
        };
      }
    
      return {
        walk: walk,
        state: state
      };
    }
      </script>
    
      <script>
    (function () {
      let game = createGame();
    
      const W = 8;
      const H = 7;
    
      const level = [
        "########",
        "#+#   ##",
        "# *    #",
        "#      #",
        "# $    #",
        "#      #",
        "########"
      ];
    
      const board = document.getElementById("board");
      const cells = [];
    
      for (let y = 0; y < H; y++) {
        for (let x = 0; x < W; x++) {
          const cell = document.createElement("div");
          cell.className = "cell empty-floor";
          cell.setAttribute("role", "img");
          cell.setAttribute("aria-label", "empty floor");
          board.appendChild(cell);
          cells.push(cell);
        }
      }
    
      function render() {
        const st = game.state();
    
        const boxAt = new Array(W * H).fill(false);
        for (let i = 0; i < st.boxes.length; i++) {
          boxAt[st.boxes[i][1] * W + st.boxes[i][0]] = true;
        }
    
        const playerIndex = st.player[1] * W + st.player[0];
    
        for (let y = 0; y < H; y++) {
          for (let x = 0; x < W; x++) {
            const i = y * W + x;
            const ch = level[y][x];
    
            const isWall = ch === "#";
            const isGoal = ch === "." || ch === "*" || ch === "+";
            const isBox = boxAt[i];
            const isPlayer = playerIndex === i;
    
            const cell = cells[i];
            let kind = "empty-floor";
            let label = "empty floor";
            let text = "";
    
            if (isWall) {
              kind = "wall";
              label = "wall";
              text = "#";
            } else if (isBox) {
              if (isGoal) {
                kind = "box-on-goal";
                label = "box on a goal";
                text = "B";
              } else {
                kind = "box";
                label = "box";
                text = "B";
              }
            } else if (isPlayer) {
              if (isGoal) {
                kind = "player-on-goal";
                label = "you on a goal";
                text = "@";
              } else {
                kind = "player";
                label = "you";
                text = "@";
              }
            } else if (isGoal) {
              kind = "empty-goal";
              label = "empty goal";
              text = ".";
            }
    
            cell.className = "cell " + kind;
            cell.textContent = text;
            cell.setAttribute("aria-label", label);
          }
        }
    
        document.getElementById("steps").textContent = String(st.steps);
        document.getElementById("pushes").textContent = String(st.pushes);
    
        const status = document.getElementById("status");
        status.textContent = st.solved
          ? "Solved in " + st.steps + " steps with " + st.pushes + " pushes"
          : "Not finished yet";
      }
    
      let timer = null;
    
      function scheduleRender() {
        if (timer !== null) {
          clearTimeout(timer);
        }
    
        timer = setTimeout(function () {
          timer = null;
          render();
        }, 100);
      }
    
      const keyDirs = {
        ArrowUp: "up",
        ArrowDown: "down",
        ArrowLeft: "left",
        ArrowRight: "right",
        Up: "up",
        Down: "down",
        Left: "left",
        Right: "right"
      };
    
      window.addEventListener("keydown", function (event) {
        if (event.repeat) {
          return;
        }
    
        const dir = keyDirs[event.key];
        if (!dir) {
          return;
        }
    
        event.preventDefault();
        game.walk(dir);
        scheduleRender();
      });
    
      const buttons = document.querySelectorAll("[data-dir]");
      for (let i = 0; i < buttons.length; i++) {
        const button = buttons[i];
        button.addEventListener("click", function () {
          game.walk(button.getAttribute("data-dir"));
          scheduleRender();
        });
      }
    
      document.getElementById("restart").addEventListener("click", function () {
        game = createGame();
        scheduleRender();
      });
    
      render();
    })();
      </script>
    </body>
    </html>
  • MinesweeperPassed

    42,036 tokens: 1,476 read, 40,560 written · 25 min 44 s · 26.4 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
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Minesweeper</title>
    <style>
    html { box-sizing: border-box; }
    *, *::before, *::after { box-sizing: inherit; }
    body {
      margin: 0;
      padding: 12px;
      background: #f8f4ed;
      color: #24221f;
      font-family: system-ui, sans-serif;
    }
    main { max-width: 640px; }
    h1 { margin: 0 0 8px; font-size: 1.35rem; }
    p { margin: 0 0 14px; line-height: 1.4; }
    .panel {
      background: #ffffff;
      border: 1px solid #e3ddd2;
      border-radius: 10px;
      padding: 12px;
      width: min(100%, 350px);
    }
    #status {
      margin: 0 0 10px;
      font-weight: 700;
    }
    #status .playing { color: #24221f; }
    #status .won { color: #087a3a; }
    #status .lost { color: #c42525; }
    #flag-mode {
      font-family: inherit;
      font-size: 14px;
      color: #d6336c;
      background: #ffffff;
      border: 1px solid #d6336c;
      border-radius: 8px;
      padding: 7px 10px;
      cursor: pointer;
      margin: 0 0 10px;
    }
    #flag-mode[aria-pressed="true"] {
      background: #d6336c;
      color: #ffffff;
    }
    #board {
      display: grid;
      grid-template-columns: repeat(9, minmax(0, 1fr));
      grid-template-rows: repeat(9, minmax(0, 1fr));
      width: 324px;
      max-width: 100%;
      aspect-ratio: 1 / 1;
    }
    .cell {
      width: 100%;
      height: 100%;
      border: 1px solid #d7d0c3;
      background: #e9e3d7;
      color: #24221f;
      font-family: inherit;
      font-weight: 700;
      font-size: 18px;
      padding: 0;
      cursor: pointer;
    }
    .cell.open { background: #ffffff; }
    .cell.number { color: #1f3d70; }
    .cell.flag { color: #d6336c; }
    .cell.mine { background: #ffffff; color: #7d1a1a; }
    </style>
    </head>
    <body>
    <main>
      <h1>Minesweeper</h1>
      <p>Click or tap to open a square. Right-click, or use Flag mode, to flag a square. Open all safe squares without opening a mine.</p>
    
      <section class="panel" aria-label="Game panel">
        <div id="status" role="status" aria-live="polite">Mines left 10 <span class="playing">Playing</span></div>
        <button id="flag-mode" type="button" aria-pressed="false">Flag mode: off</button>
        <div id="board"></div>
      </section>
    </main>
    
    <script id="game">
    function createGame() {
      const layout = [
        ".*....*..",
        ".........",
        "....*.*..",
        "..*......",
        "...*.....",
        ".....*..*",
        ".........",
        "...*.....",
        "...*....."
      ];
    
      const size = 9;
      const mine = [];
      const counts = [];
      const open = [];
      const flags = [];
      let mineCount = 0;
    
      for (let r = 0; r < size; r++) {
        mine[r] = [];
        counts[r] = [];
        open[r] = [];
        flags[r] = [];
        for (let c = 0; c < size; c++) {
          mine[r][c] = layout[r][c] === "*";
          counts[r][c] = 0;
          open[r][c] = false;
          flags[r][c] = false;
          if (mine[r][c]) mineCount++;
        }
      }
    
      for (let r = 0; r < size; r++) {
        for (let c = 0; c < size; c++) {
          if (!mine[r][c]) {
            let total = 0;
            for (let dr = -1; dr <= 1; dr++) {
              for (let dc = -1; dc <= 1; dc++) {
                if (dr === 0 && dc === 0) continue;
                const nr = r + dr;
                const nc = c + dc;
                if (nr >= 0 && nr < size && nc >= 0 && nc < size && mine[nr][nc]) {
                  total++;
                }
              }
            }
            counts[r][c] = total;
          }
        }
      }
    
      let status = "playing";
      let openedSafe = 0;
      const safeTotal = size * size - mineCount;
      const dirs = [
        [-1, -1], [-1, 0], [-1, 1],
        [0, -1],           [0, 1],
        [1, -1],  [1, 0],  [1, 1]
      ];
    
      function spread(r, c) {
        const stack = [[r, c]];
        while (stack.length > 0) {
          const at = stack.pop();
          const cr = at[0];
          const cc = at[1];
          for (let i = 0; i < 8; i++) {
            const nr = cr + dirs[i][0];
            const nc = cc + dirs[i][1];
            if (
              nr >= 0 && nr < size &&
              nc >= 0 && nc < size &&
              !mine[nr][nc] &&
              !open[nr][nc] &&
              !flags[nr][nc]
            ) {
              open[nr][nc] = true;
              openedSafe++;
              if (counts[nr][nc] === 0) {
                stack.push([nr, nc]);
              }
            }
          }
        }
      }
    
      function press(move) {
        if (status !== "playing" || !move || move.length < 3) return;
    
        const kind = move[0];
        const r = +move[1];
        const c = +move[2];
    
        if (!(r >= 0 && r < size && c >= 0 && c < size)) return;
    
        if (kind === "open") {
          if (flags[r][c] || open[r][c]) return;
          if (mine[r][c]) {
            status = "lost";
            return;
          }
    
          open[r][c] = true;
          openedSafe++;
    
          if (counts[r][c] === 0) spread(r, c);
    
          if (openedSafe === safeTotal) status = "won";
        } else if (kind === "flag") {
          if (open[r][c]) return;
          flags[r][c] = !flags[r][c];
        }
      }
    
      function state() {
        const cells = [];
        let flagged = 0;
    
        for (let r = 0; r < size; r++) {
          let row = "";
          for (let c = 0; c < size; c++) {
            if (mine[r][c]) {
              if (status === "won") {
                row += "F";
              } else if (status === "lost") {
                row += "*";
              } else {
                row += flags[r][c] ? "F" : "#";
              }
            } else {
              if (open[r][c]) {
                row += counts[r][c] === 0 ? "." : ("" + counts[r][c]);
              } else {
                row += flags[r][c] ? "F" : "#";
              }
            }
    
            if (status !== "won" && flags[r][c]) flagged++;
          }
          cells.push(row);
        }
    
        return {
          cells,
          status,
          mines_left: status === "won" ? 0 : 10 - flagged
        };
      }
    
      return { press, state };
    }
    </script>
    
    <script>
    const game = createGame();
    const board = document.getElementById("board");
    const statusEl = document.getElementById("status");
    const flagBtn = document.getElementById("flag-mode");
    const cellButtons = [];
    
    for (let r = 0; r < 9; r++) {
      for (let c = 0; c < 9; c++) {
        const button = document.createElement("button");
        button.type = "button";
        button.className = "cell";
        button.dataset.row = String(r);
        button.dataset.col = String(c);
        button.setAttribute("aria-label", "Cell row " + r + ", column " + c);
        board.appendChild(button);
        cellButtons.push(button);
      }
    }
    
    let flagMode = false;
    
    function render() {
      const s = game.state();
      const word = s.status === "won" ? "Won" : s.status === "lost" ? "Lost" : "Playing";
      statusEl.innerHTML =
        "Mines left " + s.mines_left +
        " <span class=\"" + s.status + "\">" + word + "</span>";
    
      for (let i = 0; i < cellButtons.length; i++) {
        const button = cellButtons[i];
        const r = +button.dataset.row;
        const c = +button.dataset.col;
        const ch = s.cells[r][c];
    
        let cls = "cell";
    
        if (ch === "#") {
          button.textContent = "";
        } else if (ch === ".") {
          button.textContent = "";
          cls += " open";
        } else if (ch === "F") {
          button.textContent = "F";
          cls += " flag";
        } else if (ch === "*") {
          button.textContent = "*";
          cls += " mine";
        } else {
          button.textContent = ch;
          cls += " open number";
        }
    
        button.className = cls;
      }
    }
    
    board.addEventListener("click", function (event) {
      const button = event.target.closest("button.cell");
      if (!button) return;
    
      const r = +button.dataset.row;
      const c = +button.dataset.col;
    
      if (flagMode) {
        game.press(["flag", r, c]);
      } else {
        game.press(["open", r, c]);
      }
    
      render();
    });
    
    board.addEventListener("contextmenu", function (event) {
      event.preventDefault();
    
      const button = event.target.closest("button.cell");
      if (!button) return;
    
      const r = +button.dataset.row;
      const c = +button.dataset.col;
    
      game.press(["flag", r, c]);
      render();
    });
    
    board.addEventListener("keydown", function (event) {
      const button = event.target.closest("button.cell");
      if (!button) return;
    
      if (event.key === "f" || event.key === "F") {
        event.preventDefault();
        const r = +button.dataset.row;
        const c = +button.dataset.col;
        game.press(["flag", r, c]);
        render();
      }
    });
    
    flagBtn.addEventListener("click", function () {
      flagMode = !flagMode;
      flagBtn.textContent = flagMode ? "Flag mode: on" : "Flag mode: off";
      flagBtn.setAttribute("aria-pressed", flagMode ? "true" : "false");
    });
    
    render();
    </script>
    </body>
    </html>
Building apps 3 of 4
  • Step sequencerFailed

    100,813 tokens: 1,365 read, 99,448 written · 1 h 15 min · 22 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   1000100010001100
    snare  0000100100001100
    hat    1011101010111010
    
    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">
    <title>Step sequencer</title>
    <style>
      :root {
        --pink: #b31f57;
        --ink: #111111;
        --paper: #f8f8f8;
        --surface: #ffffff;
        --line: #111111;
        --label: 4.5rem;
      }
    
      * {
        box-sizing: border-box;
      }
    
      html, body {
        overflow-x: hidden;
      }
    
      body {
        margin: 1rem;
        background: var(--paper);
        color: var(--ink);
        font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif;
        line-height: 1.3;
      }
    
      h1 {
        margin: 0 0 0.75rem;
        font-size: 1.5rem;
      }
    
      #status,
      #announce {
        height: 1.75rem;
        line-height: 1.75rem;
        margin: 0;
        white-space: nowrap;
        overflow: hidden;
      }
    
      #announce {
        display: block;
      }
    
      #controls {
        margin: 0.75rem 0;
      }
    
      button {
        font: inherit;
        border: 1px solid var(--line);
        background: var(--surface);
        color: var(--ink);
        padding: 0.35rem 0.65rem;
        border-radius: 0;
        cursor: pointer;
      }
    
      button:focus {
        outline: 2px solid var(--pink);
        outline-offset: 2px;
      }
    
      #play {
        background: var(--pink);
        color: #ffffff;
        border-color: var(--pink);
        min-width: 5rem;
      }
    
      #play:disabled {
        background: var(--pink);
        color: #ffffff;
        border-color: var(--pink);
        opacity: 0.45;
        cursor: default;
      }
    
      #stop:disabled {
        opacity: 0.45;
        cursor: default;
      }
    
      #sequencer {
        width: 100%;
        margin-top: 0.75rem;
      }
    
      .header,
      .track {
        display: grid;
        width: 100%;
        grid-template-columns: var(--label) repeat(16, minmax(0, 1fr));
        gap: 4px;
        align-items: center;
      }
    
      .header {
        margin-bottom: 4px;
      }
    
      .hnum {
        text-align: center;
        font-size: 0.8rem;
      }
    
      .hnum.playhead {
        color: var(--pink);
      }
    
      .track {
        margin-bottom: 4px;
      }
    
      .track-label {
        font-weight: 600;
        font-size: 0.9rem;
      }
    
      .step {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 34px;
        padding: 0;
      }
    
      .step.on {
        background: var(--ink);
      }
    
      .step.playhead {
        outline: 2px solid var(--pink);
        outline-offset: -1px;
      }
    
      .step .num {
        display: none;
        font-size: 0.75rem;
        color: var(--ink);
      }
    
      .step.on .num {
        color: var(--surface);
      }
    
      .step.playhead .num {
        color: var(--pink);
      }
    
      @media (max-width: 720px) {
        :root {
          --label: 3.25rem;
        }
    
        .header {
          display: none;
        }
    
        .track {
          grid-template-columns: var(--label) repeat(8, minmax(0, 1fr));
          grid-template-rows: auto auto;
        }
    
        .track-label {
          grid-row: span 2;
          align-self: start;
        }
    
        .step {
          height: 38px;
        }
    
        .step .num {
          display: block;
        }
      }
    
      @media (max-width: 380px) {
        :root {
          --label: 2.75rem;
        }
      }
    </style>
    </head>
    <body>
    <h1>Step sequencer</h1>
    
    <p id="status">Stopped</p>
    <span id="announce" aria-live="polite"></span>
    
    <p id="controls">
      <button id="play" type="button">Play</button>
      <button id="stop" type="button" disabled>Stop</button>
    </p>
    
    <div id="sequencer"></div>
    
    <script id="game">
    function createGame() {
      const patternStrings = [
        "1000100010001100",
        "0000100100001100",
        "1011101010111010"
      ];
    
      const pattern = patternStrings.map(function (row) {
        return row.split("");
      });
    
      let playing = false;
      let playhead = 0;
      let hits = [];
    
      function hitsAt(step) {
        const list = [];
        if (pattern[0][step] === "1") {
          list.push(0);
        }
        if (pattern[1][step] === "1") {
          list.push(1);
        }
        if (pattern[2][step] === "1") {
          list.push(2);
        }
        return list;
      }
    
      function press(command) {
        if (command === "play") {
          if (!playing) {
            playing = true;
            hits = hitsAt(playhead);
          }
          return;
        }
    
        if (command === "stop") {
          playing = false;
          playhead = 0;
          hits = [];
          return;
        }
    
        if (command === "tick") {
          if (!playing) {
            return;
          }
          playhead = playhead + 1;
          if (playhead > 15) {
            playhead = 0;
          }
          hits = hitsAt(playhead);
          return;
        }
    
        if (Array.isArray(command) && command.length === 2) {
          const track = command[0];
          const step = command[1];
    
          if (
            Number.isInteger(track) &&
            Number.isInteger(step) &&
            track >= 0 &&
            track <= 2 &&
            step >= 0 &&
            step <= 15
          ) {
            if (pattern[track][step] === "1") {
              pattern[track][step] = "0";
            } else {
              pattern[track][step] = "1";
            }
          }
        }
      }
    
      function state() {
        return {
          playing: playing,
          playhead: playhead,
          hits: hits.slice(),
          pattern: [
            pattern[0].join(""),
            pattern[1].join(""),
            pattern[2].join("")
          ]
        };
      }
    
      return {
        press: press,
        state: state
      };
    }
    </script>
    
    <script>
    (function () {
      const game = createGame();
    
      const status = document.getElementById("status");
      const announce = document.getElementById("announce");
      const playButton = document.getElementById("play");
      const stopButton = document.getElementById("stop");
      const grid = document.getElementById("sequencer");
    
      const trackNames = ["Kick", "Snare", "Hat"];
    
      const header = document.createElement("div");
      header.className = "header";
      header.setAttribute("aria-hidden", "true");
    
      const headerLabel = document.createElement("span");
      headerLabel.className = "header-label";
      header.appendChild(headerLabel);
    
      for (let step = 0; step < 16; step++) {
        const numberHeader = document.createElement("span");
        numberHeader.className = "hnum";
        numberHeader.dataset.step = String(step);
        numberHeader.textContent = String(step + 1);
        header.appendChild(numberHeader);
      }
    
      grid.appendChild(header);
    
      for (let track = 0; track < 3; track++) {
        const row = document.createElement("div");
        row.className = "track";
    
        const label = document.createElement("span");
        label.className = "track-label";
        label.textContent = trackNames[track];
        row.appendChild(label);
    
        for (let step = 0; step < 16; step++) {
          const button = document.createElement("button");
          button.type = "button";
          button.className = "step";
          button.dataset.track = String(track);
          button.dataset.step = String(step);
          button.setAttribute("aria-label", trackNames[track] + " step " + String(step + 1));
          button.setAttribute("aria-pressed", "false");
    
          const number = document.createElement("span");
          number.className = "num";
          number.textContent = String(step + 1);
          button.appendChild(number);
    
          row.appendChild(button);
        }
    
        grid.appendChild(row);
      }
    
      const stepButtons = Array.from(grid.querySelectorAll(".step"));
      const numbers = Array.from(grid.querySelectorAll(".hnum"));
    
      let previousPlaying = false;
      let timer = null;
    
      let audioContext = null;
      let masterGain = null;
      let noiseBuffer = null;
      const activeSources = new Set();
      const DEFAULT_MASTER_GAIN = 0.25;
    
      function updateAnnounce(playing) {
        if (playing && !previousPlaying) {
          announce.textContent = "Playing";
        } else if (!playing && previousPlaying) {
          announce.textContent = "Stopped";
        }
        previousPlaying = playing;
      }
    
      function draw() {
        const state = game.state();
    
        stepButtons.forEach(function (button) {
          const track = Number(button.dataset.track);
          const step = Number(button.dataset.step);
          const on = state.pattern[track].charAt(step) === "1";
    
          button.classList.toggle("on", on);
          button.setAttribute("aria-pressed", on ? "true" : "false");
          button.classList.toggle("playhead", state.playing && step === state.playhead);
        });
    
        numbers.forEach(function (number) {
          const step = Number(number.dataset.step);
          number.classList.toggle("playhead", state.playing && step === state.playhead);
        });
    
        status.textContent = state.playing
          ? "Playing, step " + String(state.playhead + 1) + " of 16"
          : "Stopped";
    
        playButton.disabled = state.playing;
        stopButton.disabled = !state.playing;
    
        updateAnnounce(state.playing);
      }
    
      function startTimer() {
        if (timer !== null) {
          return;
        }
        timer = window.setInterval(onTick, 125);
      }
    
      function clearTimer() {
        if (timer !== null) {
          window.clearInterval(timer);
          timer = null;
        }
      }
    
      function onTick() {
        game.press("tick");
        const state = game.state();
        draw();
        playHits(state.hits);
      }
    
      function createNoiseBuffer(context) {
        const length = Math.floor(context.sampleRate * 0.5);
        const buffer = context.createBuffer(1, length, context.sampleRate);
        const data = buffer.getChannelData(0);
    
        for (let i = 0; i < length; i++) {
          data[i] = Math.random() * 2 - 1;
        }
    
        return buffer;
      }
    
      function ensureAudio() {
        if (!audioContext) {
          const AudioContextConstructor = window.AudioContext || window.webkitAudioContext;
          if (!AudioContextConstructor) {
            return null;
          }
    
          try {
            audioContext = new AudioContextConstructor();
            masterGain = audioContext.createGain();
            masterGain.gain.value = DEFAULT_MASTER_GAIN;
            masterGain.connect(audioContext.destination);
            noiseBuffer = createNoiseBuffer(audioContext);
          } catch (error) {
            audioContext = null;
            masterGain = null;
            noiseBuffer = null;
            return null;
          }
        }
    
        if (audioContext.state === "suspended" && typeof audioContext.resume === "function") {
          try {
            audioContext.resume().catch(function () {});
          } catch (error) {}
        }
    
        return audioContext;
      }
    
      function restoreGain() {
        try {
          if (audioContext && masterGain) {
            const now = audioContext.currentTime;
            masterGain.gain.cancelScheduledValues(now);
            masterGain.gain.setValueAtTime(DEFAULT_MASTER_GAIN, now);
          }
        } catch (error) {}
      }
    
      function stopAllSounds() {
        if (audioContext && masterGain) {
          let now = 0;
    
          try {
            now = audioContext.currentTime;
          } catch (error) {}
    
          try {
            masterGain.gain.cancelScheduledValues(now);
            masterGain.gain.setValueAtTime(0, now);
          } catch (error) {}
    
          activeSources.forEach(function (source) {
            try {
              source.onended = null;
              source.disconnect();
              source.stop(now);
            } catch (error) {}
          });
    
          activeSources.clear();
        }
      }
    
      function registerSource(source) {
        activeSources.add(source);
        source.onended = function () {
          activeSources.delete(source);
        };
      }
    
      function playKick(time) {
        const oscillator = audioContext.createOscillator();
        const gain = audioContext.createGain();
    
        oscillator.type = "sine";
        oscillator.frequency.setValueAtTime(170, time);
        oscillator.frequency.exponentialRampToValueAtTime(45, time + 0.18);
    
        gain.gain.setValueAtTime(0.0001, time);
        gain.gain.exponentialRampToValueAtTime(0.7, time + 0.01);
        gain.gain.exponentialRampToValueAtTime(0.0001, time + 0.3);
    
        oscillator.connect(gain);
        gain.connect(masterGain);
    
        registerSource(oscillator);
    
        oscillator.start(time);
        oscillator.stop(time + 0.35);
      }
    
      function playSnare(time) {
        const noise = audioContext.createBufferSource();
        const noiseGain = audioContext.createGain();
        const filter = audioContext.createBiquadFilter();
    
        noise.buffer = noiseBuffer;
        filter.type = "bandpass";
        filter.frequency.value = 1800;
        filter.Q.value = 0.8;
    
        noiseGain.gain.setValueAtTime(0.0001, time);
        noiseGain.gain.exponentialRampToValueAtTime(0.35, time + 0.005);
        noiseGain.gain.exponentialRampToValueAtTime(0.0001, time + 0.12);
    
        noise.connect(filter);
        filter.connect(noiseGain);
        noiseGain.connect(masterGain);
    
        registerSource(noise);
    
        noise.start(time);
        noise.stop(time + 0.15);
    
        const body = audioContext.createOscillator();
        const bodyGain = audioContext.createGain();
    
        body.type = "sine";
        body.frequency.setValueAtTime(180, time);
        body.frequency.exponentialRampToValueAtTime(110, time + 0.08);
    
        bodyGain.gain.setValueAtTime(0.0001, time);
        bodyGain.gain.exponentialRampToValueAtTime(0.25, time + 0.006);
        bodyGain.gain.exponentialRampToValueAtTime(0.0001, time + 0.15);
    
        body.connect(bodyGain);
        bodyGain.connect(masterGain);
    
        registerSource(body);
    
        body.start(time);
        body.stop(time + 0.2);
      }
    
      function playHat(time) {
        const noise = audioContext.createBufferSource();
        const gain = audioContext.createGain();
        const filter = audioContext.createBiquadFilter();
    
        noise.buffer = noiseBuffer;
        filter.type = "highpass";
        filter.frequency.value = 7000;
        filter.Q.value = 0.7;
    
        gain.gain.setValueAtTime(0.0001, time);
        gain.gain.exponentialRampToValueAtTime(0.18, time + 0.003);
        gain.gain.exponentialRampToValueAtTime(0.0001, time + 0.05);
    
        noise.connect(filter);
        filter.connect(gain);
        gain.connect(masterGain);
    
        registerSource(noise);
    
        noise.start(time);
        noise.stop(time + 0.06);
      }
    
      function playHits(hits) {
        try {
          if (!audioContext || !noiseBuffer || !masterGain) {
            return;
          }
    
          if (audioContext.state === "suspended" && typeof audioContext.resume === "function") {
            try {
              audioContext.resume().catch(function () {});
            } catch (error) {}
          }
    
          const time = audioContext.currentTime + 0.001;
    
          for (let i = 0; i < hits.length; i++) {
            const track = hits[i];
    
            if (track === 0) {
              playKick(time);
            } else if (track === 1) {
              playSnare(time);
            } else if (track === 2) {
              playHat(time);
            }
          }
        } catch (error) {}
      }
    
      function unlockAudioOnce() {
        ensureAudio();
        document.removeEventListener("click", unlockAudioOnce);
      }
    
      document.addEventListener("click", unlockAudioOnce);
    
      playButton.addEventListener("click", function () {
        ensureAudio();
    
        const wasPlaying = game.state().playing;
        game.press("play");
        const state = game.state();
    
        draw();
    
        if (!wasPlaying && state.playing) {
          restoreGain();
          startTimer();
          playHits(state.hits);
        }
      });
    
      stopButton.addEventListener("click", function () {
        game.press("stop");
        clearTimer();
        stopAllSounds();
        draw();
      });
    
      stepButtons.forEach(function (button) {
        button.addEventListener("click", function () {
          const track = Number(button.dataset.track);
          const step = Number(button.dataset.step);
    
          game.press([track, step]);
          draw();
        });
      });
    
      document.addEventListener("visibilitychange", function () {
        if (document.hidden) {
          game.press("stop");
          clearTimer();
          stopAllSounds();
          draw();
        }
      });
    
      draw();
    })();
    </script>
    </body>
    </html>
  • Grow a branching plantPassed

    49,417 tokens: 1,282 read, 48,135 written · 31 min 32 s · 25.5 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">
    <title>Grow a branching plant</title>
    <style>
    html {
      box-sizing: border-box;
    }
    
    *,
    *::before,
    *::after {
      box-sizing: inherit;
    }
    
    body {
      margin: 0;
      padding: 16px;
      background: #f7f4ed;
      color: #22302b;
      font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
      line-height: 1.45;
      overflow-x: hidden;
    }
    
    main {
      max-width: 640px;
      margin: 0 auto;
    }
    
    h1 {
      margin: 0 0 14px;
      font-size: 1.35rem;
    }
    
    .card {
      background: #ffffff;
      border: 1px solid #d8d1c4;
      border-radius: 10px;
      padding: 12px;
    }
    
    canvas {
      display: block;
      width: 320px;
      height: auto;
      max-width: 100%;
      aspect-ratio: 320 / 320;
      margin: 0 auto;
      background: #ffffff;
    }
    
    .actions {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;
      margin-top: 12px;
    }
    
    button {
      font: inherit;
      min-height: 40px;
      padding: 10px 16px;
      border-radius: 8px;
      cursor: pointer;
    }
    
    #grow {
      border: 1px solid #2d6f59;
      background: #2d6f59;
      color: #ffffff;
    }
    
    #grow:hover:not(:disabled) {
      background: #275f4c;
    }
    
    #reset {
      border: 1px solid #c8c1b6;
      background: #ffffff;
      color: #22302b;
    }
    
    #reset:hover {
      background: #f1ede5;
    }
    
    button:disabled {
      opacity: 0.45;
      cursor: not-allowed;
    }
    
    #status {
      margin: 12px 0 0;
      font-size: 0.95rem;
      color: #586861;
    }
    </style>
    </head>
    <body>
    <main>
      <h1>Grow a branching plant</h1>
    
      <div class="card">
        <canvas id="plant" width="320" height="320"></canvas>
      </div>
    
      <div class="actions">
        <button id="grow" type="button">Grow</button>
        <button id="reset" type="button">Reset</button>
      </div>
    
      <p id="status" role="status"></p>
    </main>
    
    <script id="game">
    function createGame() {
      const rule = "F[[++F[+F]]-F[--F]]F";
      const stepX = [1, 1, 0, -1, -1, -1, 0, 1];
      const stepY = [0, 1, 1, 1, 0, -1, -1, -1];
      let generation = 0;
      let text = "F";
      let segments = [];
    
      function simulate(input) {
        let x = 0;
        let y = 0;
        let heading = 6;
        const stack = [];
        const result = [];
    
        for (let i = 0; i < input.length; i += 1) {
          const symbol = input[i];
    
          if (symbol === "F") {
            const dx = stepX[heading];
            const dy = stepY[heading];
            result.push([x, y, x + dx, y + dy]);
            x += dx;
            y += dy;
          } else if (symbol === "+") {
            heading = (heading + 1) % 8;
          } else if (symbol === "-") {
            heading = (heading + 7) % 8;
          } else if (symbol === "[") {
            stack.push([x, y, heading]);
          } else if (symbol === "]") {
            if (stack.length > 0) {
              const saved = stack.pop();
              x = saved[0];
              y = saved[1];
              heading = saved[2];
            }
          }
        }
    
        return result;
      }
    
      segments = simulate(text);
    
      return {
        grow: function grow() {
          if (generation >= 4) {
            return;
          }
    
          const parts = [];
    
          for (let i = 0; i < text.length; i += 1) {
            if (text[i] === "F") {
              parts.push(rule);
            } else {
              parts.push(text[i]);
            }
          }
    
          text = parts.join("");
          generation += 1;
          segments = simulate(text);
        },
    
        state: function state() {
          return {
            generation: generation,
            text: text,
            segments: segments
          };
        }
      };
    }
    </script>
    
    <script>
    let game = createGame();
    
    const plant = document.getElementById("plant");
    const statusLine = document.getElementById("status");
    const growButton = document.getElementById("grow");
    const resetButton = document.getElementById("reset");
    const ctx = plant.getContext("2d");
    
    function drawPlant(state) {
      ctx.clearRect(0, 0, plant.width, plant.height);
    
      const segments = state.segments;
    
      if (segments.length === 0) {
        return;
      }
    
      let minX = segments[0][0];
      let minY = segments[0][1];
      let maxX = minX;
      let maxY = minY;
    
      for (let i = 1; i < segments.length; i += 1) {
        const segment = segments[i];
    
        if (segment[0] < minX) minX = segment[0];
        if (segment[1] < minY) minY = segment[1];
        if (segment[2] < minX) minX = segment[2];
        if (segment[3] < minY) minY = segment[3];
    
        if (segment[0] > maxX) maxX = segment[0];
        if (segment[1] > maxY) maxY = segment[1];
        if (segment[2] > maxX) maxX = segment[2];
        if (segment[3] > maxY) maxY = segment[3];
      }
    
      const padding = 16;
      const availableWidth = plant.width - padding * 2;
      const availableHeight = plant.height - padding * 2;
      const boxWidth = maxX - minX;
      const boxHeight = maxY - minY;
    
      let scale = 1;
    
      if (boxWidth > 0 && boxHeight > 0) {
        scale = Math.min(availableWidth / boxWidth, availableHeight / boxHeight);
      } else if (boxWidth > 0) {
        scale = availableWidth / boxWidth;
      } else if (boxHeight > 0) {
        scale = availableHeight / boxHeight;
      }
    
      const offsetX = (plant.width - boxWidth * scale) / 2 - minX * scale;
      const offsetY = (plant.height - boxHeight * scale) / 2 - minY * scale;
    
      ctx.strokeStyle = "#23302b";
      ctx.lineWidth = 2;
      ctx.lineCap = "butt";
      ctx.beginPath();
    
      for (let i = 0; i < segments.length; i += 1) {
        const segment = segments[i];
        ctx.moveTo(segment[0] * scale + offsetX, segment[1] * scale + offsetY);
        ctx.lineTo(segment[2] * scale + offsetX, segment[3] * scale + offsetY);
      }
    
      ctx.stroke();
    }
    
    function showState(state) {
      const n = state.segments.length;
      const word = n === 1 ? "segment" : "segments";
      statusLine.textContent =
        "Generation " + state.generation + " of 4, " + n + " " + word;
    }
    
    function render() {
      const state = game.state();
      drawPlant(state);
      showState(state);
      growButton.disabled = state.generation >= 4;
    }
    
    growButton.addEventListener('click', function () {
      game.grow();
      render();
    });
    
    resetButton.addEventListener('click', function () {
      game = createGame();
      render();
    });
    
    render();
    </script>
    </body>
    </html>
  • Falling sandPassed

    54,752 tokens: 1,201 read, 53,551 written · 35 min 0 s · 25.6 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: row 19, columns 13 to 17; row 21, columns 5 to 9; row 20, columns 21 to 27.
    3. Sand: column 12, row 2; row 3, columns 9 to 15; row 4, columns 7 to 17; row 5, columns 7 to 17; row 6, columns 6 to 18; row 7, columns 7 to 17; row 8, columns 7 to 17; row 9, columns 9 to 15; column 12, row 10.
    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">
    <title>Falling Sand</title>
    <style>
    :root { color-scheme: dark; }
    
    body {
      margin: 0;
      font: 16px/1.4 system-ui, sans-serif;
      background: #070b10;
      color: #e6edf3;
    }
    
    main {
      max-width: 720px;
      margin: 0 auto;
      padding: 24px;
    }
    
    h1 {
      margin: 0 0 16px;
      font-size: 1.5rem;
    }
    
    #board {
      display: block;
      width: min(100%, 640px);
      height: auto;
      background: #0f1115;
      border-radius: 8px;
      box-shadow: 0 0 0 1px #27313d;
      touch-action: none;
      image-rendering: pixelated;
      cursor: crosshair;
    }
    
    #board:focus {
      outline: 2px solid #8ab4f8;
      outline-offset: 3px;
    }
    
    #status {
      margin: 12px 0;
      font-variant-numeric: tabular-nums;
    }
    
    .controls {
      display: flex;
      gap: 8px;
      margin: 12px 0;
    }
    
    button {
      padding: 8px 14px;
      border: 1px solid #374151;
      border-radius: 6px;
      background: #1f2937;
      color: #e6edf3;
      font: inherit;
      cursor: pointer;
    }
    
    button:hover {
      background: #283242;
    }
    
    button:focus {
      outline: 2px solid #8ab4f8;
      outline-offset: 2px;
    }
    
    .visually-hidden {
      position: absolute;
      width: 1px;
      height: 1px;
      margin: -1px;
      padding: 0;
      overflow: hidden;
      clip: rect(0 0 0 0);
      white-space: nowrap;
      border: 0;
    }
    </style>
    </head>
    <body>
    <main>
      <h1>Falling Sand</h1>
    
      <canvas id="board" width="640" height="480" tabindex="0" aria-label="Falling sand board"></canvas>
    
      <p id="status">Frame 0, 73 grains of sand</p>
    
      <div class="controls">
        <button id="play" type="button">Play</button>
        <button id="step" type="button">Step</button>
        <button id="reset" type="button">Reset</button>
      </div>
    
      <p id="say" class="visually-hidden" aria-live="polite"></p>
    </main>
    
    <script id="game">
    function createGame() {
      const COLS = 40;
      const ROWS = 30;
    
      let frame = 0;
      let cells = [];
    
      for (let y = 0; y < ROWS; y++) {
        const row = [];
        for (let x = 0; x < COLS; x++) {
          row.push(y === 29 ? 2 : 0);
        }
        cells.push(row);
      }
    
      function setRange(row, x1, x2, value) {
        for (let x = x1; x <= x2; x++) {
          row[x] = value;
        }
      }
    
      setRange(cells[19], 13, 17, 2);
      setRange(cells[21], 5, 9, 2);
      setRange(cells[20], 21, 27, 2);
    
      cells[2][12] = 1;
      setRange(cells[3], 9, 15, 1);
      setRange(cells[4], 7, 17, 1);
      setRange(cells[5], 7, 17, 1);
      setRange(cells[6], 6, 18, 1);
      setRange(cells[7], 7, 17, 1);
      setRange(cells[8], 7, 17, 1);
      setRange(cells[9], 9, 15, 1);
      cells[10][12] = 1;
    
      function inside(x, y) {
        return x >= 0 && x < COLS && y >= 0 && y < ROWS;
      }
    
      function isEmpty(x, y) {
        return inside(x, y) && cells[y][x] === 0;
      }
    
      function pour(x, y) {
        if (inside(x, y) && cells[y][x] === 0) {
          cells[y][x] = 1;
        }
      }
    
      function moveGrain(x, y) {
        if (cells[y][x] !== 1) {
          return;
        }
    
        const belowY = y + 1;
    
        if (isEmpty(x, belowY)) {
          cells[y][x] = 0;
          cells[belowY][x] = 1;
        } else if (isEmpty(x - 1, belowY)) {
          cells[y][x] = 0;
          cells[belowY][x - 1] = 1;
        } else if (isEmpty(x + 1, belowY)) {
          cells[y][x] = 0;
          cells[belowY][x + 1] = 1;
        }
      }
    
      function step() {
        const leftToRight = frame % 2 === 0;
    
        for (let y = 28; y >= 0; y--) {
          if (leftToRight) {
            for (let x = 0; x < COLS; x++) {
              moveGrain(x, y);
            }
          } else {
            for (let x = COLS - 1; x >= 0; x--) {
              moveGrain(x, y);
            }
          }
        }
    
        frame += 1;
      }
    
      function state() {
        return {
          frame: frame,
          cells: cells.map(function (row) {
            return row.slice();
          })
        };
      }
    
      function play(move) {
        if (move === "step") {
          step();
        } else if (Array.isArray(move) && move.length >= 2) {
          pour(move[0], move[1]);
        }
      }
    
      return {
        play: play,
        state: state
      };
    }
    </script>
    
    <script>
    (function () {
      const COLS = 40;
      const ROWS = 30;
    
      const canvas = document.getElementById("board");
      const ctx = canvas.getContext("2d");
      const CELL_X = canvas.width / COLS;
      const CELL_Y = canvas.height / ROWS;
    
      const playButton = document.getElementById("play");
      const stepButton = document.getElementById("step");
      const resetButton = document.getElementById("reset");
      const status = document.getElementById("status");
      const say = document.getElementById("say");
    
      const BG_COLOR = "#0f1115";
      const WALL_COLOR = "#5b6472";
      const SAND_COLOR = "#f2c14e";
    
      let game = createGame();
      let wallLayer = null;
    
      let intervalId = null;
      let running = false;
      let visible = true;
      let wasPlayingBeforeOffscreen = false;
    
      let focused = false;
      let cursor = { x: 12, y: 2 };
    
      const reducedMotion = typeof matchMedia === "function"
        ? matchMedia("(prefers-reduced-motion: reduce)")
        : { matches: false };
    
      function announce(text) {
        say.textContent = text;
      }
    
      function buildWallLayer(state) {
        const layer = document.createElement("canvas");
        layer.width = canvas.width;
        layer.height = canvas.height;
    
        const layerCtx = layer.getContext("2d");
        if (!layerCtx) {
          wallLayer = null;
          return;
        }
    
        layerCtx.fillStyle = WALL_COLOR;
        for (let y = 0; y < ROWS; y++) {
          const row = state.cells[y];
          for (let x = 0; x < COLS; x++) {
            if (row[x] === 2) {
              layerCtx.fillRect(x * CELL_X, y * CELL_Y, CELL_X, CELL_Y);
            }
          }
        }
    
        wallLayer = layer;
      }
    
      function updateStatus(frame, grains) {
        status.textContent =
          "Frame " + frame + ", " +
          grains +
          (grains === 1 ? " grain of sand" : " grains of sand");
      }
    
      function draw(state) {
        ctx.fillStyle = BG_COLOR;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    
        if (wallLayer) {
          ctx.drawImage(wallLayer, 0, 0);
        }
    
        ctx.fillStyle = SAND_COLOR;
    
        let grains = 0;
        for (let y = 0; y < ROWS; y++) {
          const row = state.cells[y];
          for (let x = 0; x < COLS; x++) {
            if (row[x] === 1) {
              ctx.fillRect(x * CELL_X, y * CELL_Y, CELL_X, CELL_Y);
              grains++;
            }
          }
        }
    
        if (focused) {
          ctx.strokeStyle = "rgba(255, 255, 255, 0.85)";
          ctx.lineWidth = 2;
    
          const w = Math.max(1, CELL_X - 4);
          const h = Math.max(1, CELL_Y - 4);
    
          ctx.strokeRect(
            cursor.x * CELL_X + 2,
            cursor.y * CELL_Y + 2,
            w,
            h
          );
        }
    
        return grains;
      }
    
      function sync() {
        const state = game.state();
        const grains = draw(state);
        updateStatus(state.frame, grains);
      }
    
      buildWallLayer(game.state());
      sync();
    
      function pourAt(x, y) {
        game.play([x, y]);
        sync();
      }
    
      function pourLine(x0, y0, x1, y1) {
        let x = x0;
        let y = y0;
    
        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) {
          pourAt(x, y);
    
          if (x === x1 && y === y1) {
            break;
          }
    
          const e2 = 2 * err;
    
          if (e2 > -dy) {
            err -= dy;
            x += sx;
          }
    
          if (e2 < dx) {
            err += dx;
            y += sy;
          }
        }
      }
    
      function cellFromPointer(event, clamp) {
        const rect = canvas.getBoundingClientRect();
        if (rect.width === 0 || rect.height === 0) {
          return null;
        }
    
        let x = Math.floor((event.clientX - rect.left) * COLS / rect.width);
        let y = Math.floor((event.clientY - rect.top) * ROWS / rect.height);
    
        if (clamp) {
          if (x < 0) x = 0;
          if (x >= COLS) x = COLS - 1;
          if (y < 0) y = 0;
          if (y >= ROWS) y = ROWS - 1;
          return { x: x, y: y };
        }
    
        if (x < 0 || x >= COLS || y < 0 || y >= ROWS) {
          return null;
        }
    
        return { x: x, y: y };
      }
    
      let dragging = false;
      let lastCell = null;
    
      function startDrag(event) {
        event.preventDefault();
        canvas.focus();
    
        try {
          canvas.setPointerCapture(event.pointerId);
        } catch (err) {
          // Ignore unsupported or synthetic events without a valid pointer id.
        }
    
        dragging = true;
        const cell = cellFromPointer(event, true);
        lastCell = cell;
    
        if (cell) {
          pourAt(cell.x, cell.y);
        }
      }
    
      function endDrag() {
        dragging = false;
        lastCell = null;
      }
    
      canvas.addEventListener("pointerdown", startDrag);
    
      canvas.addEventListener("pointermove", function (event) {
        if (!dragging) {
          return;
        }
    
        const cell = cellFromPointer(event, false);
        if (!cell) {
          return;
        }
    
        if (!lastCell) {
          lastCell = cell;
        } else if (lastCell.x !== cell.x || lastCell.y !== cell.y) {
          pourLine(lastCell.x, lastCell.y, cell.x, cell.y);
          lastCell = cell;
        } else {
          lastCell = cell;
        }
      });
    
      canvas.addEventListener("pointerup", endDrag);
      canvas.addEventListener("pointercancel", endDrag);
      canvas.addEventListener("lostpointercapture", endDrag);
    
      canvas.addEventListener("focus", function () {
        focused = true;
        sync();
      });
    
      canvas.addEventListener("blur", function () {
        focused = false;
        sync();
      });
    
      canvas.addEventListener("keydown", function (event) {
        if (event.ctrlKey || event.altKey || event.metaKey) {
          return;
        }
    
        let moved = false;
    
        if (event.key === "ArrowUp") {
          cursor.y = Math.max(0, cursor.y - 1);
          moved = true;
        } else if (event.key === "ArrowDown") {
          cursor.y = Math.min(ROWS - 1, cursor.y + 1);
          moved = true;
        } else if (event.key === "ArrowLeft") {
          cursor.x = Math.max(0, cursor.x - 1);
          moved = true;
        } else if (event.key === "ArrowRight") {
          cursor.x = Math.min(COLS - 1, cursor.x + 1);
          moved = true;
        } else if (event.key === " " || event.key === "Spacebar" || event.key === "Enter") {
          event.preventDefault();
          pourAt(cursor.x, cursor.y);
          return;
        }
    
        if (moved) {
          event.preventDefault();
          sync();
        }
      });
    
      function tick() {
        if (!visible) {
          return;
        }
    
        game.play("step");
        sync();
      }
    
      function startPlay() {
        if (!visible) {
          return;
        }
    
        if (running) {
          return;
        }
    
        if (reducedMotion.matches) {
          game.play("step");
          sync();
          playButton.textContent = "Play";
          announce("Play");
          return;
        }
    
        running = true;
        playButton.textContent = "Pause";
        announce("Play");
        intervalId = setInterval(tick, 50);
      }
    
      function stopPlay() {
        if (intervalId !== null) {
          clearInterval(intervalId);
          intervalId = null;
        }
    
        running = false;
        playButton.textContent = "Play";
      }
    
      playButton.addEventListener("click", function () {
        if (!visible) {
          return;
        }
    
        if (running) {
          stopPlay();
          announce("Pause");
        } else {
          startPlay();
        }
      });
    
      stepButton.addEventListener("click", function () {
        game.play("step");
        sync();
        announce("Step");
      });
    
      resetButton.addEventListener("click", function () {
        stopPlay();
        wasPlayingBeforeOffscreen = false;
    
        game = createGame();
        buildWallLayer(game.state());
        sync();
    
        announce("Reset");
      });
    
      function setVisibility(isVisible) {
        if (visible === isVisible) {
          return;
        }
    
        visible = isVisible;
    
        if (!visible) {
          wasPlayingBeforeOffscreen = running;
    
          if (running) {
            stopPlay();
          }
        } else {
          if (wasPlayingBeforeOffscreen && !reducedMotion.matches) {
            wasPlayingBeforeOffscreen = false;
            startPlay();
          } else {
            wasPlayingBeforeOffscreen = false;
          }
        }
      }
    
      if (typeof IntersectionObserver !== "undefined") {
        const observer = new IntersectionObserver(function (entries) {
          for (let i = 0; i < entries.length; i++) {
            setVisibility(entries[i].isIntersecting);
          }
        }, { threshold: 0 });
    
        observer.observe(canvas);
      }
    
      if (typeof reducedMotion.addEventListener === "function") {
        reducedMotion.addEventListener("change", function () {
          if (reducedMotion.matches && running) {
            stopPlay();
          }
        });
      } else if (typeof reducedMotion.addListener === "function") {
        reducedMotion.addListener(function () {
          if (reducedMotion.matches && running) {
            stopPlay();
          }
        });
      }
    })();
    </script>
    </body>
    </html>
  • Focus timerPassed

    83,795 tokens: 1,159 read, 82,636 written · 57 min 48 s · 23.9 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 180 seconds (3 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">
    <title>Focus timer</title>
    <style>
    :root {
      --bg: #f8f4ee;
      --card: #ffffff;
      --ink: #22211f;
      --muted: #6f6a63;
      --line: #ddd7cf;
      --accent: #9a4b1e;
    }
    
    *,
    *::before,
    *::after {
      box-sizing: border-box;
    }
    
    html,
    body {
      margin: 0;
      padding: 0;
    }
    
    body {
      font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      color: var(--ink);
      background: var(--bg);
      padding: 1.25rem 1rem;
    }
    
    main {
      max-width: 520px;
      margin: 0 auto;
    }
    
    .card {
      background: var(--card);
      border: 1px solid var(--line);
      border-radius: 16px;
      padding: 1.5rem;
    }
    
    h1 {
      margin: 0 0 1.25rem;
      font-size: 1.5rem;
      font-weight: 650;
      line-height: 1.2;
    }
    
    .ring-box {
      position: relative;
      width: 260px;
      height: 260px;
      margin: 0 auto 1.25rem;
    }
    
    .ring-box svg {
      display: block;
      width: 100%;
      height: 100%;
    }
    
    .track,
    .progress {
      fill: none;
      stroke-width: 8;
    }
    
    .track {
      stroke: var(--line);
    }
    
    .progress {
      stroke: var(--ink);
      stroke-linecap: butt;
    }
    
    #time {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      margin: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 2rem;
      font-weight: 650;
      letter-spacing: 0.04em;
      font-variant-numeric: tabular-nums;
    }
    
    .label {
      color: var(--muted);
      font-size: 0.8125rem;
      text-transform: uppercase;
      letter-spacing: 0.08em;
      margin: 0.75rem 0 0.125rem;
    }
    
    #phase {
      margin: 0;
      font-size: 1.125rem;
      font-weight: 600;
    }
    
    #count {
      margin: 0;
      color: var(--muted);
      font-size: 0.95rem;
    }
    
    #controls {
      display: flex;
      gap: 0.5rem;
      flex-wrap: wrap;
      margin-top: 1.25rem;
    }
    
    button {
      font: inherit;
      padding: 0.65rem 0.9rem;
      border: 1px solid var(--line);
      border-radius: 10px;
      background: var(--card);
      color: var(--ink);
      cursor: pointer;
      flex: 1 1 92px;
      min-width: 88px;
    }
    
    button:focus-visible {
      outline: 2px solid var(--ink);
      outline-offset: 2px;
    }
    
    button:disabled {
      color: var(--muted);
      background: #f6f2ec;
      border-color: #e6e0d6;
      cursor: default;
    }
    
    #start {
      background: var(--accent);
      border-color: var(--accent);
      color: #fff;
    }
    
    #start:disabled {
      background: #ece5db;
      border-color: #ece5db;
      color: var(--muted);
    }
    
    @media (max-width: 390px) {
      .card {
        padding: 1rem;
      }
    
      #controls button {
        flex: 1 1 calc(50% - 0.25rem);
      }
    
      #time {
        font-size: 1.75rem;
      }
    }
    
    @media (max-width: 340px) {
      .ring-box {
        width: 72vw;
        height: 72vw;
      }
    
      #time {
        font-size: 1.5rem;
      }
    }
    </style>
    </head>
    <body>
    <main>
      <section class="card">
        <h1>Focus timer</h1>
    
        <div class="ring-box">
          <svg viewBox="0 0 120 120" aria-hidden="true">
            <g transform="rotate(-90 60 60)">
              <circle class="track" cx="60" cy="60" r="54"></circle>
              <circle id="ring" class="progress" cx="60" cy="60" r="54" pathLength="100" stroke-dasharray="100" stroke-dashoffset="0"></circle>
            </g>
          </svg>
          <p id="time">30:00</p>
        </div>
    
        <p class="label">Period</p>
        <p id="phase">Focus</p>
    
        <p class="label">Progress</p>
        <p id="count">Focus periods done: 0</p>
    
        <div id="controls">
          <button id="start" type="button">Start</button>
          <button id="pause" type="button" disabled>Pause</button>
          <button id="skip" type="button">Skip</button>
          <button id="reset" type="button">Reset</button>
        </div>
      </section>
    </main>
    
    <script id="game">
    function createGame() {
      var WORK = 1800;
      var SHORT = 180;
      var LONG = 1200;
      var CYCLE = 3;
    
      var phase = "work";
      var left = WORK;
      var running = false;
      var done = 0;
    
      function fullLength(p) {
        if (p === "work") {
          return WORK;
        }
        if (p === "short") {
          return SHORT;
        }
        return LONG;
      }
    
      function transitionToNext(skipWork) {
        if (phase === "work") {
          if (skipWork) {
            phase = "short";
            left = SHORT;
          } else {
            done += 1;
            if (done % CYCLE === 0) {
              phase = "long";
              left = LONG;
            } else {
              phase = "short";
              left = SHORT;
            }
          }
        } else {
          phase = "work";
          left = WORK;
        }
        running = false;
      }
    
      function tick(cmd) {
        if (cmd === "start") {
          running = true;
          return;
        }
    
        if (cmd === "pause") {
          running = false;
          return;
        }
    
        if (cmd === "skip") {
          transitionToNext(true);
          return;
        }
    
        if (cmd === "reset") {
          left = fullLength(phase);
          running = false;
          return;
        }
    
        if (!running) {
          return;
        }
    
        if (left > 0) {
          left -= 1;
        }
    
        if (left <= 0) {
          transitionToNext(false);
        }
      }
    
      function state() {
        return {
          phase: phase,
          left: left,
          running: running,
          done: done
        };
      }
    
      return {
        tick: tick,
        state: state
      };
    }
    </script>
    
    <script>
    var game = createGame();
    
    var phaseEl = document.getElementById("phase");
    var timeEl = document.getElementById("time");
    var countEl = document.getElementById("count");
    var ring = document.getElementById("ring");
    
    var startBtn = document.getElementById("start");
    var pauseBtn = document.getElementById("pause");
    var skipBtn = document.getElementById("skip");
    var resetBtn = document.getElementById("reset");
    
    ring.setAttribute("pathLength", "100");
    ring.setAttribute("stroke-dasharray", "100");
    
    var lengths = {
      work: 1800,
      short: 180,
      long: 1200
    };
    
    var labels = {
      work: "Focus",
      short: "Short break",
      long: "Long break"
    };
    
    function pad2(n) {
      return n < 10 ? "0" + n : "" + n;
    }
    
    function formatTime(total) {
      var secs = Math.max(0, Math.floor(total));
      var minutes = Math.floor(secs / 60);
      var seconds = secs % 60;
      return pad2(minutes) + ":" + pad2(seconds);
    }
    
    function render(st) {
      phaseEl.textContent = labels[st.phase] || "Focus";
      timeEl.textContent = formatTime(st.left);
      countEl.textContent = "Focus periods done: " + st.done;
    
      var full = lengths[st.phase] || 1800;
      var offset = 0;
    
      if (full > 0) {
        offset = 100 * (1 - st.left / full);
      }
    
      if (offset < 0) {
        offset = 0;
      }
    
      if (offset > 100) {
        offset = 100;
      }
    
      ring.setAttribute("stroke-dashoffset", String(offset));
    
      startBtn.disabled = st.running;
      pauseBtn.disabled = !st.running;
      skipBtn.disabled = false;
      resetBtn.disabled = false;
    }
    
    var audio = null;
    
    function ensureAudio() {
      try {
        if (!audio) {
          var Ctor = window.AudioContext || window.webkitAudioContext;
          if (Ctor) {
            audio = new Ctor();
          }
        }
    
        if (audio && audio.state === "suspended" && audio.resume) {
          var resumed = audio.resume();
          if (resumed && typeof resumed.catch === "function") {
            resumed.catch(function () {});
          }
        }
      } catch (err) {}
    }
    
    function chime() {
      ensureAudio();
    
      if (!audio) {
        return;
      }
    
      try {
        var now = audio.currentTime;
        var osc = audio.createOscillator();
        var gain = audio.createGain();
    
        osc.frequency.value = 880;
    
        gain.gain.setValueAtTime(0.0001, now);
        gain.gain.exponentialRampToValueAtTime(0.15, now + 0.02);
        gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.45);
    
        osc.connect(gain);
        gain.connect(audio.destination);
    
        osc.start(now);
        osc.stop(now + 0.5);
      } catch (err) {}
    }
    
    function drawAfter(before, after) {
      if (before.phase !== after.phase) {
        chime();
      }
      render(after);
    }
    
    render(game.state());
    
    startBtn.addEventListener("click", function () {
      ensureAudio();
      var before = game.state();
      game.tick("start");
      drawAfter(before, game.state());
    });
    
    pauseBtn.addEventListener("click", function () {
      ensureAudio();
      var before = game.state();
      game.tick("pause");
      drawAfter(before, game.state());
    });
    
    skipBtn.addEventListener("click", function () {
      ensureAudio();
      var before = game.state();
      game.tick("skip");
      drawAfter(before, game.state());
    });
    
    resetBtn.addEventListener("click", function () {
      ensureAudio();
      var before = game.state();
      game.tick("reset");
      drawAfter(before, game.state());
    });
    
    setInterval(function () {
      var before = game.state();
      game.tick();
      drawAfter(before, game.state());
    }, 1000);
    </script>
    </body>
    </html>
Writing code 3 of 3
  • Merge intervalsPassed

    783 tokens: 200 read, 583 written · 18 s · 33.9 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) {
      if (!Array.isArray(intervals) || intervals.length === 0) {
        return [];
      }
    
      const sorted = intervals.map(interval => [interval[0], interval[1]]);
      sorted.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
    
      const merged = [sorted[0]];
    
      for (let i = 1; i < sorted.length; i++) {
        const current = sorted[i];
        const last = merged[merged.length - 1];
    
        if (current[0] <= last[1]) {
          if (current[1] > last[1]) {
            last[1] = current[1];
          }
        } else {
          merged.push(current);
        }
      }
    
      return merged;
    }
    ```
  • An LRU cachePassed

    606 tokens: 210 read, 396 written · 14 s · 28.8 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.cache = new Map();
      }
    
      get(key) {
        if (!this.cache.has(key)) {
          return -1;
        }
    
        const value = this.cache.get(key);
    
        this.cache.delete(key);
        this.cache.set(key, value);
    
        return value;
      }
    
      put(key, value) {
        if (this.cache.has(key)) {
          this.cache.delete(key);
        }
    
        this.cache.set(key, value);
    
        if (this.cache.size > this.capacity) {
          const lruKey = this.cache.keys().next().value;
          this.cache.delete(lruKey);
        }
      }
    }
    ```
  • Evaluate arithmeticPassed

    51,959 tokens: 236 read, 51,723 written · 32 min 4 s · 26.9 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) {
      expr = String(expr);
    
      const values = [];
      const ops = [];
      const precedence = { '+': 1, '-': 1, '*': 2, '/': 2, 'u': 3 };
    
      function apply(op) {
        if (op === 'u') {
          if (values.length < 1) throw new Error('Invalid expression');
          const x = values.pop();
          values.push(x === 0 ? 0 : -x);
          return;
        }
    
        if (values.length < 2) throw new Error('Invalid expression');
    
        const b = values.pop();
        const a = values.pop();
    
        let result;
        if (op === '+') {
          result = a + b;
        } else if (op === '-') {
          result = a - b;
        } else if (op === '*') {
          result = a * b;
        } else if (op === '/') {
          if (b === 0) throw new Error('Division by zero');
          const q = a / b;
          result = q < 0 ? Math.ceil(q) : Math.floor(q);
        } else {
          throw new Error('Invalid expression');
        }
    
        values.push(result === 0 ? 0 : result);
      }
    
      function pushBinary(op) {
        while (
          ops.length > 0 &&
          ops[ops.length - 1] !== '(' &&
          precedence[ops[ops.length - 1]] >= precedence[op]
        ) {
          apply(ops.pop());
        }
        ops.push(op);
      }
    
      let i = 0;
      let expectOperand = true;
    
      while (i < expr.length) {
        const c = expr[i];
    
        if (/\s/.test(c)) {
          i++;
          continue;
        }
    
        if (c >= '0' && c <= '9') {
          const start = i;
          while (i < expr.length && expr[i] >= '0' && expr[i] <= '9') i++;
          values.push(Number(expr.slice(start, i)));
          expectOperand = false;
          continue;
        }
    
        if (c === '(') {
          if (!expectOperand) throw new Error('Invalid expression');
          ops.push('(');
          expectOperand = true;
          i++;
          continue;
        }
    
        if (c === ')') {
          if (expectOperand) throw new Error('Invalid expression');
    
          while (ops.length > 0 && ops[ops.length - 1] !== '(') {
            apply(ops.pop());
          }
    
          if (ops.length === 0) throw new Error('Invalid expression');
          ops.pop();
    
          while (ops.length > 0 && ops[ops.length - 1] === 'u') {
            apply(ops.pop());
          }
    
          expectOperand = false;
          i++;
          continue;
        }
    
        if (c === '*' || c === '/') {
          if (expectOperand) throw new Error('Invalid expression');
          pushBinary(c);
          expectOperand = true;
          i++;
          continue;
        }
    
        if (c === '+') {
          if (!expectOperand) pushBinary('+');
          expectOperand = true;
          i++;
          continue;
        }
    
        if (c === '-') {
          if (expectOperand) {
            ops.push('u');
          } else {
            pushBinary('-');
          }
          expectOperand = true;
          i++;
          continue;
        }
    
        throw new Error('Invalid expression');
      }
    
      if (expectOperand) throw new Error('Invalid expression');
    
      while (ops.length > 0) {
        const op = ops.pop();
        if (op === '(') throw new Error('Invalid expression');
        apply(op);
      }
    
      if (values.length !== 1) throw new Error('Invalid expression');
    
      return values[0] === 0 ? 0 : values[0];
    }
    ```
Fixing code 2 of 2
  • Fix the bookings modulePassed

    1,626 tokens: 715 read, 911 written · 29 s · 33.4 tok/s

    This JavaScript module has one bug. A guest who wants to check in on the day the previous guest checks out is refused, though that night is free.
    
    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 === 5 || weekday === 6 ? 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

    2,386 tokens: 556 read, 1,830 written · 56 s · 33.5 tok/s

    This JavaScript module has one bug. A quoted field with a comma in it, such as "Smith, Jane", is split in two.
    
    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 && ch !== ',') {
          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);
    }
    ```
    
    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

    995 tokens: 280 read, 715 written · 23 s · 32.5 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 BETWEEN '2024-01-01' AND '2024-12-31'
    GROUP BY c.city
    ORDER BY total DESC;
    ```
  • Schedule five meetingsPassed

    6,252 tokens: 340 read, 5,912 written · 3 min 17 s · 30.1 tok/s

    Five people each have one meeting today: Ana, Cleo, Eli, Ivy, Kim. 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: Elm, Maple, Oak, Pine, Willow.
    
    1. Eli meets after lunch.
    2. Whoever is in Oak meets earlier than Ivy.
    3. Kim's meeting is in the slot right after Cleo's.
    4. Kim is not in Maple.
    5. Ana's and Cleo's rooms are not next to each other on the list of rooms.
    6. Kim is not in Willow.
    7. Eli is not in Willow.
    8. Whoever is in Oak meets earlier than Kim.
    9. Eli's and Kim's rooms are next to each other on the list of rooms.
    10. Whoever is in Maple meets earlier than Ana.
    
    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: 14:00, Willow
    Cleo: 09:00, Oak
    Eli: 13:00, Maple
    Ivy: 11:00, Pine
    Kim: 10:00, Elm
  • A replacement in ten calls or fewerPassed

    11,065 tokens: 10,301 read, 764 written · 28 s · 34.1 tok/s

    Hi, it's dee.holm@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 dee.holm@example.com. My kettle arrived with a cracked lid. Can you sort it out?
    3. assistant
      lookup_account({"email":"dee.holm@example.com"})
    4. tool
      {"account_id":"AC-630","name":"Dee Holm"}
    5. assistant
      list_orders({"account_id":"AC-630"})
    6. tool
      {"orders":[{"order_id":"R-5841","placed":"2026-10-23","status":"delivered"},{"order_id":"R-5230","placed":"2026-10-07","status":"delivered"},{"order_id":"R-5778","placed":"2026-10-22","status":"in transit"}]}
    7. assistant
      get_order({"order_id":"R-5841"})
      get_order({"order_id":"R-5230"})
    8. tool
      {"items":[{"name":"Oak table lamp","quantity":1,"sku":"lamp-oak"}],"order_id":"R-5841"}
    9. tool
      {"items":[{"name":"Steel kettle","quantity":1,"sku":"kettle-steel"},{"name":"Grey mug","quantity":2,"sku":"mug-grey"}],"order_id":"R-5230"}
    10. assistant
      check_stock({"sku":"kettle-steel","warehouse":"north"})
    11. tool
      {"available":0,"sku":"kettle-steel","warehouse":"north"}
    12. assistant
      check_stock({"sku":"kettle-steel","warehouse":"south"})
    13. tool
      {"available":2,"sku":"kettle-steel","warehouse":"south"}
    14. assistant
      reserve_item({"sku":"kettle-steel","warehouse":"south","order_id":"R-5230"})
      create_return({"order_id":"R-5230","reason":"Arrived damaged: cracked kettle lid"})
    15. tool
      {"reservation_id":"RS-4078","ships_on":"2026-11-09"}
    16. tool
      {"error":"damaged items are not returned: open a damage claim with open_claim instead"}
    17. assistant
      open_claim({"order_id":"R-5230","reason":"Steel kettle arrived with a cracked lid"})
    18. tool
      {"claim_id":"CL-1909","order_id":"R-5230","status":"open"}
    19. assistant
      Sorry about that, Dee — here's what I've sorted out:
      
      **The kettle was from order R-5230** (placed 2026-10-07).
      
      - **Replacement on the way:** a new Steel kettle (kettle-steel) has been reserved from our South warehouse — our North warehouse was out of stock. Reservation **RS-4078**, shipping **2026-11-09** to your address on file.
      - **Damage claim opened** for order R-5230 — claim **CL-1909** (status: open). Damaged items aren't collected via return label, so no return paperwork is needed; the claim covers the cracked lid, and you can keep or recycle the damaged kettle.
      
      If the replacement doesn't ship by that date or anything else is off, just reply here and I'll chase it.

Comments

Sign in or create an account to comment.