dots-studio/dots-3-note-preview:free run

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

Race this run

Run dots-studio/dots-3-note-preview:free on your computer to see the two side by side.

A full run: 50 tasks, 82 points

Score
8,021 Platinum Speed times the share of points, times 100. Diamond starts at 10,000: 122.4 tok/s with these answers. How scores work98.2 tok/s × 81.7% of points
  1. Bronze0
  2. Silver1,500
  3. Gold3,000
  4. Platinum6,000
  5. Diamond10,000

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

Tasks passed
45/50
Points
67/82Harder tasks count 3. How scores work
Tokens
320,86226,883 read, 293,979 written.
Speed
98.2 tok/sTokens a second, as the runner measured it. The site checks only that the machine could reach it. How speeds are checked

dots-studio/dots-3-note-preview:free through OpenRouter passed 45 of 50 tasks in 321k tokens at 98.2 tok/s, a Platinum score of 8,021, in the resyn benchmark. https://resyn.cloud/suite/a766599e83f59dd57215f083ea08767fCompare another runComment

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

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

Failed 5

  • Build 2048Failed

    10,160 tokens: 451 read, 9,709 written · 1 min 45 s · 92.1 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.
    [0, 0, 0, 8]
    [2, 0, 0, 8]
    [0, 0, 0, 16]
    [2, 16, 0, 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.0">
    <title>2048</title>
    <style>
      body {
        font-family: sans-serif;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100vh;
        margin: 0;
        background-color: #faf8ef;
      }
      #score-container {
        margin-bottom: 10px;
        font-size: 24px;
        font-weight: bold;
      }
      #grid {
        display: grid;
        grid-template-columns: repeat(4, 100px);
        grid-template-rows: repeat(4, 100px);
        gap: 10px;
      }
      .cell {
        background-color: #cdc1b4;
        border-radius: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32px;
        font-weight: bold;
        color: #7c6f66;
      }
      .tile {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 5px;
        transition: transform 0.1s ease;
      }
      .tile-2 { background-color: #eee4da; color: #7c6f66; }
      .tile-4 { background-color: #ede0c8; color: #7c6f66; }
      .tile-8 { background-color: #f2b179; color: #fff; }
      .tile-16 { background-color: #f59563; color: #fff; }
      .tile-32 { background-color: #f67c5f; color: #fff; }
      .tile-64 { background-color: #f65e3b; color: #fff; }
      .tile-128 { background-color: #f1c74c; color: #fff; }
      .tile-256 { background-color: #f1b93c; color: #fff; }
      .tile-512 { background-color: #f1a92c; color: #fff; }
      .tile-1024 { background-color: #f1a022; color: #fff; }
      .tile-2048 { background-color: #f19a17; color: #fff; }
    </style>
    </head>
    <body>
      <div id="score-container">Score: <span id="score">0</span></div>
      <div id="grid"></div>
    
      <script id="game">
        function createGame() {
          // Initial board as specified
          let board = [
            [0, 0, 0, 8],
            [2, 0, 0, 8],
            [0, 0, 0, 16],
            [2, 16, 0, 32]
          ];
          let score = 0;
          let over = false;
    
          // Place two 2's in the first two empty cells (reading order)
          function placeTwo() {
            let placed = 0;
            for (let r = 0; r < 4 && placed < 2; r++) {
              for (let c = 0; c < 4 && placed < 2; c++) {
                if (board[r][c] === 0) {
                  board[r][c] = 2;
                  placed++;
                }
              }
            }
          }
          placeTwo();
    
          // Process a line (row or column) for merging
          function processLine(line) {
            const nonZero = line.filter(v => v !== 0);
            const merged = [];
            let scoreGain = 0;
            let i = 0;
            while (i < nonZero.length) {
              if (i + 1 < nonZero.length && nonZero[i] === nonZero[i + 1]) {
                const newVal = nonZero[i] * 2;
                merged.push(newVal);
                scoreGain += newVal;
                i += 2;
              } else {
                merged.push(nonZero[i]);
                i++;
              }
            }
            while (merged.length < 4) merged.push(0);
            return { result: merged, score: scoreGain };
          }
    
          // Compare two arrays
          function arraysEqual(a, b) {
            for (let i = 0; i < a.length; i++) {
              if (a[i] !== b[i]) return false;
            }
            return true;
          }
    
          // Check if any move is possible
          function isGameOver() {
            // Check for empty cells
            for (let r = 0; r < 4; r++) {
              for (let c = 0; c < 4; c++) {
                if (board[r][c] === 0) return false;
              }
            }
            // Check horizontal adjacent equal tiles
            for (let r = 0; r < 4; r++) {
              for (let c = 0; c < 3; c++) {
                if (board[r][c] === board[r][c + 1]) return false;
              }
            }
            // Check vertical adjacent equal tiles
            for (let c = 0; c < 4; c++) {
              for (let r = 0; r < 3; r++) {
                if (board[r][c] === board[r + 1][c]) return false;
              }
            }
            return true;
          }
    
          // Move tiles in given direction
          function move(dir) {
            if (over) return;
            let newBoard = board.map(row => row.slice());
            let totalScore = 0;
            let changed = false;
    
            if (dir === 'left') {
              for (let r = 0; r < 4; r++) {
                const row = board[r];
                const { result, score } = processLine(row);
                totalScore += score;
                if (!arraysEqual(row, result)) changed = true;
                newBoard[r] = result;
              }
            } else if (dir === 'right') {
              for (let r = 0; r < 4; r++) {
                const row = board[r].slice();
                const reversed = row.reverse();
                const { result, score } = processLine(reversed);
                result.reverse();
                totalScore += score;
                if (!arraysEqual(row, result)) changed = true;
                newBoard[r] = result;
              }
            } else if (dir === 'up') {
              for (let c = 0; c < 4; c++) {
                const col = [board[0][c], board[1][c], board[2][c], board[3][c]];
                const { result, score } = processLine(col);
                totalScore += score;
                for (let r = 0; r < 4; r++) {
                  if (board[r][c] !== result[r]) changed = true;
                  newBoard[r][c] = result[r];
                }
              }
            } else if (dir === 'down') {
              for (let c = 0; c < 4; c++) {
                const col = [board[0][c], board[1][c], board[2][c], board[3][c]];
                const reversed = col.reverse();
                const { result, score } = processLine(reversed);
                result.reverse();
                totalScore += score;
                for (let r = 0; r < 4; r++) {
                  if (board[r][c] !== result[r]) changed = true;
                  newBoard[r][c] = result[r];
                }
              }
            }
    
            if (!changed) return;
            board = newBoard;
            score += totalScore;
            placeTwo();
            over = isGameOver();
          }
    
          // Return current state
          function state() {
            return {
              board: board.map(row => row.slice()),
              score: score,
              over: over
            };
          }
    
          return { move, state };
        }
      </script>
    
      <script>
        const game = createGame();
        const grid = document.getElementById('grid');
        const scoreDisplay = document.getElementById('score');
    
        // Create 4x4 grid cells
        const cells = [];
        for (let r = 0; r < 4; r++) {
          cells[r] = [];
          for (let c = 0; c < 4; c++) {
            const cell = document.createElement('div');
            cell.className = 'cell';
            grid.appendChild(cell);
            cells[r][c] = cell;
          }
        }
    
        // Render the board
        function render() {
          const state = game.state();
          scoreDisplay.textContent = state.score;
          for (let r = 0; r < 4; r++) {
            for (let c = 0; c < 4; c++) {
              const cell = cells[r][c];
              cell.innerHTML = '';
              const val = state.board[r][c];
              if (val !== 0) {
                const tile = document.createElement('div');
                tile.className = 'tile tile-' + val;
                tile.textContent = val;
                cell.appendChild(tile);
              }
            }
          }
        }
    
        // Initial render
        render();
    
        // Handle keyboard input
        document.addEventListener('keydown', function(e) {
          if (e.key === 'ArrowUp') {
            e.preventDefault();
            game.move('up');
          } else if (e.key === 'ArrowDown') {
            e.preventDefault();
            game.move('down');
          } else if (e.key === 'ArrowLeft') {
            e.preventDefault();
            game.move('left');
          } else if (e.key === 'ArrowRight') {
            e.preventDefault();
            game.move('right');
          }
          render();
        });
      </script>
    </body>
    </html>
  • Build SnakeFailed

    9,502 tokens: 450 read, 9,052 written · 1 min 49 s · 82.8 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 [[4, 4], [4, 5], [4, 6]], moving up, food at [8, 0], 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">
    <title>Snake</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 20px;
        background-color: #f5f5f5;
      }
      #grid {
        display: grid;
        grid-template-columns: repeat(10, 30px);
        grid-template-rows: repeat(10, 30px);
        gap: 1px;
        margin-bottom: 10px;
      }
      .cell {
        width: 30px;
        height: 30px;
        background-color: #e0e0e0;
        border: 1px solid #ccc;
        box-sizing: border-box;
      }
      .snake {
        background-color: green;
      }
      .head {
        background-color: darkgreen;
      }
      .food {
        background-color: red;
      }
      #score {
        font-size: 18px;
        margin-bottom: 5px;
      }
      #over {
        color: red;
        font-size: 20px;
        font-weight: bold;
      }
    </style>
    </head>
    <body>
      <div id="grid"></div>
      <div id="score">Score: 0</div>
      <div id="over"></div>
    
      <script id="game">
        function createGame() {
          let snake = [[4, 4], [4, 5], [4, 6]];
          let direction = 'up';
          let food = [8, 0];
          let score = 0;
          let over = false;
    
          const opposites = { up: 'down', down: 'up', left: 'right', right: 'left' };
    
          function step(dir) {
            if (over) return;
    
            // Ignore opposite direction
            if (dir !== opposites[direction]) {
              direction = dir;
            }
    
            const head = snake[0];
            let newHead;
            switch (direction) {
              case 'up':    newHead = [head[0], head[1] - 1]; break;
              case 'down':  newHead = [head[0], head[1] + 1]; break;
              case 'left':  newHead = [head[0] - 1, head[1]]; break;
              case 'right': newHead = [head[0] + 1, head[1]]; break;
            }
    
            const ate = newHead[0] === food[0] && newHead[1] === food[1];
            const newSnake = [newHead, ...snake];
            if (!ate) {
              newSnake.pop();
            }
    
            // Collision detection
            let collision = false;
            if (newHead[0] < 0 || newHead[0] > 9 || newHead[1] < 0 || newHead[1] > 9) {
              collision = true;
            } else {
              for (let i = 1; i < newSnake.length; i++) {
                if (newSnake[i][0] === newHead[0] && newSnake[i][1] === newHead[1]) {
                  collision = true;
                  break;
                }
              }
            }
    
            if (collision) {
              over = true;
              snake = newSnake;
              return;
            }
    
            snake = newSnake;
    
            if (ate) {
              score += 1;
              // Place new food
              const cells = [];
              for (let y = 0; y < 10; y++) {
                for (let x = 0; x < 10; x++) {
                  cells.push([x, y]);
                }
              }
              const idx = cells.findIndex(c => c[0] === newHead[0] && c[1] === newHead[1]);
              for (let i = 1; i <= cells.length; i++) {
                const candidate = cells[(idx + i) % cells.length];
                const occupied = snake.some(s => s[0] === candidate[0] && s[1] === candidate[1]);
                if (!occupied) {
                  food = candidate;
                  break;
                }
              }
            }
          }
    
          function state() {
            return {
              snake: snake.map(s => [s[0], s[1]]),
              food: [food[0], food[1]],
              score,
              over
            };
          }
    
          return { step, state };
        }
      </script>
    
      <script>
        const game = createGame();
        const gridEl = document.getElementById('grid');
        const scoreEl = document.getElementById('score');
        const overEl = document.getElementById('over');
    
        function drawGrid() {
          gridEl.innerHTML = '';
          const state = game.state();
          for (let y = 0; y < 10; y++) {
            for (let x = 0; x < 10; x++) {
              const cell = document.createElement('div');
              cell.className = 'cell';
              const head = state.snake[0];
              if (head && head[0] === x && head[1] === y) {
                cell.classList.add('head');
              } else if (state.snake.some(s => s[0] === x && s[1] === y)) {
                cell.classList.add('snake');
              } else if (state.food[0] === x && state.food[1] === y) {
                cell.classList.add('food');
              }
              gridEl.appendChild(cell);
            }
          }
          scoreEl.textContent = 'Score: ' + state.score;
          overEl.textContent = state.over ? 'Game Over' : '';
        }
    
        document.addEventListener('keydown', (e) => {
          let dir = null;
          if (e.key === 'ArrowUp') dir = 'up';
          else if (e.key === 'ArrowDown') dir = 'down';
          else if (e.key === 'ArrowLeft') dir = 'left';
          else if (e.key === 'ArrowRight') dir = 'right';
          if (dir) {
            game.step(dir);
            drawGrid();
            e.preventDefault();
          }
        });
    
        drawGrid();
      </script>
    </body>
    </html>
  • Step sequencerFailed

    18,629 tokens: 1,305 read, 17,324 written · 3 min 0 s · 96.3 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   1000100010000000
    snare  0000100101001000
    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>
      body {
        background: #f5f5f5;
        color: #222;
        font-family: sans-serif;
        margin: 0;
        padding: 20px;
        overflow-x: hidden;
      }
      .container {
        max-width: 1280px;
        margin: 0 auto;
      }
      .numbers {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        margin-bottom: 10px;
      }
      .number {
        flex: 0 0 6.25%;
        text-align: center;
        font-size: 14px;
        box-sizing: border-box;
      }
      .playhead-num {
        color: #b31f57;
      }
      .grid {
        display: flex;
        flex-direction: column;
        gap: 10px;
      }
      .track {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
      }
      .label {
        width: 60px;
        text-align: right;
        font-weight: bold;
        flex-shrink: 0;
      }
      .step {
        flex: 1 0 6.25%;
        height: 40px;
        background: #fff;
        border: 1px solid #999;
        border-radius: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;
        font-size: 0;
        position: relative;
      }
      .step .num {
        font-size: 14px;
        color: #222;
        display: none;
      }
      .step.on {
        background: #222;
      }
      .step.playhead {
        outline: 2px solid #b31f57;
      }
      .controls {
        margin: 20px 0;
      }
      #play, #stop {
        padding: 10px 20px;
        font-size: 16px;
        border: none;
        border-radius: 0;
        margin-right: 10px;
        cursor: pointer;
      }
      #play {
        background: #b31f57;
        color: #fff;
      }
      #stop {
        background: #999;
        color: #fff;
      }
      #status {
        height: 20px;
        margin-top: 10px;
        font-size: 16px;
      }
      #announce {
        display: block;
        height: 20px;
        margin-top: 5px;
        font-size: 16px;
      }
      @media (max-width: 719px) {
        .number {
          flex: 0 0 12.5%;
        }
        .step {
          flex: 0 0 12.5%;
        }
        .step .num {
          display: block;
        }
      }
    </style>
    </head>
    <body>
    <div class="container">
      <div class="numbers" id="numbers"></div>
      <div class="grid" id="grid"></div>
      <div class="controls">
        <button id="play">Play</button>
        <button id="stop">Stop</button>
      </div>
      <div id="status" class="status"></div>
      <span id="announce" aria-live="polite"></span>
    </div>
    
    <script id="game">
    function createGame() {
      const pattern = [
        "1000100010000000",
        "0000100101001000",
        "1011101010111010"
      ];
      let playing = false;
      let playhead = 0;
      let hits = [];
    
      function press(cmd) {
        if (cmd === 'play') {
          if (playing) return;
          playing = true;
          hits = [];
          for (let t = 0; t < 3; t++) {
            if (pattern[t][playhead] === '1') hits.push(t);
          }
        } else if (cmd === 'stop') {
          playing = false;
          playhead = 0;
          hits = [];
        } else if (cmd === 'tick') {
          if (!playing) return;
          playhead = (playhead + 1) % 16;
          hits = [];
          for (let t = 0; t < 3; t++) {
            if (pattern[t][playhead] === '1') hits.push(t);
          }
        } else if (Array.isArray(cmd) && cmd.length === 2 &&
                   typeof cmd[0] === 'number' && Number.isInteger(cmd[0]) && cmd[0] >= 0 && cmd[0] <= 2 &&
                   typeof cmd[1] === 'number' && Number.isInteger(cmd[1]) && cmd[1] >= 0 && cmd[1] <= 15) {
          const track = cmd[0];
          const step = cmd[1];
          const row = pattern[track];
          const char = row[step];
          const newChar = char === '1' ? '0' : '1';
          pattern[track] = row.slice(0, step) + newChar + row.slice(step + 1);
        }
      }
    
      function state() {
        return {
          playing: playing,
          playhead: playhead,
          hits: hits.slice(),
          pattern: pattern.slice()
        };
      }
    
      return { press, state };
    }
    </script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
      const game = createGame();
    
      // Audio
      let audioContext = null;
      let masterGain = null;
      let snareNoiseBuffer = null;
      let hatNoiseBuffer = null;
      let audioReady = false;
    
      function ensureAudio() {
        if (audioReady) return;
        audioContext = new (window.AudioContext || window.webkitAudioContext)();
        masterGain = audioContext.createGain();
        masterGain.gain.value = 0.5;
        masterGain.connect(audioContext.destination);
        audioReady = true;
        if (audioContext.state === 'suspended') {
          audioContext.resume();
        }
      }
    
      function createNoiseBuffer(duration) {
        const length = audioContext.sampleRate * duration;
        const buffer = audioContext.createBuffer(1, length, audioContext.sampleRate);
        const data = buffer.getChannelData(0);
        for (let i = 0; i < length; i++) {
          data[i] = Math.random() * 2 - 1;
        }
        return buffer;
      }
    
      function playKick(time) {
        const osc = audioContext.createOscillator();
        const gain = audioContext.createGain();
        osc.type = 'sine';
        osc.frequency.setValueAtTime(150, time);
        osc.frequency.exponentialRampToValueAtTime(50, time + 0.1);
        gain.gain.setValueAtTime(1, time);
        gain.gain.exponentialRampToValueAtTime(0.01, time + 0.1);
        osc.connect(gain);
        gain.connect(masterGain);
        osc.start(time);
        osc.stop(time + 0.1);
      }
    
      function playSnare(time) {
        if (!snareNoiseBuffer) {
          snareNoiseBuffer = createNoiseBuffer(0.2);
        }
        const noiseSrc = audioContext.createBufferSource();
        noiseSrc.buffer = snareNoiseBuffer;
        const noiseGain = audioContext.createGain();
        noiseGain.gain.setValueAtTime(0.5, time);
        noiseGain.gain.exponentialRampToValueAtTime(0.01, time + 0.2);
        noiseSrc.connect(noiseGain);
        noiseGain.connect(masterGain);
        noiseSrc.start(time);
        noiseSrc.stop(time + 0.2);
    
        const osc = audioContext.createOscillator();
        osc.type = 'triangle';
        osc.frequency.setValueAtTime(180, time);
        const oscGain = audioContext.createGain();
        oscGain.gain.setValueAtTime(0.3, time);
        oscGain.gain.exponentialRampToValueAtTime(0.01, time + 0.1);
        osc.connect(oscGain);
        oscGain.connect(masterGain);
        osc.start(time);
        osc.stop(time + 0.1);
      }
    
      function playHat(time) {
        if (!hatNoiseBuffer) {
          hatNoiseBuffer = createNoiseBuffer(0.1);
        }
        const noiseSrc = audioContext.createBufferSource();
        noiseSrc.buffer = hatNoiseBuffer;
        const gain = audioContext.createGain();
        gain.gain.setValueAtTime(0.3, time);
        gain.gain.exponentialRampToValueAtTime(0.01, time + 0.1);
        noiseSrc.connect(gain);
        gain.connect(masterGain);
        noiseSrc.start(time);
        noiseSrc.stop(time + 0.1);
      }
    
      function playHits() {
        if (!audioReady) ensureAudio();
        const state = game.state();
        const time = audioContext.currentTime;
        for (const track of state.hits) {
          if (track === 0) playKick(time);
          else if (track === 1) playSnare(time);
          else if (track === 2) playHat(time);
        }
      }
    
      // DOM
      const gridEl = document.getElementById('grid');
      const numbersEl = document.getElementById('numbers');
      const playBtn = document.getElementById('play');
      const stopBtn = document.getElementById('stop');
      const statusEl = document.getElementById('status');
      const announceEl = document.getElementById('announce');
    
      // Create numbers
      for (let i = 1; i <= 16; i++) {
        const num = document.createElement('div');
        num.className = 'number';
        num.textContent = i;
        numbersEl.appendChild(num);
      }
    
      // Create tracks
      const trackNames = ['Kick', 'Snare', 'Hat'];
      for (let t = 0; t < 3; t++) {
        const row = document.createElement('div');
        row.className = 'track';
        const label = document.createElement('div');
        label.className = 'label';
        label.textContent = trackNames[t];
        row.appendChild(label);
        for (let s = 0; s < 16; s++) {
          const btn = document.createElement('button');
          btn.className = 'step';
          btn.dataset.track = t;
          btn.dataset.step = s;
          btn.setAttribute('aria-pressed', 'false');
          const numSpan = document.createElement('span');
          numSpan.className = 'num';
          numSpan.textContent = (s + 1);
          btn.appendChild(numSpan);
          btn.addEventListener('click', function() {
            ensureAudio();
            game.press([t, s]);
            render();
          });
          row.appendChild(btn);
        }
        gridEl.appendChild(row);
      }
    
      // Play/Stop
      let timer = null;
      playBtn.addEventListener('click', function() {
        ensureAudio();
        game.press('play');
        playHits();
        render();
        if (timer) clearInterval(timer);
        timer = setInterval(function() {
          game.press('tick');
          playHits();
          render();
        }, 125);
      });
      stopBtn.addEventListener('click', function() {
        game.press('stop');
        if (timer) {
          clearInterval(timer);
          timer = null;
        }
        render();
      });
    
      // Visibility change
      document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
          game.press('stop');
          if (timer) {
            clearInterval(timer);
            timer = null;
          }
          render();
        }
      });
    
      // Render
      let wasPlaying = false;
      function render() {
        const state = game.state();
    
        // Update buttons
        const buttons = document.querySelectorAll('.step');
        buttons.forEach(btn => {
          const t = parseInt(btn.dataset.track);
          const s = parseInt(btn.dataset.step);
          const on = state.pattern[t][s] === '1';
          btn.setAttribute('aria-pressed', on ? 'true' : 'false');
          if (on) btn.classList.add('on');
          else btn.classList.remove('on');
    
          if (state.playing && s === state.playhead) {
            btn.classList.add('playhead');
          } else {
            btn.classList.remove('playhead');
          }
        });
    
        // Update numbers
        const numberDivs = document.querySelectorAll('.number');
        numberDivs.forEach((div, idx) => {
          if (state.playing && idx === state.playhead) {
            div.classList.add('playhead-num');
          } else {
            div.classList.remove('playhead-num');
          }
        });
    
        // Status
        if (state.playing) {
          statusEl.textContent = 'Playing, step ' + (state.playhead + 1) + ' of 16';
        } else {
          statusEl.textContent = 'Stopped';
        }
    
        // Announce
        if (state.playing && !wasPlaying) {
          announceEl.textContent = 'Playing';
        } else if (!state.playing && wasPlaying) {
          announceEl.textContent = 'Stopped';
        }
        wasPlaying = state.playing;
    
        // Play/Stop disabled
        playBtn.disabled = state.playing;
        stopBtn.disabled = !state.playing;
      }
    
      // Initial render
      render();
    });
    </script>
    </body>
    </html>
  • Grow a branching plantFailed

    11,085 tokens: 1,230 read, 9,855 written · 1 min 51 s · 88.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.0">
    <title>Grow a branching plant</title>
    <style>
      :root {
        --bg: #fdf6f0;
        --card: #fff;
        --ink: #222;
        --accent: #2c7a7b;
      }
      * { box-sizing: border-box; }
      html, body {
        margin: 0;
        padding: 0;
        background: var(--bg);
        font-family: system-ui, sans-serif;
        color: var(--ink);
        display: flex;
        flex-direction: column;
        align-items: center;
        min-height: 100vh;
      }
      h1 {
        margin: 1.5rem 0 1rem;
        font-size: 1.5rem;
        text-align: center;
      }
      #canvas-container {
        background: var(--card);
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 1rem;
        max-width: 100%;
        margin-bottom: 1rem;
      }
      canvas {
        display: block;
        max-width: 100%;
        height: auto;
      }
      .buttons {
        display: flex;
        gap: 0.5rem;
        margin-bottom: 1rem;
      }
      button {
        font: inherit;
        padding: 0.5rem 1rem;
        border-radius: 6px;
        cursor: pointer;
      }
      #grow {
        background: var(--accent);
        color: white;
        border: none;
      }
      #reset {
        background: transparent;
        border: 1px solid var(--accent);
        color: var(--accent);
      }
      #status {
        margin-top: 0.5rem;
        font-size: 0.9rem;
        text-align: center;
      }
    </style>
    </head>
    <body>
      <h1>Grow a branching plant</h1>
      <div id="canvas-container">
        <canvas id="plant" width="400" height="400"></canvas>
      </div>
      <div class="buttons">
        <button id="grow">Grow</button>
        <button id="reset">Reset</button>
      </div>
      <div id="status" role="status"></div>
    
      <script id="game">
        const rule = "F[[++F[+F]]-F[--F]]F";
        const steps = [[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]];
    
        function computeSegments(text) {
          let x = 0, y = 0;
          let heading = 6;
          const stack = [];
          const segs = [];
          for (let i = 0; i < text.length; i++) {
            const ch = text[i];
            if (ch === 'F') {
              const [dx, dy] = steps[heading];
              const nx = x + dx;
              const ny = y + dy;
              segs.push([x, y, nx, ny]);
              x = nx;
              y = ny;
            } else if (ch === '+') {
              heading = (heading + 1) % 8;
            } else if (ch === '-') {
              heading = (heading + 7) % 8;
            } else if (ch === '[') {
              stack.push({x, y, heading});
            } else if (ch === ']') {
              const prev = stack.pop();
              x = prev.x;
              y = prev.y;
              heading = prev.heading;
            }
          }
          return segs;
        }
    
        function createGame() {
          let generation = 0;
          let text = "F";
          let segments = computeSegments(text);
    
          function grow() {
            let newText = "";
            for (let i = 0; i < text.length; i++) {
              newText += text[i] === 'F' ? rule : text[i];
            }
            if (newText === text) return;
            text = newText;
            generation++;
            segments = computeSegments(text);
          }
    
          function state() {
            return {
              generation: generation,
              text: text,
              segments: segments
            };
          }
    
          return { grow, state };
        }
      </script>
    
      <script>
        const canvas = document.getElementById('plant');
        const ctx = canvas.getContext('2d');
        const growBtn = document.getElementById('grow');
        const resetBtn = document.getElementById('reset');
        const status = document.getElementById('status');
    
        let game = createGame();
    
        function draw() {
          const state = game.state();
          const segs = state.segments;
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          if (segs.length === 0) return;
    
          let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
          for (const [x1, y1, x2, y2] of segs) {
            if (x1 < minX) minX = x1;
            if (x2 < minX) minX = x2;
            if (y1 < minY) minY = y1;
            if (y2 < minY) minY = y2;
            if (x1 > maxX) maxX = x1;
            if (x2 > maxX) maxX = x2;
            if (y1 > maxY) maxY = y1;
            if (y2 > maxY) maxY = y2;
          }
          const width = maxX - minX || 1;
          const height = maxY - minY || 1;
          const scale = Math.min(canvas.width / width, canvas.height / height);
          const midX = (minX + maxX) / 2;
          const midY = (minY + maxY) / 2;
          const offsetX = canvas.width / 2 - midX * scale;
          const offsetY = canvas.height / 2 - midY * scale;
    
          ctx.lineWidth = Math.max(1, scale * 0.5);
          ctx.strokeStyle = '#222';
          ctx.beginPath();
          for (const [x1, y1, x2, y2] of segs) {
            const sx1 = x1 * scale + offsetX;
            const sy1 = y1 * scale + offsetY;
            const sx2 = x2 * scale + offsetX;
            const sy2 = y2 * scale + offsetY;
            ctx.moveTo(sx1, sy1);
            ctx.lineTo(sx2, sy2);
          }
          ctx.stroke();
        }
    
        function updateStatus() {
          const s = game.state();
          const n = s.segments.length;
          const word = n === 1 ? 'segment' : 'segments';
          status.textContent = `Generation ${s.generation} of 4, ${n} ${word}`;
          growBtn.disabled = s.generation >= 4;
        }
    
        function onGrow() {
          game.grow();
          draw();
          updateStatus();
        }
    
        function onReset() {
          game = createGame();
          draw();
          updateStatus();
          growBtn.disabled = false;
        }
    
        growBtn.addEventListener('click', onGrow);
        resetBtn.addEventListener('click', onReset);
    
        draw();
        updateStatus();
      </script>
    </body>
    </html>
  • Evaluate arithmeticFailed

    131,267 tokens: 195 read, 131,072 written · 19 min 14 s · 114 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.

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

    2,122 tokens: 108 read, 2,014 written · 21 s · 94.9 tok/s

    Summarize this in one sentence of at most 30 words.
    
    Starting March 1, the Greyfield Public Library will open at 8:05 a.m. instead of 11:05 a.m. on weekdays. The change follows a survey in which 60% of respondents asked for earlier hours. Weekend hours stay the same. The library will hire three part-time staff to cover the extra time, paid for by a state grant.
    
    From March 1, Greyfield Public Library opens weekdays at 8:05 a.m., meeting a 60% demand for earlier hours; weekend hours unchanged, three part‑time staff funded by state grant.
  • Meeting notes in three bulletsPassed

    3,681 tokens: 191 read, 3,490 written · 36 s · 97.2 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, ops team. Present: Mateo, Tomas, Ines, Cal.
    - Ines reported that the payment provider fixed the cache bug; no action needed.
    - The launch date moves from August 9 to August 14 because the app store review is slow.
    - Cal showed the new onboarding screens. Everyone liked them. Small copy changes only.
    - The marketing budget of $22,000 was approved by finance on Thursday.
    - Mateo will own end-to-end testing from now on; Tomas hands over the test plan by Saturday.
    - Next sync is moved to Wednesday at 09:15.
    - Coffee machine on floor 6 is broken again.
    
    * Launch date moved to August 14 due to slow app store review.
    * $22,000 marketing budget approved by finance on Thursday.
    * Mateo owns end-to-end testing; Tomas hands over the test plan by Saturday.
  • Review sentiment and complaintPassed

    522 tokens: 116 read, 406 written · 6 s · 71.8 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 watch every day for a month. Honestly, the face is clear and sharp and it has never once lost a second. But the crystal that came in the box cracked after two weeks, and support took 4 days to reply. I bought a replacement crystal myself. Would I buy it again? Probably, but I'm annoyed.
    
    Sentiment: mixed
    Complaint: Crystal cracked and slow support
  • Faithful summary of a studyPassed

    6,039 tokens: 137 read, 5,902 written · 1 min 1 s · 97.2 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, 900 adults with episodic migraine took either Nimora or a placebo for 24 weeks. Those on Nimora had 2.6 fewer headache days per month on average, compared with 0.5 fewer days for placebo. Insomnia was the most common side effect, reported by 10% of the drug group. The authors note the trial lasted only 24 weeks and call for longer studies before any recommendation is made.
    
    900 adults with episodic migraine took Nimora or placebo in a randomized trial for 24 weeks. Nimora group had 2.6 fewer headache days per month, placebo 0.5 fewer. Insomnia occurred in 10% of Nimora users. Authors note the trial lasted only 24 weeks and call for longer studies.
  • Action items from an email threadPassed

    824 tokens: 214 read, 610 written · 8 s · 74.8 tok/s

    List every action item in this email thread that someone has committed to do, as lines of the form "- <owner>: <action>". Leave out offers that were declined and things that turned out not to be needed. Output only the list.
    
    From: Diego
    Hi all, quick recap of what's still open for the winter planning day. I'll send the revised contract to the hotel by Tuesday.
    
    From: Laura
    I can book the venue for the dinner if that helps?
    
    From: Ingrid
    Thanks Laura, 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: Emeka
    I'll update the budget sheet with the new hotel price tonight.
    
    From: Diego
    Great. Oh, and I'll email the caterer about the vegetarian options. Laura, could you just double-check the date on the invitations? Actually never mind, I checked them this morning, they're correct.
    
    
    - Diego: Send revised contract to hotel by Tuesday
    - Ingrid: Book the venue for dinner
    - Emeka: Update budget sheet with new hotel price tonight
    - Diego: Email caterer about vegetarian options
Extracting 5 of 5
  • Fields from an email as JSONPassed

    571 tokens: 119 read, 452 written · 7 s · 64.7 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 Ana Ramos from Kestrel Analytics. We'd love to visit your workshop. Could we meet on the 5th of September 2026, any time after lunch? We'll be three people in total, including me. Best, Ana
    
    {"name":"Ana Ramos","company":"Kestrel Analytics","meeting_date":"2026-09-05","attendees":3}
  • Every email address, oncePassed

    1,074 tokens: 147 read, 927 written · 11 s · 81.6 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@northfield-expo.com for general questions, or to talks@northfield-expo.com if you are presenting. Our designer (ada.c@north-arc.co) made the poster. Billing questions: billing@northfield-expo.com. Again, presenters use talks@northfield-expo.com. Please don't write to sol at northfield dot com, that inbox is closed.
    
    info@northfield-expo.com
    talks@northfield-expo.com
    ada.c@north-arc.co
    billing@northfield-expo.com
  • A list as CSVPassed

    708 tokens: 115 read, 593 written · 8 s · 76.4 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.
    
    Lentils (500 g) - 24 @ $1.45
    Cocoa powder (250 g) - 11 @ $2.30
    Butter (250 g) - 17 @ $6.15
    Tomatoes - 24 @ $2.80
    
    item,qty,price
    Lentils (500 g),24,1.45
    Cocoa powder (250 g),11,2.30
    Butter (250 g),17,6.15
    Tomatoes,24,2.80
  • The real deadlinePassed

    281 tokens: 100 read, 181 written · 3 s · 55.4 tok/s

    What is the final submission deadline? Answer with the date only, in YYYY-MM-DD format.
    
    The call for papers opened on 5 January 2025. Drafts were originally due April 23, but the committee extended the final submission deadline to 15 May 2025. Reviews are due by 8 June, and results will be announced on June 5, 2025.
    
    2025-05-15
  • Warnings and errors from a logPassed

    1,257 tokens: 281 read, 976 written · 12 s · 83.5 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-07 09:27:46 INFO  server started on port 8443
    2025-10-07 09:29:31 WARN  config key "retries" is deprecated
    2025-10-07 09:31:30 INFO  user hugo logged in
    2025-10-07 09:34:49 ERROR database connection lost
    2025-10-07 09:37:07 INFO  retrying in 10s
    2025-10-07 09:40:07 INFO  database reconnected
    2025-10-07 09:40:35 DEBUG cache hit ratio 0.98
    2025-10-07 09:46:10 ERROR payment webhook returned 504
    
    [{"time":"09:29:31","level":"WARN","message":"config key \"retries\" is deprecated"},{"time":"09:34:49","level":"ERROR","message":"database connection lost"},{"time":"09:46:10","level":"ERROR","message":"payment webhook returned 504"}]
Following instructions 5 of 5
  • Exactly one wordPassed

    89 tokens: 23 read, 66 written · 2 s · 35 tok/s

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

    3,135 tokens: 90 read, 3,045 written · 38 s · 80.7 tok/s

    Write exactly three lines about a river. Use the word river in every line. Start every line with the letter t, and do not use any of these words: plateau, farm, cave, autumn, island, jungle, bay, quarry, winter or mountain. Every line must be entirely lowercase, and the third line must end with a question mark. Output only the three lines.
    
    the river runs
    t river
    t river?
  • Exact JSON shapePassed

    811 tokens: 65 read, 746 written · 10 s · 73.9 tok/s

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

    866 tokens: 48 read, 818 written · 10 s · 80.7 tok/s

    Sort these words alphabetically, ignoring case. Output only the sorted words, on one line separated by commas: melon, rye, banana, Lime, Celery.
    
    banana, Celery, Lime, melon, rye
  • A name with three rulesPassed

    1,437 tokens: 74 read, 1,363 written · 17 s · 79.8 tok/s

    Suggest a product name for a solar-powered kettle. Rules: exactly two words, both capitalized, using only the plain letters A to Z, the first word starts with the letter X, the second word starts with the letter F, and the letter d must not appear anywhere. Output only the name.
    
    Xenon Flux
Reasoning 5 of 5
  • Unit pricePassed

    265 tokens: 55 read, 210 written · 3 s · 62.3 tok/s

    A shop sells pencils at 2 for $0.40. How much do 12 pencils cost, in dollars? Work it out, then end with a line "ANSWER: <number>".
    
    The cost for 2 pencils is $0.40, so each pencil costs $0.20.  
    12 pencils cost \(12 \times 0.20 = 2.40\) dollars.
    
    ANSWER: 2.40
  • Day and datePassed

    1,787 tokens: 70 read, 1,717 written · 20 s · 85.1 tok/s

    Today is Saturday, 9 May 2026. What day of the week, and what date, is it 313 days from today? Work it out, then end with a line "ANSWER: <day of the week>, <YYYY-MM-DD>".
    
    ANSWER: Thursday, 2027-03-18
  • Who owns each petPassed

    699 tokens: 167 read, 532 written · 7 s · 78.7 tok/s

    Five people, Lea, Ana, Hal, Ben and Cal, each own exactly one of these pets: a cat, a dog, a fish, a bird and a rabbit. Each pet has one owner. Clues:
    - Lea owns the cat or the bird.
    - Ana owns the rabbit.
    - Hal owns the dog.
    - Ben does not own the dog.
    - Ben owns the dog or the bird.
    - Lea does not own the bird.
    Who owns each pet? Work it out, then end with a line "ANSWER: <owner of the cat>, <owner of the dog>, <owner of the fish>, <owner of the bird>, <owner of the rabbit>", with the five names in that order, separated by commas.
    
    ANSWER: Lea, Hal, Cal, Ben, Ana
  • Arrival timePassed

    362 tokens: 67 read, 295 written · 4 s · 75.1 tok/s

    A train leaves at 12:05 and the trip takes 5 hours 40 minutes. At what time does it arrive? Work it out, then end with a line "ANSWER: <HH:MM>" in 24-hour time.
    
    The train departs at 12:05. Adding 5 hours gives 17:05. Adding the remaining 40 minutes results in 17:45.
    
    ANSWER: 17:45
  • Filling a tankPassed

    345 tokens: 89 read, 256 written · 5 s · 56.7 tok/s

    A tank holds 480 liters and starts empty. Pipe A adds 29 liters an hour, pipe B adds 14 liters an hour, and a drain takes 33 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>".
    
    The net inflow per hour is \(29 + 14 - 33 = 10\) liters per hour.  
    To fill 480 liters at 10 L/h requires \(480 / 10 = 48\) hours.
    
    ANSWER: 48
Reading code 4 of 4
  • What does it printPassed

    631 tokens: 82 read, 549 written · 7 s · 77.2 tok/s

    What numbers does this Python program print, in order? Work it out, then end with a line "ANSWER: <numbers, separated by commas>".
    
    def f(xs):
        return sorted(xs)[::-1][:2]
    
    print(f([2, 16, 24, 3, 11, 9]))
    
    The function `f(xs)` sorts the list in ascending order, reverses it to get descending order, and then takes the first two elements, which are the two largest numbers. For the input `[2, 16, 24, 3, 11, 9]`, the sorted list is `[2, 3, 9, 11, 16, 24]`, reversed to `[24, 16, 11, 9, 3, 2]`, and the first two are `24` and `16`.
    
    ANSWER: 24, 16
  • Trace a loopPassed

    506 tokens: 93 read, 413 written · 5 s · 76.4 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 % 8 == 0 or i % 2 == 0:
                total += i
        return total
    
    print(g(83))
    
    ANSWER: 1722
  • Find the bugPassed

    638 tokens: 119 read, 519 written · 7 s · 75.4 tok/s

    The function decimal_mean should return the mean of a non-empty list, as a decimal number. The code below has one bug. Find the line with the bug, and write that line corrected, exactly as it should read in the code. Work it out, then end with a line "ANSWER: <corrected line>".
    
    def decimal_mean(numbers):
        total = 0
        length = 0
        for num in numbers:
            total += num
            length += 1
        return total // length
    
    ANSWER: return total / length
  • Run a query in your headPassed

    633 tokens: 144 read, 489 written · 6 s · 81.9 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  | cal      | 65
    2  | ana      | 55
    3  | cal      | 30
    4  | ben      | 130
    5  | ben      | 85
    6  | ana      | 140
    
    Query:
    SELECT customer, SUM(amount) AS total
    FROM orders
    GROUP BY customer
    HAVING SUM(amount) > 100
    ORDER BY total DESC;
    
    ben,215
    ana,195
Using tools 5 of 5
  • Call one toolPassed

    640 tokens: 489 read, 151 written · 5 s · 33 tok/s

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

    428 tokens: 310 read, 118 written · 2 s · 57.1 tok/s

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

    902 tokens: 628 read, 274 written · 5 s · 55.1 tok/s

    Convert 100 GBP to USD and to JPY.
    1. user
      Convert 100 GBP to USD and to JPY.
    2. assistant
      
      I'll convert 100 GBP to both USD and JPY for you.
      
      
      convert_currency({"amount": 100, "from": "GBP", "to": "USD"})
      convert_currency({"amount": 100, "from": "GBP", "to": "JPY"})
    3. tool
      {"amount": 125.81, "currency": "USD"}
    4. tool
      {"amount": 18663, "currency": "JPY"}
    5. assistant
      
      100 GBP converts to:
      
      - **125.81 USD**
      - **18,663 JPY**
  • Chain two toolsPassed

    1,156 tokens: 920 read, 236 written · 6 s · 41.4 tok/s

    What is the status of each order for the customer with the email ruth.abara@example.com?
    1. user
      What is the status of each order for the customer with the email ruth.abara@example.com?
    2. assistant
      
      
      
      find_customer({"email": "ruth.abara@example.com"})
    3. tool
      {"customer_id": "C-3087", "name": "Ruth Abara"}
    4. assistant
      
      
      
      get_orders({"customer_id": "C-3087"})
    5. tool
      {"orders": [{"order_id": "A-79", "status": "delivered"}, {"order_id": "A-64", "status": "processing"}]}
    6. assistant
      
      For the customer Ruth Abara (email: ruth.abara@example.com), here are the order statuses:
      
      - **Order A-79**: delivered
      - **Order A-64**: processing
  • Handle a failed call honestlyPassed

    974 tokens: 589 read, 385 written · 6 s · 62.5 tok/s

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

    4,901 tokens: 192 read, 4,709 written · 54 s · 86.6 tok/s

    Build a one-page website for a bakery called "Flint Bakery". 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 Focaccia, Cinnamon bun, Pecan danish and Rye loaf; 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">
    <title>Flint Bakery</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        background-color: #fff;
        color: #333;
      }
      header {
        background-color: #f4c26b;
        padding: 1rem;
        text-align: center;
      }
      nav {
        background-color: #e6b87a;
        padding: 0.5rem;
      }
      nav a {
        margin: 0 1rem;
        color: #333;
        text-decoration: none;
      }
      main {
        padding: 1rem;
      }
      #menu ul {
        list-style: square;
        padding-left: 1.5rem;
      }
      footer {
        background-color: #f4c26b;
        padding: 1rem;
        text-align: center;
        position: fixed;
        bottom: 0;
        width: 100%;
      }
    </style>
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        console.log('Flint Bakery page loaded');
      });
    </script>
    </head>
    <body>
    <header>
      <h1>Flint Bakery</h1>
    </header>
    <nav>
      <a href="#home">Home</a>
      <a href="#menu">Menu</a>
      <a href="#contact">Contact</a>
    </nav>
    <main>
      <section id="menu">
        <ul>
          <li>Focaccia</li>
          <li>Cinnamon bun</li>
          <li>Pecan danish</li>
          <li>Rye loaf</li>
        </ul>
      </section>
    </main>
    <footer>
      <p>Opening Hours: Mon-Fri 7am-6pm, Sat 8am-4pm, Sun 9am-3pm</p>
    </footer>
    </body>
    </html>
  • A pricing table with a togglePassed

    7,885 tokens: 217 read, 7,668 written · 1 min 29 s · 86.2 tok/s

    Build a pricing page with three plans, in this order: Premium at $26 a month or $260 a year, Studio at $32 a month or $320 a year and Business at $51 a month or $510 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">
    <title>Pricing</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        padding: 20px;
      }
      #billing-toggle {
        padding: 10px 20px;
        margin-bottom: 20px;
        cursor: pointer;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
      }
      .plans {
        display: flex;
        gap: 20px;
      }
      .plan {
        border: 1px solid #ccc;
        padding: 20px;
        text-align: center;
        flex: 1;
      }
      .price {
        font-size: 24px;
        margin: 10px 0;
      }
    </style>
    </head>
    <body>
      <button id="billing-toggle">Toggle Billing</button>
      <div class="plans">
        <div class="plan">
          <h2>Premium</h2>
          <div class="price">$26 monthly</div>
        </div>
        <div class="plan">
          <h2>Studio</h2>
          <div class="price">$32 monthly</div>
        </div>
        <div class="plan">
          <h2>Business</h2>
          <div class="price">$51 monthly</div>
        </div>
      </div>
    <script>
      const toggle = document.getElementById('billing-toggle');
      let isYearly = false;
      toggle.addEventListener('click', () => {
        isYearly = !isYearly;
        const prices = document.querySelectorAll('.price');
        if (isYearly) {
          prices[0].textContent = '$260 yearly';
          prices[1].textContent = '$320 yearly';
          prices[2].textContent = '$510 yearly';
        } else {
          prices[0].textContent = '$26 monthly';
          prices[1].textContent = '$32 monthly';
          prices[2].textContent = '$51 monthly';
        }
      });
    </script>
    </body>
    </html>
  • An accessible sign-up formPassed

    4,771 tokens: 250 read, 4,521 written · 52 s · 86.7 tok/s

    Build a sign-up form for Quill Press. 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">
    <title>Quill Press Sign-up</title>
    <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    h1 { color: #333; }
    form { margin-top: 10px; }
    label { display: block; margin-top: 8px; }
    input[type="text"], input[type="email"], input[type="password"] { width: 100%; padding: 8px; box-sizing: border-box; }
    button { margin-top: 12px; padding: 10px 20px; }
    #status { margin-top: 12px; color: #d00; }
    </style>
    </head>
    <body>
    <h1>Quill Press</h1>
    <form id="signup" novalidate>
      <label for="name">Name</label>
      <input type="text" id="name" name="name" required>
    
      <label for="email">Email</label>
      <input type="email" id="email" name="email">
    
      <label for="password">Password</label>
      <input type="password" id="password" name="password" minlength="8">
    
      <button type="submit">Sign Up</button>
    </form>
    <div id="status" role="status"></div>
    
    <script>
    document.getElementById('signup').addEventListener('submit', function(e) {
      e.preventDefault();
      const email = document.getElementById('email').value.trim();
      const password = document.getElementById('password').value;
      const status = document.getElementById('status');
      status.textContent = '';
    
      const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
      const passwordValid = password.length >= 8;
    
      if (!emailValid || !passwordValid) {
        let msg = '';
        if (!emailValid) msg += 'Invalid email address. ';
        if (!passwordValid) msg += 'Password must be at least 8 characters.';
        status.textContent = msg.trim();
      }
      // if valid, status remains empty
    });
    </script>
    </body>
    </html>
  • A to-do app that remembersPassed

    2,754 tokens: 181 read, 2,573 written · 29 s · 88.1 tok/s

    Build a to-do list app called "Kitchen tasks". 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">
    <title>Kitchen tasks</title>
    <style>
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
    }
    h1 {
      color: #333;
    }
    #new-task {
      width: 200px;
      padding: 5px;
    }
    #add {
      padding: 5px 10px;
      margin-left: 5px;
    }
    ul {
      list-style: none;
      padding: 0;
      margin-top: 10px;
    }
    li {
      margin: 5px 0;
      padding: 5px;
      background: #f9f9f9;
      border: 1px solid #ddd;
      border-radius: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    li button {
      background: #e74c3c;
      color: white;
      border: none;
      padding: 3px 8px;
      border-radius: 4px;
      cursor: pointer;
    }
    li button:hover {
      background: #c0392b;
    }
    </style>
    </head>
    <body>
    <h1>Kitchen tasks</h1>
    <input id="new-task" type="text" placeholder="Enter task">
    <button id="add">Add</button>
    <ul id="tasks"></ul>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
      const input = document.getElementById('new-task');
      const addBtn = document.getElementById('add');
      const ul = document.getElementById('tasks');
    
      function loadTasks() {
        const tasks = JSON.parse(localStorage.getItem('todos') || '[]');
        tasks.forEach(addTask);
      }
    
      function addTask(text) {
        const li = document.createElement('li');
        li.textContent = text;
        const removeBtn = document.createElement('button');
        removeBtn.textContent = 'Remove';
        removeBtn.addEventListener('click', function() {
          ul.removeChild(li);
          saveTasks();
        });
        li.appendChild(removeBtn);
        ul.appendChild(li);
      }
    
      function saveTasks() {
        const tasks = Array.from(ul.children).map(li => li.firstChild.textContent);
        localStorage.setItem('todos', JSON.stringify(tasks));
      }
    
      addBtn.addEventListener('click', function() {
        const text = input.value.trim();
        if (text) {
          addTask(text);
          input.value = '';
          saveTasks();
        }
      });
    
      input.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
          addBtn.click();
        }
      });
    
      loadTasks();
    });
    </script>
    </body>
    </html>
  • A bar chart in SVGPassed

    4,670 tokens: 234 read, 4,436 written · 53 s · 84.4 tok/s

    Draw an inline SVG bar chart of lattes sold, in this order: Tue 23, Wed 37, Thu 7, Fri 41 and Sat 3. 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>Lattes Sold</title>
    <style>
      .bar { fill: #4caf50; }
    </style>
    </head>
    <body>
    <svg width="500" height="300" aria-label="Bar chart of lattes sold">
      <title>Lattes sold</title>
      <rect class="bar" x="40" y="135" width="60" height="115"/>
      <rect class="bar" x="120" y="65" width="60" height="185"/>
      <rect class="bar" x="200" y="215" width="60" height="35"/>
      <rect class="bar" x="280" y="45" width="60" height="205"/>
      <rect class="bar" x="360" y="235" width="60" height="15"/>
      <text x="70" y="270" text-anchor="middle">Tue</text>
      <text x="150" y="270" text-anchor="middle">Wed</text>
      <text x="230" y="270" text-anchor="middle">Thu</text>
      <text x="310" y="270" text-anchor="middle">Fri</text>
      <text x="390" y="270" text-anchor="middle">Sat</text>
    </svg>
    </body>
    </html>
Building games 2 of 4
  • Build 2048Failed

    10,160 tokens: 451 read, 9,709 written · 1 min 45 s · 92.1 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.
    [0, 0, 0, 8]
    [2, 0, 0, 8]
    [0, 0, 0, 16]
    [2, 16, 0, 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.0">
    <title>2048</title>
    <style>
      body {
        font-family: sans-serif;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100vh;
        margin: 0;
        background-color: #faf8ef;
      }
      #score-container {
        margin-bottom: 10px;
        font-size: 24px;
        font-weight: bold;
      }
      #grid {
        display: grid;
        grid-template-columns: repeat(4, 100px);
        grid-template-rows: repeat(4, 100px);
        gap: 10px;
      }
      .cell {
        background-color: #cdc1b4;
        border-radius: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32px;
        font-weight: bold;
        color: #7c6f66;
      }
      .tile {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 5px;
        transition: transform 0.1s ease;
      }
      .tile-2 { background-color: #eee4da; color: #7c6f66; }
      .tile-4 { background-color: #ede0c8; color: #7c6f66; }
      .tile-8 { background-color: #f2b179; color: #fff; }
      .tile-16 { background-color: #f59563; color: #fff; }
      .tile-32 { background-color: #f67c5f; color: #fff; }
      .tile-64 { background-color: #f65e3b; color: #fff; }
      .tile-128 { background-color: #f1c74c; color: #fff; }
      .tile-256 { background-color: #f1b93c; color: #fff; }
      .tile-512 { background-color: #f1a92c; color: #fff; }
      .tile-1024 { background-color: #f1a022; color: #fff; }
      .tile-2048 { background-color: #f19a17; color: #fff; }
    </style>
    </head>
    <body>
      <div id="score-container">Score: <span id="score">0</span></div>
      <div id="grid"></div>
    
      <script id="game">
        function createGame() {
          // Initial board as specified
          let board = [
            [0, 0, 0, 8],
            [2, 0, 0, 8],
            [0, 0, 0, 16],
            [2, 16, 0, 32]
          ];
          let score = 0;
          let over = false;
    
          // Place two 2's in the first two empty cells (reading order)
          function placeTwo() {
            let placed = 0;
            for (let r = 0; r < 4 && placed < 2; r++) {
              for (let c = 0; c < 4 && placed < 2; c++) {
                if (board[r][c] === 0) {
                  board[r][c] = 2;
                  placed++;
                }
              }
            }
          }
          placeTwo();
    
          // Process a line (row or column) for merging
          function processLine(line) {
            const nonZero = line.filter(v => v !== 0);
            const merged = [];
            let scoreGain = 0;
            let i = 0;
            while (i < nonZero.length) {
              if (i + 1 < nonZero.length && nonZero[i] === nonZero[i + 1]) {
                const newVal = nonZero[i] * 2;
                merged.push(newVal);
                scoreGain += newVal;
                i += 2;
              } else {
                merged.push(nonZero[i]);
                i++;
              }
            }
            while (merged.length < 4) merged.push(0);
            return { result: merged, score: scoreGain };
          }
    
          // Compare two arrays
          function arraysEqual(a, b) {
            for (let i = 0; i < a.length; i++) {
              if (a[i] !== b[i]) return false;
            }
            return true;
          }
    
          // Check if any move is possible
          function isGameOver() {
            // Check for empty cells
            for (let r = 0; r < 4; r++) {
              for (let c = 0; c < 4; c++) {
                if (board[r][c] === 0) return false;
              }
            }
            // Check horizontal adjacent equal tiles
            for (let r = 0; r < 4; r++) {
              for (let c = 0; c < 3; c++) {
                if (board[r][c] === board[r][c + 1]) return false;
              }
            }
            // Check vertical adjacent equal tiles
            for (let c = 0; c < 4; c++) {
              for (let r = 0; r < 3; r++) {
                if (board[r][c] === board[r + 1][c]) return false;
              }
            }
            return true;
          }
    
          // Move tiles in given direction
          function move(dir) {
            if (over) return;
            let newBoard = board.map(row => row.slice());
            let totalScore = 0;
            let changed = false;
    
            if (dir === 'left') {
              for (let r = 0; r < 4; r++) {
                const row = board[r];
                const { result, score } = processLine(row);
                totalScore += score;
                if (!arraysEqual(row, result)) changed = true;
                newBoard[r] = result;
              }
            } else if (dir === 'right') {
              for (let r = 0; r < 4; r++) {
                const row = board[r].slice();
                const reversed = row.reverse();
                const { result, score } = processLine(reversed);
                result.reverse();
                totalScore += score;
                if (!arraysEqual(row, result)) changed = true;
                newBoard[r] = result;
              }
            } else if (dir === 'up') {
              for (let c = 0; c < 4; c++) {
                const col = [board[0][c], board[1][c], board[2][c], board[3][c]];
                const { result, score } = processLine(col);
                totalScore += score;
                for (let r = 0; r < 4; r++) {
                  if (board[r][c] !== result[r]) changed = true;
                  newBoard[r][c] = result[r];
                }
              }
            } else if (dir === 'down') {
              for (let c = 0; c < 4; c++) {
                const col = [board[0][c], board[1][c], board[2][c], board[3][c]];
                const reversed = col.reverse();
                const { result, score } = processLine(reversed);
                result.reverse();
                totalScore += score;
                for (let r = 0; r < 4; r++) {
                  if (board[r][c] !== result[r]) changed = true;
                  newBoard[r][c] = result[r];
                }
              }
            }
    
            if (!changed) return;
            board = newBoard;
            score += totalScore;
            placeTwo();
            over = isGameOver();
          }
    
          // Return current state
          function state() {
            return {
              board: board.map(row => row.slice()),
              score: score,
              over: over
            };
          }
    
          return { move, state };
        }
      </script>
    
      <script>
        const game = createGame();
        const grid = document.getElementById('grid');
        const scoreDisplay = document.getElementById('score');
    
        // Create 4x4 grid cells
        const cells = [];
        for (let r = 0; r < 4; r++) {
          cells[r] = [];
          for (let c = 0; c < 4; c++) {
            const cell = document.createElement('div');
            cell.className = 'cell';
            grid.appendChild(cell);
            cells[r][c] = cell;
          }
        }
    
        // Render the board
        function render() {
          const state = game.state();
          scoreDisplay.textContent = state.score;
          for (let r = 0; r < 4; r++) {
            for (let c = 0; c < 4; c++) {
              const cell = cells[r][c];
              cell.innerHTML = '';
              const val = state.board[r][c];
              if (val !== 0) {
                const tile = document.createElement('div');
                tile.className = 'tile tile-' + val;
                tile.textContent = val;
                cell.appendChild(tile);
              }
            }
          }
        }
    
        // Initial render
        render();
    
        // Handle keyboard input
        document.addEventListener('keydown', function(e) {
          if (e.key === 'ArrowUp') {
            e.preventDefault();
            game.move('up');
          } else if (e.key === 'ArrowDown') {
            e.preventDefault();
            game.move('down');
          } else if (e.key === 'ArrowLeft') {
            e.preventDefault();
            game.move('left');
          } else if (e.key === 'ArrowRight') {
            e.preventDefault();
            game.move('right');
          }
          render();
        });
      </script>
    </body>
    </html>
  • Build SnakeFailed

    9,502 tokens: 450 read, 9,052 written · 1 min 49 s · 82.8 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 [[4, 4], [4, 5], [4, 6]], moving up, food at [8, 0], 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">
    <title>Snake</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 20px;
        background-color: #f5f5f5;
      }
      #grid {
        display: grid;
        grid-template-columns: repeat(10, 30px);
        grid-template-rows: repeat(10, 30px);
        gap: 1px;
        margin-bottom: 10px;
      }
      .cell {
        width: 30px;
        height: 30px;
        background-color: #e0e0e0;
        border: 1px solid #ccc;
        box-sizing: border-box;
      }
      .snake {
        background-color: green;
      }
      .head {
        background-color: darkgreen;
      }
      .food {
        background-color: red;
      }
      #score {
        font-size: 18px;
        margin-bottom: 5px;
      }
      #over {
        color: red;
        font-size: 20px;
        font-weight: bold;
      }
    </style>
    </head>
    <body>
      <div id="grid"></div>
      <div id="score">Score: 0</div>
      <div id="over"></div>
    
      <script id="game">
        function createGame() {
          let snake = [[4, 4], [4, 5], [4, 6]];
          let direction = 'up';
          let food = [8, 0];
          let score = 0;
          let over = false;
    
          const opposites = { up: 'down', down: 'up', left: 'right', right: 'left' };
    
          function step(dir) {
            if (over) return;
    
            // Ignore opposite direction
            if (dir !== opposites[direction]) {
              direction = dir;
            }
    
            const head = snake[0];
            let newHead;
            switch (direction) {
              case 'up':    newHead = [head[0], head[1] - 1]; break;
              case 'down':  newHead = [head[0], head[1] + 1]; break;
              case 'left':  newHead = [head[0] - 1, head[1]]; break;
              case 'right': newHead = [head[0] + 1, head[1]]; break;
            }
    
            const ate = newHead[0] === food[0] && newHead[1] === food[1];
            const newSnake = [newHead, ...snake];
            if (!ate) {
              newSnake.pop();
            }
    
            // Collision detection
            let collision = false;
            if (newHead[0] < 0 || newHead[0] > 9 || newHead[1] < 0 || newHead[1] > 9) {
              collision = true;
            } else {
              for (let i = 1; i < newSnake.length; i++) {
                if (newSnake[i][0] === newHead[0] && newSnake[i][1] === newHead[1]) {
                  collision = true;
                  break;
                }
              }
            }
    
            if (collision) {
              over = true;
              snake = newSnake;
              return;
            }
    
            snake = newSnake;
    
            if (ate) {
              score += 1;
              // Place new food
              const cells = [];
              for (let y = 0; y < 10; y++) {
                for (let x = 0; x < 10; x++) {
                  cells.push([x, y]);
                }
              }
              const idx = cells.findIndex(c => c[0] === newHead[0] && c[1] === newHead[1]);
              for (let i = 1; i <= cells.length; i++) {
                const candidate = cells[(idx + i) % cells.length];
                const occupied = snake.some(s => s[0] === candidate[0] && s[1] === candidate[1]);
                if (!occupied) {
                  food = candidate;
                  break;
                }
              }
            }
          }
    
          function state() {
            return {
              snake: snake.map(s => [s[0], s[1]]),
              food: [food[0], food[1]],
              score,
              over
            };
          }
    
          return { step, state };
        }
      </script>
    
      <script>
        const game = createGame();
        const gridEl = document.getElementById('grid');
        const scoreEl = document.getElementById('score');
        const overEl = document.getElementById('over');
    
        function drawGrid() {
          gridEl.innerHTML = '';
          const state = game.state();
          for (let y = 0; y < 10; y++) {
            for (let x = 0; x < 10; x++) {
              const cell = document.createElement('div');
              cell.className = 'cell';
              const head = state.snake[0];
              if (head && head[0] === x && head[1] === y) {
                cell.classList.add('head');
              } else if (state.snake.some(s => s[0] === x && s[1] === y)) {
                cell.classList.add('snake');
              } else if (state.food[0] === x && state.food[1] === y) {
                cell.classList.add('food');
              }
              gridEl.appendChild(cell);
            }
          }
          scoreEl.textContent = 'Score: ' + state.score;
          overEl.textContent = state.over ? 'Game Over' : '';
        }
    
        document.addEventListener('keydown', (e) => {
          let dir = null;
          if (e.key === 'ArrowUp') dir = 'up';
          else if (e.key === 'ArrowDown') dir = 'down';
          else if (e.key === 'ArrowLeft') dir = 'left';
          else if (e.key === 'ArrowRight') dir = 'right';
          if (dir) {
            game.step(dir);
            drawGrid();
            e.preventDefault();
          }
        });
    
        drawGrid();
      </script>
    </body>
    </html>
  • Box-pushing puzzlePassed

    11,324 tokens: 1,112 read, 10,212 written · 1 min 50 s · 92.6 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
    
    ```html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Box-pushing puzzle</title>
    <style>
      body {
        background: #f0f0f0;
        font-family: sans-serif;
        margin: 1em;
      }
      h1 {
        margin-bottom: 0.5em;
      }
      #board {
        display: grid;
        grid-template-columns: repeat(8, 2.5em);
        grid-template-rows: repeat(7, 2.5em);
        gap: 2px;
        margin-bottom: 1em;
      }
      .cell {
        width: 2.5em;
        height: 2.5em;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: monospace;
        font-size: 1.5em;
        border: 1px solid #ccc;
        background: #fff;
        text-align: center;
      }
      .wall {
        background: #333;
        color: #fff;
      }
      .goal {
        border: 2px solid gold;
      }
      .player {
        color: blue;
        font-weight: bold;
      }
      .box {
        color: brown;
        font-weight: bold;
      }
      #steps, #pushes {
        font-weight: bold;
      }
      #status {
        margin-top: 0.5em;
        font-weight: bold;
      }
      #controls {
        margin-top: 1em;
      }
      button {
        width: 4em;
        height: 2em;
        margin: 2px;
        font-size: 1em;
      }
    </style>
    </head>
    <body>
      <h1>Box-pushing puzzle</h1>
      <div id="board"></div>
      <p>Steps: <span id="steps">0</span></p>
      <p>Pushes: <span id="pushes">0</span></p>
      <p id="status">Not solved yet</p>
      <div id="controls">
        <button data-dir="up">Up</button>
        <br>
        <button data-dir="left">Left</button>
        <button data-dir="down">Down</button>
        <button data-dir="right">Right</button>
        <br>
        <button id="restart">Restart</button>
      </div>
    
      <script id="game">
        function createGame() {
          const MAP = [
            "########",
            "#     .#",
            "# $  * #",
            "#+   # #",
            "# $ #  #",
            "#      #",
            "########"
          ];
          const walls = new Set();
          const goals = new Set();
          let playerX, playerY;
          const boxes = [];
          for (let y = 0; y < MAP.length; y++) {
            const row = MAP[y];
            for (let x = 0; x < row.length; x++) {
              const ch = row[x];
              if (ch === '#') walls.add(x + ',' + y);
              else if (ch === '.') goals.add(x + ',' + y);
              else if (ch === '+') { goals.add(x + ',' + y); playerX = x; playerY = y; }
              else if (ch === '*') { goals.add(x + ',' + y); boxes.push([x, y]); }
              else if (ch === '$') boxes.push([x, y]);
              else if (ch === '@') { playerX = x; playerY = y; }
            }
          }
          let steps = 0, pushes = 0;
          let solved = false;
          function isWall(x, y) { return walls.has(x + ',' + y); }
          function isBox(x, y) { return boxes.some(b => b[0] === x && b[1] === y); }
          function isGoal(x, y) { return goals.has(x + ',' + y); }
          function walk(dir) {
            if (solved) return;
            const dx = { up: 0, down: 0, left: -1, right: 1 }[dir];
            const dy = { up: -1, down: 1, left: 0, right: 0 }[dir];
            const nx = playerX + dx, ny = playerY + dy;
            if (isWall(nx, ny)) return;
            if (isBox(nx, ny)) {
              const beyondX = nx + dx, beyondY = ny + dy;
              if (isWall(beyondX, beyondY) || isBox(beyondX, beyondY)) return;
              const idx = boxes.findIndex(b => b[0] === nx && b[1] === ny);
              boxes[idx] = [beyondX, beyondY];
              playerX = nx; playerY = ny;
              pushes++;
              steps++;
            } else {
              playerX = nx; playerY = ny;
              steps++;
            }
            if (boxes.every(b => isGoal(b[0], b[1]))) solved = true;
          }
          return {
            walk,
            state() {
              const sortedBoxes = boxes.slice().sort((a, b) => a[1] - b[1] || a[0] - b[0]);
              return {
                player: [playerX, playerY],
                boxes: sortedBoxes,
                pushes,
                steps,
                solved
              };
            }
          };
        }
      </script>
    
      <script>
        (function() {
          let game = createGame();
          const boardEl = document.getElementById('board');
          const stepsEl = document.getElementById('steps');
          const pushesEl = document.getElementById('pushes');
          const statusEl = document.getElementById('status');
          const LEVEL = [
            "########",
            "#     .#",
            "# $  * #",
            "#+   # #",
            "# $ #  #",
            "#      #",
            "########"
          ];
          // Precompute static cell types
          const cellTypes = [];
          for (let y = 0; y < 7; y++) {
            for (let x = 0; x < 8; x++) {
              const ch = LEVEL[y][x];
              let type = 'floor';
              if (ch === '#') type = 'wall';
              else if (ch === '.' || ch === '+' || ch === '*') type = 'goal';
              cellTypes.push(type);
            }
          }
          // Create cells
          const cells = [];
          for (let i = 0; i < 56; i++) {
            const cell = document.createElement('div');
            cell.className = 'cell';
            cell.setAttribute('role', 'img');
            boardEl.appendChild(cell);
            cells.push(cell);
          }
          // Update function
          function update() {
            const state = game.state();
            for (let y = 0; y < 7; y++) {
              for (let x = 0; x < 8; x++) {
                const idx = y * 8 + x;
                const cell = cells[idx];
                const type = cellTypes[idx];
                let char = '';
                let label = '';
                const isPlayer = state.player[0] === x && state.player[1] === y;
                const boxIdx = state.boxes.findIndex(b => b[0] === x && b[1] === y);
                const isBox = boxIdx !== -1;
                const isGoal = type === 'goal';
                if (type === 'wall') {
                  char = '#';
                  label = 'wall';
                } else if (isPlayer && isGoal) {
                  char = '+';
                  label = 'you on a goal';
                } else if (isPlayer) {
                  char = '@';
                  label = 'you';
                } else if (isBox && isGoal) {
                  char = '*';
                  label = 'box on a goal';
                } else if (isBox) {
                  char = '$';
                  label = 'box';
                } else if (isGoal) {
                  char = '.';
                  label = 'empty goal';
                } else {
                  char = ' ';
                  label = 'empty floor';
                }
                cell.textContent = char;
                cell.setAttribute('aria-label', label);
                cell.className = 'cell ' + type;
                if (isPlayer) cell.classList.add('player');
                if (isBox) cell.classList.add('box');
              }
            }
            stepsEl.textContent = state.steps;
            pushesEl.textContent = state.pushes;
            if (state.solved) {
              statusEl.textContent = `Solved in ${state.steps} steps with ${state.pushes} pushes`;
            } else {
              statusEl.textContent = 'Not solved yet';
            }
          }
          // Buttons
          document.querySelectorAll('button[data-dir]').forEach(btn => {
            btn.addEventListener('click', () => {
              game.walk(btn.dataset.dir);
              setTimeout(update, 100);
            });
          });
          document.getElementById('restart').addEventListener('click', () => {
            game = createGame();
            setTimeout(update, 100);
          });
          // Arrow keys
          document.addEventListener('keydown', (e) => {
            if (e.repeat) return;
            let dir;
            switch (e.key) {
              case 'ArrowUp': dir = 'up'; break;
              case 'ArrowDown': dir = 'down'; break;
              case 'ArrowLeft': dir = 'left'; break;
              case 'ArrowRight': dir = 'right'; break;
              default: return;
            }
            e.preventDefault();
            game.walk(dir);
            setTimeout(update, 100);
          });
          // Initial render
          update();
        })();
      </script>
    </body>
    </html>
    ```
  • MinesweeperPassed

    15,864 tokens: 1,410 read, 14,454 written · 2 min 30 s · 96.6 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>
      body {
        font-family: system-ui, sans-serif;
        background-color: #f7f3e9;
        margin: 0;
        padding: 1rem;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      .panel {
        background-color: white;
        border-radius: 8px;
        padding: 1rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        max-width: 360px;
        width: 100%;
        box-sizing: border-box;
      }
      #status {
        margin-bottom: 0.5rem;
        font-size: 1.1rem;
      }
      #flag-mode {
        margin-bottom: 0.5rem;
        padding: 0.5rem 1rem;
        border: 1px solid #ccc;
        border-radius: 4px;
        background-color: #f0f0f0;
        cursor: pointer;
        font-size: 1rem;
      }
      #flag-mode.on {
        background-color: pink;
        border-color: pink;
      }
      #board {
        display: block;
        width: 100%;
        height: auto;
        max-width: 324px;
        margin: 0 auto;
        border: 1px solid #ccc;
      }
    </style>
    </head>
    <body>
      <h1>Minesweeper</h1>
      <p>Click to open a cell. Right-click to flag a cell. Use Flag mode button to flag with left-click. Win by opening all safe cells. Avoid mines.</p>
      <div class="panel">
        <div id="status" role="status"></div>
        <button id="flag-mode">Flag mode: off</button>
        <canvas id="board" width="324" height="324"></canvas>
      </div>
    
      <script id="game">
    function createGame() {
      const rows = 9, cols = 9;
      const minePositions = [
        [false,false,false,false,true,false,false,false,true],
        [false,false,false,false,false,true,false,false,false],
        [false,true,false,false,false,true,false,true,false],
        [false,false,false,false,false,false,false,false,false],
        [false,false,false,true,false,false,false,false,false],
        [false,false,false,false,true,false,false,false,false],
        [false,false,false,false,true,false,false,false,false],
        [false,false,false,false,false,false,false,false,false],
        [false,false,false,false,false,false,false,false,true]
      ];
    
      // Build grid
      let grid = [];
      for (let r = 0; r < rows; r++) {
        grid[r] = [];
        for (let c = 0; c < cols; c++) {
          grid[r].push({
            isMine: minePositions[r][c],
            isOpen: false,
            isFlagged: false,
            adjacent: 0
          });
        }
      }
    
      // Compute adjacent mine counts
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
          if (!grid[r][c].isMine) {
            let count = 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, nc = c + dc;
                if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc].isMine) {
                  count++;
                }
              }
            }
            grid[r][c].adjacent = count;
          }
        }
      }
    
      let status = "playing";
      let flaggedCount = 0;
    
      function openCell(r, c) {
        const cell = grid[r][c];
        if (cell.isOpen || cell.isFlagged) return;
        if (cell.isMine) {
          status = "lost";
          return;
        }
        cell.isOpen = true;
        if (cell.adjacent === 0) {
          let stack = [[r, c]];
          while (stack.length) {
            const [cr, cc] = stack.pop();
            for (let dr = -1; dr <= 1; dr++) {
              for (let dc = -1; dc <= 1; dc++) {
                if (dr === 0 && dc === 0) continue;
                const nr = cr + dr, nc = cc + dc;
                if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) {
                  const neighbor = grid[nr][nc];
                  if (!neighbor.isOpen && !neighbor.isFlagged) {
                    neighbor.isOpen = true;
                    if (neighbor.adjacent === 0) {
                      stack.push([nr, nc]);
                    }
                  }
                }
              }
            }
          }
        }
        // Check win
        let allSafeOpen = true;
        for (let r = 0; r < rows; r++) {
          for (let c = 0; c < cols; c++) {
            if (!grid[r][c].isMine && !grid[r][c].isOpen) {
              allSafeOpen = false;
              break;
            }
          }
          if (!allSafeOpen) break;
        }
        if (allSafeOpen) {
          status = "won";
          for (let r = 0; r < rows; r++) {
            for (let c = 0; c < cols; c++) {
              if (grid[r][c].isMine) {
                grid[r][c].isFlagged = true;
              }
            }
          }
          flaggedCount = 10;
        }
      }
    
      function press(move) {
        if (status !== "playing") return;
        const [kind, r, c] = move;
        if (kind === "open") {
          openCell(r, c);
        } else if (kind === "flag") {
          const cell = grid[r][c];
          if (cell.isOpen) return;
          if (cell.isFlagged) {
            cell.isFlagged = false;
            flaggedCount--;
          } else {
            cell.isFlagged = true;
            flaggedCount++;
          }
        }
      }
    
      function state() {
        let cells = [];
        for (let r = 0; r < rows; r++) {
          let rowStr = "";
          for (let c = 0; c < cols; c++) {
            const cell = grid[r][c];
            if (status === "lost" && cell.isMine) {
              rowStr += "*";
            } else if (status === "won" && cell.isMine) {
              rowStr += "F";
            } else if (cell.isFlagged) {
              rowStr += "F";
            } else if (cell.isOpen) {
              if (cell.isMine) {
                rowStr += "*";
              } else if (cell.adjacent === 0) {
                rowStr += ".";
              } else {
                rowStr += cell.adjacent.toString();
              }
            } else {
              rowStr += "#";
            }
          }
          cells.push(rowStr);
        }
        const mines_left = 10 - flaggedCount;
        return { cells: cells, status: status, mines_left: mines_left };
      }
    
      return { press, state };
    }
      </script>
    
      <script>
        const game = createGame();
        const statusEl = document.getElementById('status');
        const flagModeBtn = document.getElementById('flag-mode');
        const canvas = document.getElementById('board');
        const ctx = canvas.getContext('2d');
    
        let flagMode = false;
    
        function update() {
          const s = game.state();
          let statusWord;
          if (s.status === 'playing') statusWord = 'Playing';
          else if (s.status === 'won') statusWord = 'Won';
          else statusWord = 'Lost';
          
          statusEl.textContent = `Mines left ${s.mines_left} ${statusWord}`;
          statusEl.style.color = '';
          if (s.status === 'won') statusEl.style.color = 'green';
          else if (s.status === 'lost') statusEl.style.color = 'red';
    
          flagModeBtn.textContent = `Flag mode: ${flagMode ? 'on' : 'off'}`;
          flagModeBtn.classList.toggle('on', flagMode);
          flagModeBtn.setAttribute('aria-pressed', flagMode);
    
          drawBoard(s.cells);
        }
    
        function drawBoard(cells) {
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.font = "30px system-ui, sans-serif";
          ctx.textAlign = "center";
          ctx.textBaseline = "middle";
          for (let r = 0; r < 9; r++) {
            for (let c = 0; c < 9; c++) {
              const ch = cells[r][c];
              if (ch !== '#' && ch !== '.') {
                let color;
                if (ch === 'F') color = 'pink';
                else if (ch === '*') color = 'red';
                else if (ch >= '1' && ch <= '8') color = 'blue';
                else color = 'black';
                ctx.fillStyle = color;
                const x = c * 36 + 18;
                const y = r * 36 + 18;
                ctx.fillText(ch, x, y);
              }
            }
          }
        }
    
        function getCellFromEvent(e) {
          const rect = canvas.getBoundingClientRect();
          const x = (e.clientX - rect.left) * canvas.width / rect.width;
          const y = (e.clientY - rect.top) * canvas.height / rect.height;
          const col = Math.floor(x / 36);
          const row = Math.floor(y / 36);
          if (row >= 0 && row < 9 && col >= 0 && col < 9) {
            return [row, col];
          }
          return null;
        }
    
        canvas.addEventListener('click', (e) => {
          const cell = getCellFromEvent(e);
          if (!cell) return;
          const [row, col] = cell;
          if (flagMode) {
            game.press(['flag', row, col]);
          } else {
            game.press(['open', row, col]);
          }
          update();
        });
    
        canvas.addEventListener('contextmenu', (e) => {
          e.preventDefault();
          const cell = getCellFromEvent(e);
          if (!cell) return;
          const [row, col] = cell;
          game.press(['flag', row, col]);
          update();
        });
    
        flagModeBtn.addEventListener('click', () => {
          flagMode = !flagMode;
          update();
        });
    
        update();
      </script>
    </body>
    </html>
Building apps 2 of 4
  • Step sequencerFailed

    18,629 tokens: 1,305 read, 17,324 written · 3 min 0 s · 96.3 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   1000100010000000
    snare  0000100101001000
    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>
      body {
        background: #f5f5f5;
        color: #222;
        font-family: sans-serif;
        margin: 0;
        padding: 20px;
        overflow-x: hidden;
      }
      .container {
        max-width: 1280px;
        margin: 0 auto;
      }
      .numbers {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        margin-bottom: 10px;
      }
      .number {
        flex: 0 0 6.25%;
        text-align: center;
        font-size: 14px;
        box-sizing: border-box;
      }
      .playhead-num {
        color: #b31f57;
      }
      .grid {
        display: flex;
        flex-direction: column;
        gap: 10px;
      }
      .track {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
      }
      .label {
        width: 60px;
        text-align: right;
        font-weight: bold;
        flex-shrink: 0;
      }
      .step {
        flex: 1 0 6.25%;
        height: 40px;
        background: #fff;
        border: 1px solid #999;
        border-radius: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;
        font-size: 0;
        position: relative;
      }
      .step .num {
        font-size: 14px;
        color: #222;
        display: none;
      }
      .step.on {
        background: #222;
      }
      .step.playhead {
        outline: 2px solid #b31f57;
      }
      .controls {
        margin: 20px 0;
      }
      #play, #stop {
        padding: 10px 20px;
        font-size: 16px;
        border: none;
        border-radius: 0;
        margin-right: 10px;
        cursor: pointer;
      }
      #play {
        background: #b31f57;
        color: #fff;
      }
      #stop {
        background: #999;
        color: #fff;
      }
      #status {
        height: 20px;
        margin-top: 10px;
        font-size: 16px;
      }
      #announce {
        display: block;
        height: 20px;
        margin-top: 5px;
        font-size: 16px;
      }
      @media (max-width: 719px) {
        .number {
          flex: 0 0 12.5%;
        }
        .step {
          flex: 0 0 12.5%;
        }
        .step .num {
          display: block;
        }
      }
    </style>
    </head>
    <body>
    <div class="container">
      <div class="numbers" id="numbers"></div>
      <div class="grid" id="grid"></div>
      <div class="controls">
        <button id="play">Play</button>
        <button id="stop">Stop</button>
      </div>
      <div id="status" class="status"></div>
      <span id="announce" aria-live="polite"></span>
    </div>
    
    <script id="game">
    function createGame() {
      const pattern = [
        "1000100010000000",
        "0000100101001000",
        "1011101010111010"
      ];
      let playing = false;
      let playhead = 0;
      let hits = [];
    
      function press(cmd) {
        if (cmd === 'play') {
          if (playing) return;
          playing = true;
          hits = [];
          for (let t = 0; t < 3; t++) {
            if (pattern[t][playhead] === '1') hits.push(t);
          }
        } else if (cmd === 'stop') {
          playing = false;
          playhead = 0;
          hits = [];
        } else if (cmd === 'tick') {
          if (!playing) return;
          playhead = (playhead + 1) % 16;
          hits = [];
          for (let t = 0; t < 3; t++) {
            if (pattern[t][playhead] === '1') hits.push(t);
          }
        } else if (Array.isArray(cmd) && cmd.length === 2 &&
                   typeof cmd[0] === 'number' && Number.isInteger(cmd[0]) && cmd[0] >= 0 && cmd[0] <= 2 &&
                   typeof cmd[1] === 'number' && Number.isInteger(cmd[1]) && cmd[1] >= 0 && cmd[1] <= 15) {
          const track = cmd[0];
          const step = cmd[1];
          const row = pattern[track];
          const char = row[step];
          const newChar = char === '1' ? '0' : '1';
          pattern[track] = row.slice(0, step) + newChar + row.slice(step + 1);
        }
      }
    
      function state() {
        return {
          playing: playing,
          playhead: playhead,
          hits: hits.slice(),
          pattern: pattern.slice()
        };
      }
    
      return { press, state };
    }
    </script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
      const game = createGame();
    
      // Audio
      let audioContext = null;
      let masterGain = null;
      let snareNoiseBuffer = null;
      let hatNoiseBuffer = null;
      let audioReady = false;
    
      function ensureAudio() {
        if (audioReady) return;
        audioContext = new (window.AudioContext || window.webkitAudioContext)();
        masterGain = audioContext.createGain();
        masterGain.gain.value = 0.5;
        masterGain.connect(audioContext.destination);
        audioReady = true;
        if (audioContext.state === 'suspended') {
          audioContext.resume();
        }
      }
    
      function createNoiseBuffer(duration) {
        const length = audioContext.sampleRate * duration;
        const buffer = audioContext.createBuffer(1, length, audioContext.sampleRate);
        const data = buffer.getChannelData(0);
        for (let i = 0; i < length; i++) {
          data[i] = Math.random() * 2 - 1;
        }
        return buffer;
      }
    
      function playKick(time) {
        const osc = audioContext.createOscillator();
        const gain = audioContext.createGain();
        osc.type = 'sine';
        osc.frequency.setValueAtTime(150, time);
        osc.frequency.exponentialRampToValueAtTime(50, time + 0.1);
        gain.gain.setValueAtTime(1, time);
        gain.gain.exponentialRampToValueAtTime(0.01, time + 0.1);
        osc.connect(gain);
        gain.connect(masterGain);
        osc.start(time);
        osc.stop(time + 0.1);
      }
    
      function playSnare(time) {
        if (!snareNoiseBuffer) {
          snareNoiseBuffer = createNoiseBuffer(0.2);
        }
        const noiseSrc = audioContext.createBufferSource();
        noiseSrc.buffer = snareNoiseBuffer;
        const noiseGain = audioContext.createGain();
        noiseGain.gain.setValueAtTime(0.5, time);
        noiseGain.gain.exponentialRampToValueAtTime(0.01, time + 0.2);
        noiseSrc.connect(noiseGain);
        noiseGain.connect(masterGain);
        noiseSrc.start(time);
        noiseSrc.stop(time + 0.2);
    
        const osc = audioContext.createOscillator();
        osc.type = 'triangle';
        osc.frequency.setValueAtTime(180, time);
        const oscGain = audioContext.createGain();
        oscGain.gain.setValueAtTime(0.3, time);
        oscGain.gain.exponentialRampToValueAtTime(0.01, time + 0.1);
        osc.connect(oscGain);
        oscGain.connect(masterGain);
        osc.start(time);
        osc.stop(time + 0.1);
      }
    
      function playHat(time) {
        if (!hatNoiseBuffer) {
          hatNoiseBuffer = createNoiseBuffer(0.1);
        }
        const noiseSrc = audioContext.createBufferSource();
        noiseSrc.buffer = hatNoiseBuffer;
        const gain = audioContext.createGain();
        gain.gain.setValueAtTime(0.3, time);
        gain.gain.exponentialRampToValueAtTime(0.01, time + 0.1);
        noiseSrc.connect(gain);
        gain.connect(masterGain);
        noiseSrc.start(time);
        noiseSrc.stop(time + 0.1);
      }
    
      function playHits() {
        if (!audioReady) ensureAudio();
        const state = game.state();
        const time = audioContext.currentTime;
        for (const track of state.hits) {
          if (track === 0) playKick(time);
          else if (track === 1) playSnare(time);
          else if (track === 2) playHat(time);
        }
      }
    
      // DOM
      const gridEl = document.getElementById('grid');
      const numbersEl = document.getElementById('numbers');
      const playBtn = document.getElementById('play');
      const stopBtn = document.getElementById('stop');
      const statusEl = document.getElementById('status');
      const announceEl = document.getElementById('announce');
    
      // Create numbers
      for (let i = 1; i <= 16; i++) {
        const num = document.createElement('div');
        num.className = 'number';
        num.textContent = i;
        numbersEl.appendChild(num);
      }
    
      // Create tracks
      const trackNames = ['Kick', 'Snare', 'Hat'];
      for (let t = 0; t < 3; t++) {
        const row = document.createElement('div');
        row.className = 'track';
        const label = document.createElement('div');
        label.className = 'label';
        label.textContent = trackNames[t];
        row.appendChild(label);
        for (let s = 0; s < 16; s++) {
          const btn = document.createElement('button');
          btn.className = 'step';
          btn.dataset.track = t;
          btn.dataset.step = s;
          btn.setAttribute('aria-pressed', 'false');
          const numSpan = document.createElement('span');
          numSpan.className = 'num';
          numSpan.textContent = (s + 1);
          btn.appendChild(numSpan);
          btn.addEventListener('click', function() {
            ensureAudio();
            game.press([t, s]);
            render();
          });
          row.appendChild(btn);
        }
        gridEl.appendChild(row);
      }
    
      // Play/Stop
      let timer = null;
      playBtn.addEventListener('click', function() {
        ensureAudio();
        game.press('play');
        playHits();
        render();
        if (timer) clearInterval(timer);
        timer = setInterval(function() {
          game.press('tick');
          playHits();
          render();
        }, 125);
      });
      stopBtn.addEventListener('click', function() {
        game.press('stop');
        if (timer) {
          clearInterval(timer);
          timer = null;
        }
        render();
      });
    
      // Visibility change
      document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
          game.press('stop');
          if (timer) {
            clearInterval(timer);
            timer = null;
          }
          render();
        }
      });
    
      // Render
      let wasPlaying = false;
      function render() {
        const state = game.state();
    
        // Update buttons
        const buttons = document.querySelectorAll('.step');
        buttons.forEach(btn => {
          const t = parseInt(btn.dataset.track);
          const s = parseInt(btn.dataset.step);
          const on = state.pattern[t][s] === '1';
          btn.setAttribute('aria-pressed', on ? 'true' : 'false');
          if (on) btn.classList.add('on');
          else btn.classList.remove('on');
    
          if (state.playing && s === state.playhead) {
            btn.classList.add('playhead');
          } else {
            btn.classList.remove('playhead');
          }
        });
    
        // Update numbers
        const numberDivs = document.querySelectorAll('.number');
        numberDivs.forEach((div, idx) => {
          if (state.playing && idx === state.playhead) {
            div.classList.add('playhead-num');
          } else {
            div.classList.remove('playhead-num');
          }
        });
    
        // Status
        if (state.playing) {
          statusEl.textContent = 'Playing, step ' + (state.playhead + 1) + ' of 16';
        } else {
          statusEl.textContent = 'Stopped';
        }
    
        // Announce
        if (state.playing && !wasPlaying) {
          announceEl.textContent = 'Playing';
        } else if (!state.playing && wasPlaying) {
          announceEl.textContent = 'Stopped';
        }
        wasPlaying = state.playing;
    
        // Play/Stop disabled
        playBtn.disabled = state.playing;
        stopBtn.disabled = !state.playing;
      }
    
      // Initial render
      render();
    });
    </script>
    </body>
    </html>
  • Grow a branching plantFailed

    11,085 tokens: 1,230 read, 9,855 written · 1 min 51 s · 88.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.0">
    <title>Grow a branching plant</title>
    <style>
      :root {
        --bg: #fdf6f0;
        --card: #fff;
        --ink: #222;
        --accent: #2c7a7b;
      }
      * { box-sizing: border-box; }
      html, body {
        margin: 0;
        padding: 0;
        background: var(--bg);
        font-family: system-ui, sans-serif;
        color: var(--ink);
        display: flex;
        flex-direction: column;
        align-items: center;
        min-height: 100vh;
      }
      h1 {
        margin: 1.5rem 0 1rem;
        font-size: 1.5rem;
        text-align: center;
      }
      #canvas-container {
        background: var(--card);
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 1rem;
        max-width: 100%;
        margin-bottom: 1rem;
      }
      canvas {
        display: block;
        max-width: 100%;
        height: auto;
      }
      .buttons {
        display: flex;
        gap: 0.5rem;
        margin-bottom: 1rem;
      }
      button {
        font: inherit;
        padding: 0.5rem 1rem;
        border-radius: 6px;
        cursor: pointer;
      }
      #grow {
        background: var(--accent);
        color: white;
        border: none;
      }
      #reset {
        background: transparent;
        border: 1px solid var(--accent);
        color: var(--accent);
      }
      #status {
        margin-top: 0.5rem;
        font-size: 0.9rem;
        text-align: center;
      }
    </style>
    </head>
    <body>
      <h1>Grow a branching plant</h1>
      <div id="canvas-container">
        <canvas id="plant" width="400" height="400"></canvas>
      </div>
      <div class="buttons">
        <button id="grow">Grow</button>
        <button id="reset">Reset</button>
      </div>
      <div id="status" role="status"></div>
    
      <script id="game">
        const rule = "F[[++F[+F]]-F[--F]]F";
        const steps = [[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]];
    
        function computeSegments(text) {
          let x = 0, y = 0;
          let heading = 6;
          const stack = [];
          const segs = [];
          for (let i = 0; i < text.length; i++) {
            const ch = text[i];
            if (ch === 'F') {
              const [dx, dy] = steps[heading];
              const nx = x + dx;
              const ny = y + dy;
              segs.push([x, y, nx, ny]);
              x = nx;
              y = ny;
            } else if (ch === '+') {
              heading = (heading + 1) % 8;
            } else if (ch === '-') {
              heading = (heading + 7) % 8;
            } else if (ch === '[') {
              stack.push({x, y, heading});
            } else if (ch === ']') {
              const prev = stack.pop();
              x = prev.x;
              y = prev.y;
              heading = prev.heading;
            }
          }
          return segs;
        }
    
        function createGame() {
          let generation = 0;
          let text = "F";
          let segments = computeSegments(text);
    
          function grow() {
            let newText = "";
            for (let i = 0; i < text.length; i++) {
              newText += text[i] === 'F' ? rule : text[i];
            }
            if (newText === text) return;
            text = newText;
            generation++;
            segments = computeSegments(text);
          }
    
          function state() {
            return {
              generation: generation,
              text: text,
              segments: segments
            };
          }
    
          return { grow, state };
        }
      </script>
    
      <script>
        const canvas = document.getElementById('plant');
        const ctx = canvas.getContext('2d');
        const growBtn = document.getElementById('grow');
        const resetBtn = document.getElementById('reset');
        const status = document.getElementById('status');
    
        let game = createGame();
    
        function draw() {
          const state = game.state();
          const segs = state.segments;
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          if (segs.length === 0) return;
    
          let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
          for (const [x1, y1, x2, y2] of segs) {
            if (x1 < minX) minX = x1;
            if (x2 < minX) minX = x2;
            if (y1 < minY) minY = y1;
            if (y2 < minY) minY = y2;
            if (x1 > maxX) maxX = x1;
            if (x2 > maxX) maxX = x2;
            if (y1 > maxY) maxY = y1;
            if (y2 > maxY) maxY = y2;
          }
          const width = maxX - minX || 1;
          const height = maxY - minY || 1;
          const scale = Math.min(canvas.width / width, canvas.height / height);
          const midX = (minX + maxX) / 2;
          const midY = (minY + maxY) / 2;
          const offsetX = canvas.width / 2 - midX * scale;
          const offsetY = canvas.height / 2 - midY * scale;
    
          ctx.lineWidth = Math.max(1, scale * 0.5);
          ctx.strokeStyle = '#222';
          ctx.beginPath();
          for (const [x1, y1, x2, y2] of segs) {
            const sx1 = x1 * scale + offsetX;
            const sy1 = y1 * scale + offsetY;
            const sx2 = x2 * scale + offsetX;
            const sy2 = y2 * scale + offsetY;
            ctx.moveTo(sx1, sy1);
            ctx.lineTo(sx2, sy2);
          }
          ctx.stroke();
        }
    
        function updateStatus() {
          const s = game.state();
          const n = s.segments.length;
          const word = n === 1 ? 'segment' : 'segments';
          status.textContent = `Generation ${s.generation} of 4, ${n} ${word}`;
          growBtn.disabled = s.generation >= 4;
        }
    
        function onGrow() {
          game.grow();
          draw();
          updateStatus();
        }
    
        function onReset() {
          game = createGame();
          draw();
          updateStatus();
          growBtn.disabled = false;
        }
    
        growBtn.addEventListener('click', onGrow);
        resetBtn.addEventListener('click', onReset);
    
        draw();
        updateStatus();
      </script>
    </body>
    </html>
  • Falling sandPassed

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

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

    Page source
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Falling sand</title>
    <style>
      body { font-family: sans-serif; margin: 10px; }
      #board { border: 1px solid #000; }
      #status { margin-top: 10px; }
      #say { position: absolute; left: -9999px; }
    </style>
    </head>
    <body>
    <canvas id="board" width="640" height="480"></canvas>
    <div>
      <button id="play">Play</button>
      <button id="step">Step</button>
      <button id="reset">Reset</button>
    </div>
    <div id="status"></div>
    <div id="say" aria-live="polite"></div>
    
    <script id="game">
    function createGame() {
      const ROWS = 30, COLS = 40;
      let board = new Array(ROWS);
      for (let y = 0; y < ROWS; y++) board[y] = new Int8Array(COLS);
      // walls
      for (let x = 0; x < COLS; x++) board[29][x] = 2;
      for (let x = 25; x <= 30; x++) board[15][x] = 2;
      for (let x = 17; x <= 25; x++) board[21][x] = 2;
      for (let x = 7; x <= 14; x++) board[19][x] = 2;
      // sand
      board[2][24] = 1;
      for (let x = 21; x <= 27; x++) board[3][x] = 1;
      for (let x = 20; x <= 28; x++) board[4][x] = 1;
      for (let x = 19; x <= 29; x++) board[5][x] = 1;
      for (let x = 20; x <= 28; x++) board[6][x] = 1;
      for (let x = 21; x <= 27; x++) board[7][x] = 1;
      board[8][24] = 1;
    
      let frame = 0;
    
      function pour(x, y) {
        if (x >= 0 && x < COLS && y >= 0 && y < ROWS && board[y][x] === 0) {
          board[y][x] = 1;
        }
      }
    
      function step() {
        const even = (frame % 2 === 0);
        for (let y = 28; y >= 0; y--) {
          if (even) {
            for (let x = 0; x < COLS; x++) {
              if (board[y][x] === 1) {
                if (board[y+1][x] === 0) {
                  board[y+1][x] = 1;
                  board[y][x] = 0;
                } else if (x > 0 && board[y+1][x-1] === 0) {
                  board[y+1][x-1] = 1;
                  board[y][x] = 0;
                } else if (x < COLS-1 && board[y+1][x+1] === 0) {
                  board[y+1][x+1] = 1;
                  board[y][x] = 0;
                }
              }
            }
          } else {
            for (let x = COLS-1; x >= 0; x--) {
              if (board[y][x] === 1) {
                if (board[y+1][x] === 0) {
                  board[y+1][x] = 1;
                  board[y][x] = 0;
                } else if (x > 0 && board[y+1][x-1] === 0) {
                  board[y+1][x-1] = 1;
                  board[y][x] = 0;
                } else if (x < COLS-1 && board[y+1][x+1] === 0) {
                  board[y+1][x+1] = 1;
                  board[y][x] = 0;
                }
              }
            }
          }
        }
        frame++;
      }
    
      function play(move) {
        if (move === "step") step();
        else if (Array.isArray(move) && move.length === 2) pour(move[0], move[1]);
      }
    
      function state() {
        return {
          frame: frame,
          cells: board.map(row => Array.from(row))
        };
      }
    
      return { play, state };
    }
    </script>
    
    <script>
    const canvas = document.getElementById('board');
    const ctx = canvas.getContext('2d');
    const playBtn = document.getElementById('play');
    const stepBtn = document.getElementById('step');
    const resetBtn = document.getElementById('reset');
    const status = document.getElementById('status');
    const say = document.getElementById('say');
    
    const CELL_W = 16, CELL_H = 16;
    
    let game = createGame();
    let playing = false;
    let intervalId = null;
    let lastMouseCell = null;
    let dragging = false;
    let wasPlaying = false;
    
    function getCell(e) {
      const rect = canvas.getBoundingClientRect();
      const x = Math.floor((e.clientX - rect.left) / rect.width * 40);
      const y = Math.floor((e.clientY - rect.top) / rect.height * 30);
      return [x, y];
    }
    
    function pourAtCell(x, y) {
      game.play([x, y]);
      draw();
      updateStatus();
    }
    
    function onLine(x0, y0, x1, y1) {
      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;
      let x = x0, y = y0;
      while (true) {
        pourAtCell(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;
        }
      }
    }
    
    canvas.addEventListener('mousedown', e => {
      const [x, y] = getCell(e);
      pourAtCell(x, y);
      lastMouseCell = [x, y];
      dragging = true;
    });
    
    canvas.addEventListener('mousemove', e => {
      if (!dragging) return;
      const [x, y] = getCell(e);
      if (lastMouseCell && (x !== lastMouseCell[0] || y !== lastMouseCell[1])) {
        onLine(lastMouseCell[0], lastMouseCell[1], x, y);
        lastMouseCell = [x, y];
      }
    });
    
    canvas.addEventListener('mouseup', () => {
      dragging = false;
    });
    
    playBtn.addEventListener('click', () => {
      if (playing) {
        pause();
      } else {
        play();
      }
    });
    
    stepBtn.addEventListener('click', () => {
      game.play('step');
      draw();
      updateStatus();
      announce('Step');
    });
    
    resetBtn.addEventListener('click', () => {
      game = createGame();
      if (playing) {
        pause();
      }
      draw();
      updateStatus();
      announce('Reset');
    });
    
    function play() {
      if (prefersReducedMotion()) {
        game.play('step');
        draw();
        updateStatus();
        announce('Play');
        return;
      }
      playing = true;
      playBtn.textContent = 'Pause';
      announce('Play');
      intervalId = setInterval(() => {
        game.play('step');
        draw();
        updateStatus();
      }, 50);
    }
    
    function pause() {
      playing = false;
      playBtn.textContent = 'Play';
      announce('Pause');
      clearInterval(intervalId);
    }
    
    function prefersReducedMotion() {
      return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    }
    
    function announce(msg) {
      say.textContent = msg;
    }
    
    function updateStatus() {
      const st = game.state();
      let grains = 0;
      for (let row of st.cells) {
        for (let v of row) if (v === 1) grains++;
      }
      const grainText = grains === 1 ? '1 grain of sand' : `${grains} grains of sand`;
      status.textContent = `Frame ${st.frame}, ${grainText}`;
    }
    
    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      const st = game.state();
      for (let y = 0; y < 30; y++) {
        for (let x = 0; x < 40; x++) {
          const v = st.cells[y][x];
          if (v === 1) {
            ctx.fillStyle = '#e0c000';
            ctx.fillRect(x * CELL_W, y * CELL_H, CELL_W, CELL_H);
          } else if (v === 2) {
            ctx.fillStyle = '#333';
            ctx.fillRect(x * CELL_W, y * CELL_H, CELL_W, CELL_H);
          }
        }
      }
    }
    
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        if (playing) {
          pause();
          wasPlaying = true;
        }
      } else {
        if (wasPlaying) {
          play();
          wasPlaying = false;
        }
      }
    });
    
    // initial draw
    draw();
    updateStatus();
    </script>
    </body>
    </html>
  • Focus timerPassed

    13,038 tokens: 1,098 read, 11,940 written · 2 min 10 s · 92 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 1500 seconds (25 minutes), short break 420 seconds (7 minutes), long break 900 seconds (15 minutes). A long break follows every 4th finished work period.
    
    The rules, exactly:
    1. The timer starts in work, with left 1500, 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 4, 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 25:00.
    - An SVG ring around the time: a circle with pathLength="100" and stroke-dasharray="100". Set its stroke-dashoffset attribute to 100 times (1 minus left divided by the full length of the current period) on every redraw. The arc is full, with an offset of 0, at the start of a period, and it is empty, with an offset of 100, when the time is up. A track circle without a stroke-dashoffset may sit under it.
    - Four buttons in one row, with the ids start, pause, skip and reset, labelled Start, Pause, Skip and Reset. Each calls tick() with its command. Start is disabled while the timer runs, and Pause is disabled while it is paused. Skip and Reset are always enabled. Below 390 px they may wrap into two rows of two.
    - The count in an element with the id count, in words: "Focus periods done: 3".
    - The page's own timer calls tick() once a second, with no argument. After every call, the page redraws from state(). When a period ends, the page may play a short chime with the Web Audio API.
    - Look: a light, warm off-white page with one white card, dark ink text and muted grey for the small labels. One accent colour, used for the Start button only. Flat fills, no gradients or shadows, no outside fonts or images: use the system font. It must look tidy at 390 px and at 1280 px wide, with no sideways scrolling.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the timer's logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and drives the timer through createGame(). Do not use eval, Function or any other way of running text as code: no string given to a timer, and no script element or event-handler attribute made from text while the page runs. Put the wiring in another <script>.

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

    Page source
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Focus timer</title>
    <style>
    :root {
      --accent: #ff6b6b;
      --bg: #faf8f5;
      --card-bg: #fff;
      --text: #333;
      --muted: #777;
    }
    * {
      box-sizing: border-box;
    }
    body {
      margin: 0;
      padding: 20px;
      background: var(--bg);
      font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
      color: var(--text);
      display: flex;
      justify-content: center;
      align-items: flex-start;
      min-height: 100vh;
    }
    .card {
      background: var(--card-bg);
      border-radius: 8px;
      padding: 20px;
      max-width: 480px;
      width: 100%;
      text-align: center;
    }
    h1 {
      margin-top: 0;
      font-size: 1.5rem;
    }
    #phase {
      font-size: 1.2rem;
      margin-bottom: 10px;
    }
    #time {
      font-size: 2.5rem;
      font-weight: bold;
      margin: 10px 0;
    }
    svg {
      display: block;
      margin: 0 auto 10px;
      width: 150px;
      height: 150px;
    }
    .track {
      stroke: #e0e0e0;
    }
    .progress {
      stroke: var(--accent);
      stroke-linecap: round;
    }
    .buttons {
      display: flex;
      gap: 10px;
      justify-content: center;
      flex-wrap: wrap;
      margin-bottom: 10px;
    }
    button {
      flex: 1 1 45%;
      padding: 10px;
      border: none;
      border-radius: 4px;
      font-size: 1rem;
      cursor: pointer;
      min-width: 120px;
    }
    #start {
      background: var(--accent);
      color: #fff;
    }
    #start:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
    #pause, #skip, #reset {
      background: #f0f0f0;
      color: var(--text);
    }
    #pause:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
    #count {
      color: var(--muted);
      font-size: 0.9rem;
    }
    </style>
    </head>
    <body>
    <div class="card">
      <h1>Focus timer</h1>
      <div id="phase">Focus</div>
      <svg viewBox="0 0 120 120">
        <circle class="track" cx="60" cy="60" r="50" fill="none" stroke-width="10"/>
        <circle id="progress-ring" class="progress" cx="60" cy="60" r="50" fill="none" stroke-width="10" pathLength="100" stroke-dasharray="100" stroke-dashoffset="0"/>
      </svg>
      <div id="time">25:00</div>
      <div class="buttons">
        <button id="start">Start</button>
        <button id="pause">Pause</button>
        <button id="skip">Skip</button>
        <button id="reset">Reset</button>
      </div>
      <div id="count">Focus periods done: 0</div>
    </div>
    
    <script id="game">
    function createGame() {
      const WORK = 1500;
      const SHORT = 420;
      const LONG = 900;
    
      let phase = 'work';
      let left = WORK;
      let running = false;
      let done = 0;
    
      function fullLength(p) {
        if (p === 'work') return WORK;
        if (p === 'short') return SHORT;
        if (p === 'long') return LONG;
      }
    
      function transition() {
        if (phase === 'work') {
          done++;
          if (done % 4 === 0) {
            phase = 'long';
          } else {
            phase = 'short';
          }
        } else {
          phase = 'work';
        }
        left = fullLength(phase);
        running = false;
      }
    
      function skipTransition() {
        if (phase === 'work') {
          phase = 'short';
        } else {
          phase = 'work';
        }
        left = fullLength(phase);
        running = false;
      }
    
      return {
        tick(cmd) {
          if (cmd === 'start') {
            running = true;
          } else if (cmd === 'pause') {
            running = false;
          } else if (cmd === 'skip') {
            skipTransition();
          } else if (cmd === 'reset') {
            left = fullLength(phase);
            running = false;
          } else {
            if (running) {
              left--;
              if (left === 0) {
                transition();
              }
            }
          }
        },
        state() {
          return { phase, left, running, done };
        }
      };
    }
    </script>
    
    <script>
    const game = createGame();
    
    const phaseEl = document.getElementById('phase');
    const timeEl = document.getElementById('time');
    const countEl = document.getElementById('count');
    const startBtn = document.getElementById('start');
    const pauseBtn = document.getElementById('pause');
    const skipBtn = document.getElementById('skip');
    const resetBtn = document.getElementById('reset');
    const progressRing = document.getElementById('progress-ring');
    
    const WORK = 1500;
    const SHORT = 420;
    const LONG = 900;
    
    function fullLength(phase) {
      if (phase === 'work') return WORK;
      if (phase === 'short') return SHORT;
      if (phase === 'long') return LONG;
    }
    
    function formatTime(seconds) {
      const m = Math.floor(seconds / 60).toString().padStart(2, '0');
      const s = (seconds % 60).toString().padStart(2, '0');
      return `${m}:${s}`;
    }
    
    let prevState = null;
    
    function playChime() {
      try {
        if (!window.audioCtx) {
          window.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        }
        const ctx = window.audioCtx;
        const osc = ctx.createOscillator();
        const gain = ctx.createGain();
        osc.connect(gain);
        gain.connect(ctx.destination);
        osc.frequency.value = 880;
        osc.type = 'sine';
        gain.gain.setValueAtTime(0.3, ctx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.5);
        osc.start();
        osc.stop(ctx.currentTime + 0.5);
      } catch (e) { /* ignore */ }
    }
    
    function update() {
      const s = game.state();
      
      let phaseText;
      switch (s.phase) {
        case 'work': phaseText = 'Focus'; break;
        case 'short': phaseText = 'Short break'; break;
        case 'long': phaseText = 'Long break'; break;
      }
      phaseEl.textContent = phaseText;
      
      timeEl.textContent = formatTime(s.left);
      
      countEl.textContent = `Focus periods done: ${s.done}`;
      
      const full = fullLength(s.phase);
      const offset = 100 * (1 - s.left / full);
      progressRing.setAttribute('stroke-dashoffset', offset);
      
      startBtn.disabled = s.running;
      pauseBtn.disabled = !s.running;
      
      if (prevState !== null && prevState.phase !== s.phase) {
        playChime();
      }
      prevState = s;
    }
    
    startBtn.addEventListener('click', () => { game.tick('start'); update(); });
    pauseBtn.addEventListener('click', () => { game.tick('pause'); update(); });
    skipBtn.addEventListener('click', () => { game.tick('skip'); update(); });
    resetBtn.addEventListener('click', () => { game.tick('reset'); update(); });
    
    update();
    
    setInterval(() => {
      game.tick();
      update();
    }, 1000);
    </script>
    </body>
    </html>
Writing code 2 of 3
  • Merge intervalsPassed

    2,220 tokens: 160 read, 2,060 written · 26 s · 79.5 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 (!intervals || intervals.length === 0) return [];
      const sorted = intervals.slice().sort((a, b) => a[0] - b[0]);
      const merged = [];
      let current = [sorted[0][0], sorted[0][1]];
      for (let i = 1; i < sorted.length; i++) {
        const [start, end] = sorted[i];
        if (start <= current[1]) {
          current[1] = Math.max(current[1], end);
        } else {
          merged.push(current);
          current = [start, end];
        }
      }
      merged.push(current);
      return merged;
    }
    ```
  • An LRU cachePassed

    1,573 tokens: 166 read, 1,407 written · 18 s · 80 tok/s

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

    131,267 tokens: 195 read, 131,072 written · 19 min 14 s · 114 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.
Fixing code 2 of 2
  • Fix the bookings modulePassed

    1,507 tokens: 621 read, 886 written · 10 s · 88 tok/s

    This JavaScript module has one bug. The occupancy report sometimes counts one booked night more than there is in the range it was asked about.
    
    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

    1,979 tokens: 466 read, 1,513 written · 17 s · 87.4 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

    1,274 tokens: 223 read, 1,051 written · 13 s · 81.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: Every customer who has no delivered order (including customers with no orders at all), with how many orders of any status they placed. Columns: name, orders. Any order of rows.
    
    Reply with only the query, in one ```sql code block: one SELECT statement (WITH is fine), nothing that changes the database.
    
    ```sql
    SELECT c.name, COUNT(o.id) AS orders
    FROM customers c
    LEFT JOIN orders o ON o.customer_id = c.id
    WHERE NOT EXISTS (
        SELECT 1 FROM orders od
        WHERE od.customer_id = c.id AND od.status = 'delivered'
    )
    GROUP BY c.id, c.name;
    ```
  • Schedule five meetingsPassed

    6,248 tokens: 286 read, 5,962 written · 1 min 2 s · 95.4 tok/s

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

    10,917 tokens: 9,857 read, 1,060 written · 22 s · 48.3 tok/s

    Hi, it's cal.reyes@example.com. My kettle arrived with a cracked lid. Can you sort it out?
    1. system
      You are the support agent of Tidewell Home, working through its tools, and you may make at most 10 tool calls for one request. When an item arrives damaged: confirm which order it came in, send a replacement from the north warehouse if it has the item, else from south, else from east (check each in that order, and only as far as needed), and take the damaged item back with a return. If the return is refused, open a damage claim for the order with open_claim. Then reply to the customer with what you did, giving any reference numbers and the date the replacement ships.
    2. user
      Hi, it's cal.reyes@example.com. My kettle arrived with a cracked lid. Can you sort it out?
    3. assistant
      
      I'll help you with the damaged kettle. Let me first look up your account and find the relevant order.
      
      lookup_account({"email": "cal.reyes@example.com"})
    4. tool
      {"account_id": "AC-457", "name": "Cal Reyes"}
    5. assistant
      
      
      
      list_orders({"account_id": "AC-457"})
    6. tool
      {"orders": [{"order_id": "R-5269", "placed": "2026-10-07", "status": "delivered"}, {"order_id": "R-5564", "placed": "2026-10-19", "status": "delivered"}, {"order_id": "R-5212", "placed": "2026-10-24", "status": "in transit"}]}
    7. assistant
      
      
      
      get_order({"order_id": "R-5564"})
    8. tool
      {"items": [{"name": "Steel kettle", "quantity": 1, "sku": "kettle-steel"}, {"name": "Grey mug", "quantity": 2, "sku": "mug-grey"}], "order_id": "R-5564"}
    9. assistant
      
      
      
      check_stock({"sku": "kettle-steel", "warehouse": "north"})
    10. tool
      {"available": 0, "sku": "kettle-steel", "warehouse": "north"}
    11. assistant
      
      
      
      check_stock({"sku": "kettle-steel", "warehouse": "south"})
    12. tool
      {"available": 5, "sku": "kettle-steel", "warehouse": "south"}
    13. assistant
      
      
      
      reserve_item({"order_id": "R-5564", "sku": "kettle-steel", "warehouse": "south"})
    14. tool
      {"reservation_id": "RS-4388", "ships_on": "2026-11-26"}
    15. assistant
      
      
      
      create_return({"order_id": "R-5564", "reason": "Damaged - cracked lid"})
    16. tool
      {"error": "damaged items are not returned: open a damage claim with open_claim instead"}
    17. assistant
      
      
      
      open_claim({"order_id": "R-5564", "reason": "Damaged - cracked lid"})
    18. tool
      {"claim_id": "CL-4780", "order_id": "R-5564", "status": "open"}
    19. assistant
      
      I've taken care of your damaged kettle. Here's what I did:
      
      1. **Replacement Ordered**: Reserved a new steel kettle (SKU: kettle-steel) from our south warehouse. It will ship on **November 26, 2026** with reservation ID **RS-4388**.
      
      2. **Damage Claim Opened**: Since the item arrived damaged, I've opened a claim for your order **R-5564**. Claim ID: **CL-4780** (status: open).
      
      The replacement will be sent to your address on file. No return is needed for the damaged kettle. Let me know if you need anything else!

Comments

Sign in or create an account to comment.