baidu/ernie-5.5-flash-preview:free run
OpenRouter · OpenCode 2.2.7 · every run of this model · uwu · 2026-11-13
Run baidu/ernie-5.5-flash-preview:free on your computer to see the two side by side.
A full run: 50 tasks, 82 points
- Score
- 21,609 Diamond Speed times the share of points, times 100. How scores work253 tok/s × 85.4% of points
- Bronze0
- Silver1,500
- Gold3,000
- Platinum6,000
- Diamond10,000
Not on the leaderboard: it ran through a hosted service, so it is not on a computer board. Leaderboard
- Tasks passed
- 44/50
- Points
- 70/82Harder tasks count 3. How scores work
- Tokens
- 285,36426,331 read, 259,033 written.
- Speed
- 253 tok/sTokens a second, as the runner measured it. The site checks only that the machine could reach it. How speeds are checked
- Summarizing 3/5
- Extracting 5/5
- Following instructions 5/5
- Reasoning 5/5
- Reading code 4/4
- Using tools 5/5
- Building pages 4/5
- Building games 3/4
- Building apps 3/4
- Writing code 3/3
- Fixing code 1/2
- Planning and data 3/3
Run details
Flag this run
Failed 6
One-sentence summaryFailed
427 tokens: 115 read, 312 written · 2 s · 167 tok/s
Summarize this in one sentence of at most 30 words. Starting September 19, the Westham Public Library will open at 7:20 a.m. instead of 9:45 a.m. on weekdays. The change follows a survey in which 52% of respondents asked for earlier hours. Weekend hours stay the same. The library will hire four part-time staff to cover the extra time, paid for by a state grant.
Starting September 19, Westham Public Library will open weekdays at 7:20 a.m. instead of 9:45, keeping weekend hours, with four new part-time staff funded by a state grant.
Meeting notes in three bulletsFailed
385 tokens: 194 read, 191 written · 2 s · 92.8 tok/s
Summarize these meeting notes as exactly three bullet points, each at most 20 words. Keep only the decisions and ownership changes that matter. Output only the bullet points. Weekly sync, design team. Present: Hugo, Tariq, Priya, Dana. - Priya reported that the payment provider fixed the export bug; no action needed. - The launch date moves from August 10 to August 15 because the app store review is slow. - Dana showed the new onboarding screens. Everyone liked them. Small copy changes only. - The marketing budget of $15,000 was approved by finance on Friday. - Hugo will own end-to-end testing from now on; Tariq hands over the test plan by Tuesday. - Next sync is moved to Monday at 09:15. - Coffee machine on floor 5 is broken again.
- Launch date moves from August 10 to August 15 due to slow app store review. - Finance approved the $15,000 marketing budget on Friday. - Hugo takes ownership of end-to-end testing; Tariq delivers the test plan by Tuesday.
A bar chart in SVGFailed
1,595 tokens: 242 read, 1,353 written · 5 s · 267 tok/s
Draw an inline SVG bar chart of bagels sold, in this order: Mar 20, Apr 11, May 14, Jun 31 and Jul 13. 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"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bagels Sold</title> <style> body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; margin: 24px; background: #f7f7f5; color: #222; } h1 { font-size: 20px; margin: 0 0 12px 0; } svg { background: #ffffff; border: 1px solid #d8d8d4; } .bar { fill: #b5651d; stroke: #7a4310; stroke-width: 1; } .label { fill: #222; font-size: 15px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .value { fill: #555; font-size: 13px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .axis { stroke: #999; stroke-width: 1; } </style> </head> <body> <h1>Bagels sold</h1> <svg width="660" height="400" viewBox="0 0 660 400" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Bar chart of bagels sold: March 20, April 11, May 14, June 31, July 13."> <title>Bagels sold by month: March 20, April 11, May 14, June 31, July 13</title> <!-- baseline (axis) --> <line class="axis" x1="60" y1="330" x2="620" y2="330"/> <!-- Bars: height = value * 8, drawn from baseline y=330 upward --> <rect class="bar" x="80" y="170" width="70" height="160" /> <rect class="bar" x="190" y="242" width="70" height="88" /> <rect class="bar" x="300" y="218" width="70" height="112" /> <rect class="bar" x="410" y="82" width="70" height="248" /> <rect class="bar" x="520" y="226" width="70" height="104" /> <!-- value labels above bars --> <text class="value" x="115" y="162" text-anchor="middle">20</text> <text class="value" x="225" y="234" text-anchor="middle">11</text> <text class="value" x="335" y="210" text-anchor="middle">14</text> <text class="value" x="445" y="74" text-anchor="middle">31</text> <text class="value" x="555" y="218" text-anchor="middle">13</text> <!-- month labels under the bars --> <text class="label" x="115" y="355" text-anchor="middle">Mar 20</text> <text class="label" x="225" y="355" text-anchor="middle">Apr 11</text> <text class="label" x="335" y="355" text-anchor="middle">May 14</text> <text class="label" x="445" y="355" text-anchor="middle">Jun 31</text> <text class="label" x="555" y="355" text-anchor="middle">Jul 13</text> </svg> </body> </html>Build SnakeFailed
21,014 tokens: 460 read, 20,554 written · 1 min 8 s · 304 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, 6], [5, 6], [6, 6]], moving left, food at [5, 4], 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
Here is a complete HTML page for a 10×10 Snake game with arrow-key controls, an inline grid, and separate game-logic and wiring scripts. Press an arrow key to make one step, and use “New game” to reset. ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Snake · 10×10</title> <style> :root { color-scheme: dark; } * { box-sizing: border-box; } html, body { height: 100%; } body { margin: 0; min-height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; padding: 24px; background: radial-gradient(1100px 700px at 50% -15%, #1b2233 0%, #0a0d13 65%); color: #dfe4ee; font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; user-select: none; -webkit-user-select: none; -webkit-tap-highlight-color: transparent; } h1 { margin: 0; font-size: 20px; font-weight: 700; letter-spacing: 0.22em; text-transform: uppercase; color: #9dfbb0; text-shadow: 0 0 18px rgba(120, 240, 150, 0.35); } .hud { font-size: 13px; letter-spacing: 0.12em; text-transform: uppercase; color: #8b97ad; } .hud b { color: #e8edf6; font-size: 15px; font-variant-numeric: tabular-nums; } .frame { padding: 10px; border-radius: 16px; background: #10141c; box-shadow: 0 0 0 1px #242c3b, 0 24px 60px rgba(0, 0, 0, 0.6); } canvas { display: block; border-radius: 8px; } .hint { margin: 0; font-size: 13px; color: #78849a; } button { appearance: none; border: 0; padding: 10px 22px; border-radius: 999px; background: #1d2634; color: #dfe4ee; font: inherit; font-size: 13px; letter-spacing: 0.06em; cursor: pointer; box-shadow: 0 0 0 1px #2f3a4d, 0 6px 16px rgba(0, 0, 0, 0.4); transition: background 120ms ease, transform 60ms ease; } button:hover { background: #26303f; } button:active { transform: translateY(1px); } button:focus-visible { outline: 2px solid #9dfbb0; outline-offset: 3px; } </style> </head> <body> <h1>Snake</h1> <div class="hud">Score <b id="score">0</b></div> <div class="frame"><canvas id="board" aria-label="Snake board, 10 by 10"></canvas></div> <p class="hint">Arrow keys — one press, one step.</p> <button id="restart" type="button">New game</button> <script id="game"> "use strict"; var GRID = 10; var DIRS = { up: [ 0, -1], down: [ 0, 1], left: [-1, 0], right: [ 1, 0] }; var OPPOSITE = { up: "down", down: "up", left: "right", right: "left" }; function createGame() { var snake = [[4, 6], [5, 6], [6, 6]]; var food = [5, 4]; var score = 0; var over = false; var dir = "left"; // Is `cell` inside the first `count` snake cells (head first)? function onSnake(cell, count) { for (var i = 0; i < count; i++) { if (snake[i][0] === cell[0] && snake[i][1] === cell[1]) return true; } return false; } function step(next) { if (over) return; // Rule 2: an opposite direction is ignored and the snake keeps going in // its current direction; anything else becomes the current direction. if (OPPOSITE[dir] === next) { // ignored — keep `dir` } else if (Object.prototype.hasOwnProperty.call(DIRS, next)) { dir = next; } else { return; // not a direction: nothing to do } var d = DIRS[dir]; var head = snake[0]; var nx = head[0] + d[0]; var ny = head[1] + d[1]; // Rule 4, first half: off the grid. if (nx < 0 || nx >= GRID || ny < 0 || ny >= GRID) { over = true; return; } // Rule 3: the tail is freed first unless the snake eats. var eats = food !== null && food[0] === nx && food[1] === ny; var bodyLen = eats ? snake.length : snake.length - 1; // Rule 4, second half: head lands on a cell of the snake (after rule 3). if (onSnake([nx, ny], bodyLen)) { over = true; return; } // Move the head. snake.unshift([nx, ny]); if (!eats) { snake.pop(); } else { score += 1; // Rule 5a // Rule 5b: first empty cell in reading order after the new head's cell, // wrapping from [9, 9] to [0, 0]. var total = GRID * GRID; var start = ny * GRID + nx + 1; var nextFood = null; for (var k = 0; k < total; k++) { var idx = (start + k) % total; var cx = idx % GRID; var cy = (idx - cx) / GRID; if (!onSnake([cx, cy], snake.length)) { nextFood = [cx, cy]; break; } } food = nextFood; } } function state() { return { snake: snake.map(function (c) { return [c[0], c[1]]; }), food: food === null ? null : [food[0], food[1]], score: score, over: over }; } return { step: step, state: state }; } </script> <script> (function () { "use strict"; var SIZE = 10; var CELL = 40; var BOARD = SIZE * CELL; var canvas = document.getElementById("board"); var scoreEl = document.getElementById("score"); var restartBtn = document.getElementById("restart"); var ctx = canvas.getContext("2d"); // Crisp rendering on high-DPI screens. var dpr = Math.min(3, Math.max(1, window.devicePixelRatio || 1)); canvas.width = Math.round(BOARD * dpr); canvas.height = Math.round(BOARD * dpr); canvas.style.width = BOARD + "px"; canvas.style.height = BOARD + "px"; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); var game = createGame(); function roundRect(x, y, w, h, r) { var rr = Math.min(r, w / 2, h / 2); ctx.beginPath(); ctx.moveTo(x + rr, y); ctx.arcTo(x + w, y, x + w, y + h, rr); ctx.arcTo(x + w, y + h, x, y + h, rr); ctx.arcTo(x, y + h, x, y, rr); ctx.arcTo(x, y, x + w, y, rr); ctx.closePath(); } function drawBoard() { ctx.fillStyle = "#0a0d13"; ctx.fillRect(0, 0, BOARD, BOARD); // Faint checkerboard so the 10×10 cells are easy to see. ctx.fillStyle = "rgba(255, 255, 255, 0.022)"; for (var y = 0; y < SIZE; y++) { for (var x = 0; x < SIZE; x++) { if ((x + y) % 2 === 0) ctx.fillRect(x * CELL, y * CELL, CELL, CELL); } } // Grid lines. ctx.strokeStyle = "rgba(130, 160, 210, 0.16)"; ctx.lineWidth = 1; ctx.beginPath(); for (var i = 1; i < SIZE; i++) { var p = i * CELL + 0.5; ctx.moveTo(p, 0); ctx.lineTo(p, BOARD); ctx.moveTo(0, p); ctx.lineTo(BOARD, p); } ctx.stroke(); } function drawFood(food) { if (!food) return; var fx = food[0] * CELL + CELL / 2; var fy = food[1] * CELL + CELL / 2; ctx.save(); ctx.shadowColor = "rgba(255, 80, 105, 0.8)"; ctx.shadowBlur = 16; ctx.fillStyle = "#ff4f66"; ctx.beginPath(); ctx.arc(fx, fy, CELL * 0.3, 0, Math.PI * 2); ctx.fill(); ctx.restore(); ctx.fillStyle = "rgba(255, 255, 255, 0.7)"; ctx.beginPath(); ctx.arc(fx - CELL * 0.1, fy - CELL * 0.1, CELL * 0.07, 0, Math.PI * 2); ctx.fill(); } function drawSnake(snake) { for (var i = snake.length - 1; i >= 0; i--) { var cell = snake[i]; var isHead = i === 0; var pad = isHead ? 2 : 3.5; var x = cell[0] * CELL + pad; var y = cell[1] * CELL + pad; var w = CELL - pad * 2; ctx.fillStyle = isHead ? "#a3f7b5" : (i % 2 === 0 ? "#3fc25e" : "#37ad53"); if (isHead) { ctx.save(); ctx.shadowColor = "rgba(120, 240, 150, 0.45)"; ctx.shadowBlur = 12; } roundRect(x, y, w, w, isHead ? 9 : 7); ctx.fill(); if (isHead) ctx.restore(); } } function drawEyes(snake) { var head = snake[0]; if (!head) return; var hx = head[0] * CELL + CELL / 2; var hy = head[1] * CELL + CELL / 2; // Infer facing from head -> neck (default: left, the starting direction). var fx = -1, fy = 0; if (snake.length > 1) { fx = head[0] - snake[1][0]; fy = head[1] - snake[1][1]; } var fwd = 5.5, side = 6; var e1x, e1y, e2x, e2y; if (fx !== 0) { e1x = hx + fx * fwd; e1y = hy + side; e2x = hx + fx * fwd; e2y = hy - side; } else if (fy !== 0) { e1x = hx + side; e1y = hy + fy * fwd; e2x = hx - side; e2y = hy + fy * fwd; } else { e1x = hx + side; e1y = hy; e2x = hx - side; e2y = hy; } ctx.fillStyle = "#0a1a10"; ctx.beginPath(); ctx.arc(e1x, e1y, 2.8, 0, Math.PI * 2); ctx.fill(); ctx.beginPath(); ctx.arc(e2x, e2y, 2.8, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = "rgba(255, 255, 255, 0.85)"; ctx.beginPath(); ctx.arc(e1x - 0.9, e1y - 0.9, 0.9, 0, Math.PI * 2); ctx.fill(); ctx.beginPath(); ctx.arc(e2x - 0.9, e2y - 0.9, 0.9, 0, Math.PI * 2); ctx.fill(); } function drawOver() { ctx.fillStyle = "rgba(5, 7, 11, 0.74)"; ctx.fillRect(0, 0, BOARD, BOARD); ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = "#ff4f66"; ctx.font = "800 36px system-ui, -apple-system, 'Segoe UI', sans-serif"; ctx.fillText("GAME OVER", BOARD / 2, BOARD / 2 - 12); ctx.fillStyle = "#93a0b6"; ctx.font = "500 15px system-ui, -apple-system, 'Segoe UI', sans-serif"; ctx.fillText("New game to play again", BOARD / 2, BOARD / 2 + 28); } function draw() { var st = game.state(); drawBoard(); drawFood(st.food); drawSnake(st.snake); drawEyes(st.snake); if (st.over) drawOver(); scoreEl.textContent = String(st.score); } var KEYMAP = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right" }; // One key press = one step. document.addEventListener("keydown", function (e) { var dir = KEYMAP[e.key]; if (!dir) return; e.preventDefault(); if (e.repeat || e.altKey || e.ctrlKey || e.metaKey) return; game.step(dir); draw(); }); restartBtn.addEventListener("click", function () { game = createGame(); draw(); restartBtn.blur(); }); draw(); })(); </script> </body> </html> ``` ### Gameplay & Controls The snake moves automatically one cell per arrow key press, and you can reset at any time. - **One key press = one step** — each arrow key press moves the snake exactly one cell; holding a key does not auto-repeat. - **Direction rules** — if you press the opposite of the current direction, the input is ignored and the snake continues straight. Pressing a new valid direction changes the current direction. - **Food & scoring** — eating food adds 1 point and the snake grows; the next food appears in the first empty cell after the new head, wrapping around. - **Collision** — hitting the grid edge or the snake ends the game; once over, all steps do nothing until you click **New game**. - **Visual feedback** — a checkerboard grid, glowing snake body, red food, and an overlay appear when the game ends.Grow a branching plantFailed
26,348 tokens: 1,230 read, 25,118 written · 1 min 49 s · 230 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
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Grow a branching plant</title> <style> :root { --page: #f7f3ea; --card: #ffffff; --line: #e6ded1; --ink: #22322a; --muted: #6a6559; --accent: #2f6b4f; --accent-dark: #24543c; } * { box-sizing: border-box; } html, body { margin: 0; } body { min-height: 100vh; padding: 28px 16px 56px; background: var(--page); color: var(--ink); font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; display: flex; flex-direction: column; align-items: center; -webkit-font-smoothing: antialiased; } h1 { margin: 0 0 22px; font-size: clamp(1.5rem, 4vw, 2.1rem); font-weight: 650; letter-spacing: -0.01em; text-align: center; } .card { width: 100%; max-width: 560px; padding: 12px; background: var(--card); border: 1px solid var(--line); border-radius: 16px; box-shadow: 0 2px 10px rgba(60, 50, 30, 0.05); } canvas { display: block; width: 100%; height: auto; border-radius: 8px; background: #ffffff; } .status { width: 100%; max-width: 560px; margin: 16px 0 0; text-align: center; font-size: 0.95rem; color: var(--muted); font-variant-numeric: tabular-nums; } .controls { margin-top: 18px; display: flex; gap: 12px; flex-wrap: wrap; justify-content: center; } button { font: inherit; font-weight: 600; font-size: 1rem; padding: 11px 28px; border-radius: 11px; cursor: pointer; transition: background-color 0.15s ease, transform 0.05s ease; } button:focus-visible { outline: 3px solid rgba(47, 107, 79, 0.35); outline-offset: 2px; } #grow { color: #ffffff; background: var(--accent); border: 1px solid var(--accent); } #grow:hover:not(:disabled) { background: var(--accent-dark); border-color: var(--accent-dark); } #grow:active:not(:disabled) { transform: translateY(1px); } #grow:disabled { opacity: 0.4; cursor: not-allowed; } #reset { color: var(--accent); background: transparent; border: 1px solid var(--accent); } #reset:hover { background: rgba(47, 107, 79, 0.08); } #reset:active { transform: translateY(1px); } </style> </head> <body> <h1>Grow a branching plant</h1> <div class="card"> <canvas id="canvas" width="600" height="600" role="img" aria-label="The plant drawn so far"></canvas> </div> <p class="status" role="status" id="status"></p> <div class="controls"> <button id="grow" type="button">Grow</button> <button id="reset" type="button">Reset</button> </div> <script id="game"> function createGame() { var rule = "F[-F[--F]]F[[++F]]F"; var steps = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; var generation = 0; var text = "F"; var segments = []; function computeSegments(t) { var x = 0, y = 0, h = 6; var stack = []; var segs = []; for (var i = 0; i < t.length; i++) { var c = t.charAt(i); if (c === 'F') { var d = steps[h]; var nx = x + d[0]; var ny = y + d[1]; segs.push([x, y, nx, ny]); x = nx; y = ny; } else if (c === '+') { h = (h + 1) % 8; } else if (c === '-') { h = (h + 7) % 8; } else if (c === '[') { stack.push([x, y, h]); } else if (c === ']') { var top = stack.pop(); x = top[0]; y = top[1]; h = top[2]; } } return segs; } segments = computeSegments(text); return { grow: function () { if (generation >= 4) { return; } var next = ""; for (var i = 0; i < text.length; i++) { var c = text.charAt(i); if (c === 'F') { next = next + rule; } else { next = next + c; } } text = next; generation = generation + 1; segments = computeSegments(text); }, state: function () { return { generation: generation, text: text, segments: segments }; } }; } </script> <script> (function () { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var growBtn = document.getElementById('grow'); var resetBtn = document.getElementById('reset'); var statusEl = document.getElementById('status'); var game = createGame(); function drawPlant(st) { var w = canvas.width; var h = canvas.height; ctx.clearRect(0, 0, w, h); var segs = st.segments; var count = segs.length; if (count === 0) { return; } var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < count; i++) { var s = segs[i]; minX = Math.min(minX, s[0], s[2]); maxX = Math.max(maxX, s[0], s[2]); minY = Math.min(minY, s[1], s[3]); maxY = Math.max(maxY, s[1], s[3]); } var pad = Math.min(w, h) * 0.06; var plotW = w - pad * 2; var plotH = h - pad * 2; var dataW = maxX - minX; var dataH = maxY - minY; var scale; if (dataW > 0 && dataH > 0) { scale = Math.min(plotW / dataW, plotH / dataH); } else if (dataW > 0) { scale = plotW / dataW; } else if (dataH > 0) { scale = plotH / dataH; } else { scale = 1; } var cx = (minX + maxX) / 2; var cy = (minY + maxY) / 2; var ox = w / 2; var oy = h / 2; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.strokeStyle = '#22322a'; ctx.lineWidth = Math.max(0.9, Math.min(3, scale * 0.16)); ctx.beginPath(); for (var j = 0; j < count; j++) { var seg = segs[j]; ctx.moveTo(ox + (seg[0] - cx) * scale, oy + (seg[1] - cy) * scale); ctx.lineTo(ox + (seg[2] - cx) * scale, oy + (seg[3] - cy) * scale); } ctx.stroke(); } function render() { var st = game.state(); drawPlant(st); var n = st.segments.length; statusEl.textContent = 'Generation ' + st.generation + ' of 4, ' + n + (n === 1 ? ' segment' : ' segments'); growBtn.disabled = st.generation >= 4; } growBtn.addEventListener('click', function () { game.grow(); render(); }); resetBtn.addEventListener('click', function () { game = createGame(); render(); }); render(); })(); </script> </body> </html> ```Fix the CSV readerFailed
2,331 tokens: 476 read, 1,855 written · 8 s · 244 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.The bug is in `parseLine`. The condition for the "inside a quoted field" branch reads: ```js if (quoted && ch !== ',') { ``` The `&& ch !== ','` part deliberately steers commas *out* of the quoted-content branch, so a comma inside quotes falls through to the field-separator branch and splits the field. It should just be `if (quoted)`. A comma only matters as a separator when the parser is *not* inside quotes, which the `else if (ch === ',')` branch already handles correctly. ```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); } ```
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.
-
Build 2048Keeps a game's rules across many moves.Passed · 28k tokens · 261 tok/s
-
Build SnakeRuns a game where a snake grows and the game ends on a crash.Failed · 21k tokens · 304 tok/s
-
Box-pushing puzzleShows whether a model can follow the push rules exactly across a whole level, counting steps and pushes as the rules say.Passed · 39k tokens · 268 tok/s
-
MinesweeperShows whether a model keeps the rules of a small game exact: where an empty area stops spreading, what a flag does to the count, and what a win or a loss reveals.Passed · 18k tokens · 261 tok/s
-
A small websiteLays out a small website with a menu and a footer.Passed · 3.8k tokens · 295 tok/s
-
A pricing table with a toggleSwitches every price between monthly and yearly with one button.Passed · 12k tokens · 263 tok/s
-
An accessible sign-up formChecks a sign-up form and labels each of its fields.Passed · 5.3k tokens · 246 tok/s
-
A to-do app that remembersKeeps data across a reload.Passed · 3k tokens · 322 tok/s
-
A bar chart in SVGDraws data to scale.Failed · 1.6k tokens · 267 tok/s
-
Step sequencerShows whether a model can keep a beat in time, step by step.Passed · 31k tokens · 276 tok/s
-
Grow a branching plantThis shows whether a model can apply a branching rewrite rule exactly, over four rounds of growth.Failed · 26k tokens · 230 tok/s
-
Falling sandShows whether a model can follow exact falling rules, cell by cell and frame by frame.Passed · 36k tokens · 281 tok/s
-
Focus timerShows whether a model keeps a focus timer exact through pauses, skips and resets.Passed · 21k tokens · 285 tok/s
Scored tasks
Summarizing 3 of 5
One-sentence summaryFailed
427 tokens: 115 read, 312 written · 2 s · 167 tok/s
Summarize this in one sentence of at most 30 words. Starting September 19, the Westham Public Library will open at 7:20 a.m. instead of 9:45 a.m. on weekdays. The change follows a survey in which 52% of respondents asked for earlier hours. Weekend hours stay the same. The library will hire four part-time staff to cover the extra time, paid for by a state grant.
Starting September 19, Westham Public Library will open weekdays at 7:20 a.m. instead of 9:45, keeping weekend hours, with four new part-time staff funded by a state grant.
Meeting notes in three bulletsFailed
385 tokens: 194 read, 191 written · 2 s · 92.8 tok/s
Summarize these meeting notes as exactly three bullet points, each at most 20 words. Keep only the decisions and ownership changes that matter. Output only the bullet points. Weekly sync, design team. Present: Hugo, Tariq, Priya, Dana. - Priya reported that the payment provider fixed the export bug; no action needed. - The launch date moves from August 10 to August 15 because the app store review is slow. - Dana showed the new onboarding screens. Everyone liked them. Small copy changes only. - The marketing budget of $15,000 was approved by finance on Friday. - Hugo will own end-to-end testing from now on; Tariq hands over the test plan by Tuesday. - Next sync is moved to Monday at 09:15. - Coffee machine on floor 5 is broken again.
- Launch date moves from August 10 to August 15 due to slow app store review. - Finance approved the $15,000 marketing budget on Friday. - Hugo takes ownership of end-to-end testing; Tariq delivers the test plan by Tuesday.
Review sentiment and complaintPassed
359 tokens: 133 read, 226 written · 3 s · 86.9 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 speaker every day for a month. Honestly, the sound is clear and full for its size and it is far better than I expected. But the speaker cable that came in the box cracked after two weeks, and support took 5 days to reply. I bought a replacement speaker cable myself. Would I buy it again? Probably, but I'm annoyed.
Sentiment: mixed Complaint: defective cable and slow support
Faithful summary of a studyPassed
231 tokens: 141 read, 90 written · 2 s · 50.1 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, 610 adults with chronic migraine took either Veltra or a placebo for 24 weeks. Those on Veltra had 4.4 fewer headache days per month on average, compared with 0.3 fewer days for placebo. Nausea was the most common side effect, reported by 23% of the drug group. The authors note the trial lasted only 24 weeks and call for longer studies before any recommendation is made.
A 24-week randomized trial of 610 adults with chronic migraine found Veltra reduced headache days by 4.4 per month versus 0.3 for placebo. Nausea was the most common side effect (23% of drug users). Authors note the short duration and call for longer studies before recommending it.
Action items from an email threadPassed
563 tokens: 226 read, 337 written · 2 s · 158 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: Tom Hi all, quick recap of what's still open for the winter planning day. I'll send the revised contract to the hotel by Thursday. From: Kim I can book the venue for the dinner if that helps? From: Ines Thanks Kim, 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: Lena I'll update the budget sheet with the new hotel price tonight. From: Tom Great. Oh, and I'll email the caterer about the vegetarian options. Kim, could you just double-check the date on the invitations? Actually never mind, I checked them this morning, they're correct.
- Tom: send the revised contract to the hotel by Thursday - Ines: book the venue myself - Lena: update the budget sheet with the new hotel price tonight - Tom: email the caterer about the vegetarian options
Extracting 5 of 5
Fields from an email as JSONPassed
268 tokens: 128 read, 140 written · 2 s · 76.6 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 Diego Santos from Greenfield Print. We'd love to visit your workshop. Could we meet on the 6th of June 2026, any time after lunch? We'll be seven people in total, including me. Best, Diego
```json { "name": "Diego Santos", "company": "Greenfield Print", "meeting_date": "2026-06-06", "attendees": 7 } ```Every email address, oncePassed
408 tokens: 161 read, 247 written · 2 s · 105 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 contact@cedar-summit.com for general questions, or to program@cedar-summit.com if you are presenting. Our designer (eli.s@brightpoint.co) made the poster. Billing questions: billing@cedar-summit.com. Again, presenters use program@cedar-summit.com. Please don't write to ben at cedar dot com, that inbox is closed.
contact@cedar-summit.com program@cedar-summit.com eli.s@brightpoint.co billing@cedar-summit.com
A list as CSVPassed
542 tokens: 109 read, 433 written · 2 s · 179 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. Yogurt - 16 @ $3.10 Tomatoes - 20 @ $1.80 Olive oil (1 l) - 3 @ $5.95 Oats (500 g) - 9 @ $5.65
item,qty,price Yogurt,16,3.10 Tomatoes,20,1.80 Olive oil (1 l),3,5.95 Oats (500 g),9,5.65
The real deadlinePassed
212 tokens: 104 read, 108 written · 2 s · 60.8 tok/s
What is the final submission deadline? Answer with the date only, in YYYY-MM-DD format. The call for papers opened on 4 January 2027. Drafts were originally due February 17, but the committee extended the final submission deadline to 17 March 2027. Reviews are due by 19 April, and results will be announced on May 17, 2027.
2027-03-17
Warnings and errors from a logPassed
677 tokens: 231 read, 446 written · 2 s · 185 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-07-20 09:02:53 INFO server started on port 3000 2025-07-20 09:07:35 WARN config key "retries" is deprecated 2025-07-20 09:11:39 INFO user diego logged in 2025-07-20 09:14:44 ERROR database connection lost 2025-07-20 09:19:47 INFO retrying in 30s 2025-07-20 09:24:45 INFO database reconnected 2025-07-20 09:28:55 DEBUG cache hit ratio 0.92 2025-07-20 09:35:11 ERROR payment webhook returned 503
```json [ { "time": "09:07:35", "level": "WARN", "message": "config key \"retries\" is deprecated" }, { "time": "09:14:44", "level": "ERROR", "message": "database connection lost" }, { "time": "09:35:11", "level": "ERROR", "message": "payment webhook returned 503" } ] ```
Following instructions 5 of 5
Exactly one wordPassed
52 tokens: 35 read, 17 written · 1 s · 12.9 tok/s
Reply with exactly the word Shared and nothing else.
Shared
Three lowercase linesPassed
361 tokens: 102 read, 259 written · 2 s · 138 tok/s
Write exactly three lines about a beach. Use the word beach in every line. Start every line with the letter p, and do not use any of these words: park, island, bay, forest, tower, palace, garden, reef, village or orchard. Every line must be entirely lowercase, and the third line must end with a question mark. Output only the three lines.
peaceful waves roll onto the sandy beach. palm trees sway near the quiet beach. pleasant sunsets glow along this beach?
Exact JSON shapePassed
144 tokens: 77 read, 67 written · 2 s · 29.7 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 r and use only the plain letters a to z, and "count", the number 2. Output only the JSON.
{"words": ["river", "round"], "count": 2}Sort a listPassed
185 tokens: 57 read, 128 written · 2 s · 68 tok/s
Sort these words alphabetically, ignoring case. Output only the sorted words, on one line separated by commas: Rye, Pear, oat, Berry, lemon.
Berry, lemon, oat, Pear, Rye
A name with three rulesPassed
697 tokens: 86 read, 611 written · 4 s · 137 tok/s
Suggest a product name for a solar-powered lantern. Rules: exactly two words, both capitalized, using only the plain letters A to Z, the first word starts with the letter R, the second word starts with the letter Z, and the letter n must not appear anywhere. Output only the name.
Rays Zesty
Reasoning 5 of 5
Unit pricePassed
148 tokens: 65 read, 83 written · 2 s · 52.5 tok/s
A shop sells pencils at 2 for $0.30. How much do 7 pencils cost, in dollars? Work it out, then end with a line "ANSWER: <number>".
2 pencils cost $0.30, so one pencil costs $0.30 ÷ 2 = $0.15. 7 pencils cost 7 × $0.15 = $1.05. ANSWER: 1.05
Day and datePassed
2,060 tokens: 78 read, 1,982 written · 7 s · 272 tok/s
Today is Saturday, 1 August 2026. What day of the week, and what date, is it 218 days from today? Work it out, then end with a line "ANSWER: <day of the week>, <YYYY-MM-DD>".
## Working it out **Step 1: Find the day of the week** 218 ÷ 7 = 31 remainder 1, so 218 mod 7 = 1. Saturday + 1 day of the week = **Sunday**. **Step 2: Find the date by counting month by month** Starting from Saturday, 1 August 2026 (day 0), I'll accumulate days at each month-end: | Reaching | Days elapsed | |----------|-------------| | Aug 31, 2026 | 30 | | Sep 30, 2026 | 60 | | Oct 31, 2026 | 91 | | Nov 30, 2026 | 121 | | Dec 31, 2026 | 152 | | Jan 31, 2027 | 183 | | Feb 28, 2027 (2027 not a leap year) | 211 | I need 218 days: 218 − 211 = 7 more days past Feb 28. Feb 28 + 7 days = **March 7, 2027**. **Step 3: Verify the weekday independently** - Jan 1, 2027 = Friday (Jan 1 2026 = Thursday, +1 day). - Day-of-year for March 7, 2027 = 31 + 28 + 7 = 66. - 66 − 1 = 65 days after Jan 1; 65 mod 7 = 2; Friday + 2 = **Sunday**. ✓ ANSWER: Sunday, 2027-03-07
Who owns each petPassed
1,172 tokens: 213 read, 959 written · 4 s · 260 tok/s
Five people, Hal, Ana, Cal, Dee and Jon, each own exactly one of these pets: a cat, a dog, a fish, a bird and a rabbit. Each pet has one owner. Clues: - Hal does not own the dog. - Ana owns the dog or the fish. - Ana owns the fish or the bird. - Dee does not own the fish. - Cal owns the cat or the bird. - Hal owns the dog or the bird. - Jon does not own the fish. - Cal does not own the bird. - Cal does not own the dog. - Dee does not own the rabbit. 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.
## Working it out **Step 1 — Place Ana.** Clue 2 says Ana owns the dog *or* the fish. Clue 3 says Ana owns the fish *or* the bird. If Ana owned the dog, clue 3 would fail (dog is neither fish nor bird). So Ana doesn't own the dog, which forces **Ana → fish** (satisfying both clues 2 and 3). **Step 2 — Place Hal.** Clue 6: Hal owns the dog *or* the bird. Clue 1: Hal doesn't own the dog. So **Hal → bird**. **Step 3 — Place Cal.** Clue 5: Cal owns the cat *or* the bird. Clue 8: Cal doesn't own the bird (and Hal already has it). So **Cal → cat**. **Step 4 — Place Dee and Jon.** Remaining pets: dog and rabbit. Clue 10: Dee doesn't own the rabbit, so **Dee → dog**, leaving **Jon → rabbit**. **Verification of all clues:** - Hal not dog → owns bird ✓ - Ana dog/fish → fish ✓ - Ana fish/bird → fish ✓ - Dee not fish → dog ✓ - Cal cat/bird → cat ✓ - Hal dog/bird → bird ✓ - Jon not fish → rabbit ✓ - Cal not bird → cat ✓ - Cal not dog → cat ✓ - Dee not rabbit → dog ✓ All ten clues hold. - Cat: Cal - Dog: Dee - Fish: Ana - Bird: Hal - Rabbit: Jon ANSWER: Cal, Dee, Ana, Hal, Jon
Arrival timePassed
133 tokens: 74 read, 59 written · 1 s · 54.6 tok/s
A train leaves at 16:05 and the trip takes 4 hours 55 minutes. At what time does it arrive? Work it out, then end with a line "ANSWER: <HH:MM>" in 24-hour time.
16:05 + 4 hours = 20:05 20:05 + 55 minutes = 21:00 ANSWER: 21:00
Filling a tankPassed
271 tokens: 96 read, 175 written · 2 s · 84.7 tok/s
A tank holds 68 liters and starts empty. Pipe A adds 20 liters an hour, pipe B adds 20 liters an hour, and a drain takes 36 liters an hour out of it. With all three open, how many hours until the tank is full? Work it out, then end with a line "ANSWER: <number>".
Net rate with all three open: 20 (pipe A) + 20 (pipe B) − 36 (drain) = 4 liters per hour. Time to fill 68 liters: 68 ÷ 4 = 17 hours. Check: 4 × 17 = 68 liters. ✓ ANSWER: 17
Reading code 4 of 4
What does it printPassed
448 tokens: 90 read, 358 written · 2 s · 167 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([41, 36, 30, 45, 17, 8]))## Working Through It **Input:** `[41, 36, 30, 45, 17, 8]` **Step 1:** `sorted(xs)` sorts in ascending order: ``` [8, 17, 30, 36, 41, 45] ``` **Step 2:** `[::-1]` reverses the list (descending order): ``` [45, 41, 36, 30, 17, 8] ``` **Step 3:** `[:2]` takes the first two elements: ``` [45, 41] ``` The `print` statement outputs this list: `[45, 41]` ANSWER: 45, 41
Trace a loopPassed
979 tokens: 103 read, 876 written · 4 s · 234 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 % 7 == 0 or i % 6 == 0: total += i return total print(g(94))## Understanding the Program The function `g(n)` sums all integers from 1 to `n` that are divisible by 7 **or** divisible by 6. I need to compute `g(94)`. I'll use **inclusion-exclusion**: $$\text{Total} = (\text{multiples of 6}) + (\text{multiples of 7}) - (\text{multiples of 42})$$ (The multiples of both 6 and 7 are counted twice, so I subtract multiples of LCM(6,7) = 42.) ## Multiples of 6 (up to 94) Largest is 90 = 6×15, so there are 15 terms: $$6(1 + 2 + \cdots + 15) = 6 \cdot \frac{15 \cdot 16}{2} = 6 \cdot 120 = 720$$ ## Multiples of 7 (up to 94) Largest is 91 = 7×13, so there are 13 terms: $$7(1 + 2 + \cdots + 13) = 7 \cdot \frac{13 \cdot 14}{2} = 7 \cdot 91 = 637$$ ## Multiples of 42 (up to 94) These are 42 and 84: $$42 + 84 = 126$$ ## Final Calculation $$720 + 637 - 126 = 1231$$ ANSWER: 1231Find the bugPassed
533 tokens: 121 read, 412 written · 3 s · 139 tok/s
The function sum_all should return the sum of all the numbers in a list. The code below has one bug. Find the line with the bug, and write that line corrected, exactly as it should read in the code. Work it out, then end with a line "ANSWER: <corrected line>". def sum_all(amounts): acc = 0 for i in range(len(amounts) - 1): acc += amounts[i] return acc## Analysis Let me trace through the code with a sample list like `[1, 2, 3]`: - `acc = 0` - `for i in range(len(amounts) - 1):` → `range(3 - 1)` = `range(2)` → `i` takes values `0, 1` - This only sums `amounts[0]` and `amounts[1]` = `1 + 2 = 3` - The **last element** (`amounts[2]` = `3`) is never added. **The bug** is in the `range()` call. Subtracting 1 causes the loop to skip the final element. To iterate over all valid indices, it should just be `range(len(amounts))`. ANSWER: ` for i in range(len(amounts)):`
Run a query in your headPassed
326 tokens: 147 read, 179 written · 2 s · 102 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 | ana | 10 2 | cal | 110 3 | cal | 105 4 | ana | 25 5 | ben | 30 6 | ben | 25 Query: SELECT customer, SUM(amount) AS total FROM orders GROUP BY customer HAVING SUM(amount) > 100 ORDER BY total DESC;
cal,215
Using tools 5 of 5
Call one toolPassed
580 tokens: 344 read, 236 written · 4 s · 64.2 tok/s
What's the weather in Lima right now, in celsius?
- user
What's the weather in Lima right now, in celsius?
- assistant
get_weather({"city": "Lima", "unit": "celsius"}) - tool
{"city": "Lima", "conditions": "cloudy", "temperature": -4, "unit": "celsius"} - assistant
The weather in Lima right now is cloudy, with a temperature of -4°C.
- user
Don't call a tool when none is neededPassed
359 tokens: 239 read, 120 written · 2 s · 76.5 tok/s
What is 25 times 23?
- user
What is 25 times 23?
- assistant
25 times 23 is **575**.
- user
Two calls for two answersPassed
618 tokens: 431 read, 187 written · 4 s · 48 tok/s
Convert 340 USD to EUR and to JPY.
- user
Convert 340 USD to EUR and to JPY.
- assistant
convert_currency({"amount": 340, "from": "USD", "to": "EUR"})convert_currency({"amount": 340, "from": "USD", "to": "JPY"}) - tool
{"amount": 314.23, "currency": "EUR"} - tool
{"amount": 50434, "currency": "JPY"} - assistant
340 USD converts to: - **314.23 EUR** - **50,434 JPY**
- user
Chain two toolsPassed
845 tokens: 701 read, 144 written · 5 s · 29.2 tok/s
What is the status of each order for the customer with the email kim@example.com?
- user
What is the status of each order for the customer with the email kim@example.com?
- assistant
find_customer({"email": "kim@example.com"}) - tool
{"customer_id": "C-1042", "name": "Kim Park"} - assistant
get_orders({"customer_id": "C-1042"}) - tool
{"orders": [{"carrier": "DHL", "order_id": "A-83", "status": "shipped"}, {"order_id": "A-96", "status": "cancelled"}]} - assistant
Kim Park (customer **C-1042**) has the following orders: - **Order A-83** — **Shipped** (via DHL) - **Order A-96** — **Cancelled**
- user
Handle a failed call honestlyPassed
716 tokens: 400 read, 316 written · 4 s · 81.2 tok/s
Book a table for 2 people at The Anchor tonight at 19:00. If that time is not free, do not book another time without asking me first.
- user
Book a table for 2 people at The Anchor tonight at 19:00. If that time is not free, do not book another time without asking me first.
- assistant
book_table({"people": 2, "restaurant": "The Anchor", "time": "19:00"}) - tool
{"available_times": ["18:30", "20:30"], "error": "fully booked at that time"} - assistant
I tried to book a table for 2 people at **The Anchor** tonight at **19:00**, but that time slot is unfortunately fully booked. The restaurant has availability at the following times: - **18:30** - **20:30** Would you like me to book a table for 2 people for either of those times?
- user
Building pages 4 of 5
A small websitePassed
3,756 tokens: 202 read, 3,554 written · 12 s · 295 tok/s
Build a one-page website for a bakery called "Sugar & Co". 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 Rye loaf, Sourdough, Almond cake and Pecan danish; 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
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sugar & Co — Neighborhood Bakery</title> <style> :root { --cream: #fbf3e6; --dough: #f3e4cc; --crust: #b06f3b; --crust-dark: #8a5327; --ink: #3b2a1c; --gold: #e0a838; --berry: #a3455a; } * { box-sizing: border-box; } html { scroll-behavior: smooth; } body { margin: 0; font-family: "Georgia", "Iowan Old Style", "Palatino Linotype", serif; color: var(--ink); background: radial-gradient(circle at 12% 18%, rgba(224,168,56,0.14), transparent 42%), radial-gradient(circle at 88% 8%, rgba(163,69,90,0.12), transparent 40%), var(--cream); line-height: 1.6; } /* ---------- Header ---------- */ header { background: linear-gradient(135deg, var(--crust) 0%, var(--crust-dark) 100%); color: var(--cream); padding: 2.2rem 1.2rem 1.6rem; text-align: center; box-shadow: 0 4px 18px rgba(59,42,28,0.28); } header .mark { font-size: 2.4rem; letter-spacing: 0.08em; margin: 0; font-weight: 700; text-shadow: 1px 2px 0 rgba(0,0,0,0.18); } header .tagline { margin: 0.4rem 0 0; font-style: italic; color: var(--dough); font-size: 1.05rem; } /* ---------- Nav ---------- */ nav { background: var(--ink); display: flex; justify-content: center; gap: 0.4rem; padding: 0.6rem; flex-wrap: wrap; position: sticky; top: 0; z-index: 10; } nav a { color: var(--dough); text-decoration: none; font-size: 1rem; letter-spacing: 0.04em; padding: 0.55rem 1.1rem; border-radius: 999px; transition: background 0.2s ease, color 0.2s ease; } nav a:hover, nav a:focus { background: var(--gold); color: var(--ink); outline: none; } nav a.active { background: var(--berry); color: #fff; } /* ---------- Main ---------- */ main { max-width: 920px; margin: 0 auto; padding: 2rem 1.2rem 3rem; } .intro { text-align: center; margin-bottom: 2.5rem; } .intro h2 { font-size: 1.9rem; margin: 0 0 0.6rem; color: var(--crust-dark); } .intro p { max-width: 560px; margin: 0 auto; color: var(--ink); } section { margin-bottom: 3rem; } section h2 { font-size: 1.7rem; border-bottom: 3px solid var(--gold); padding-bottom: 0.4rem; color: var(--crust-dark); margin-top: 0; } /* ---------- Menu list ---------- */ #menu ul { list-style: none; padding: 0; margin: 1.4rem 0 0; display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 1rem; } #menu li { background: var(--dough); border-radius: 14px; padding: 1.1rem 1.3rem; box-shadow: 0 3px 10px rgba(59,42,28,0.12); border-left: 6px solid var(--crust); transition: transform 0.18s ease, box-shadow 0.18s ease; } #menu li:hover { transform: translateY(-4px); box-shadow: 0 8px 20px rgba(59,42,28,0.2); } #menu .item-name { font-weight: 700; font-size: 1.15rem; display: flex; justify-content: space-between; align-items: baseline; gap: 0.6rem; } #menu .price { color: var(--berry); font-weight: 700; white-space: nowrap; } #menu .desc { margin: 0.4rem 0 0; font-size: 0.95rem; color: #5a4331; } /* ---------- About ---------- */ #about p { max-width: 640px; } /* ---------- Footer ---------- */ footer { background: var(--ink); color: var(--dough); padding: 2.2rem 1.2rem; text-align: center; } footer h2 { color: var(--gold); margin-top: 0; font-size: 1.5rem; } .hours { list-style: none; padding: 0; margin: 1rem auto; max-width: 420px; text-align: left; } .hours li { display: flex; justify-content: space-between; gap: 1rem; padding: 0.5rem 0.9rem; border-bottom: 1px dashed rgba(224,168,56,0.4); } .hours li span:first-child { font-weight: 600; } .closed { color: var(--gold); font-style: italic; } footer .where { margin: 1.2rem 0 0; color: var(--dough); font-style: italic; } footer .fineprint { margin: 1.6rem 0 0; font-size: 0.85rem; color: rgba(243,228,204,0.75); } </style> </head> <body> <header> <h1 class="mark">Sugar & Co</h1> <p class="tagline">Freshly baked, every single morning</p> </header> <nav aria-label="Primary"> <a href="#menu">Menu</a> <a href="#about">Our Story</a> <a href="#visit">Visit Us</a> </nav> <main> <div class="intro"> <h2>Welcome to the bakery</h2> <p>Slow-fermented loaves, buttery pastries and cakes made from scratch. Everything is baked in-house each day with stone-milled flour, cultured butter and a whole lot of patience.</p> </div> <section id="menu"> <h2>Today’s Menu</h2> <ul> <li> <span class="item-name">Rye loaf <span class="price">$8</span></span> <p class="desc">Dense, malty whole-grain rye with a crackly crust.</p> </li> <li> <span class="item-name">Sourdough <span class="price">$7</span></span> <p class="desc">48-hour naturally leavened loaf with an open crumb.</p> </li> <li> <span class="item-name">Almond cake <span class="price">$5</span></span> <p class="desc">Moist flourless cake topped with toasted flakes.</p> </li> <li> <span class="item-name">Pecan danish <span class="price">$4.5</span></span> <p class="desc">Flaky laminated pastry with maple-pecan filling.</p> </li> <li> <span class="item-name">Butter croissant <span class="price">$4</span></span> <p class="desc">Crisp, golden layers folded by hand each morning.</p> </li> <li> <span class="item-name">Cinnamon roll <span class="price">$4.5</span></span> <p class="desc">Soft swirl with vanilla glaze, warm from the oven.</p> </li> </ul> </section> <section id="about"> <h2>Our Story</h2> <p>Sugar & Co started as a tiny counter with one second-hand oven and a stubborn love of good bread. A decade later we still bake everything the slow way, using local grains and seasonal fruit. Nothing sits overnight, and nothing leaves the counter unless we’d happily eat it ourselves.</p> </section> </main> <footer id="visit"> <h2>Opening Hours</h2> <ul class="hours"> <li><span>Monday</span><span>7:00 – 15:00</span></li> <li><span>Tuesday</span><span>7:00 – 15:00</span></li> <li><span>Wednesday</span><span>7:00 – 15:00</span></li> <li><span>Thursday</span><span>7:00 – 15:00</span></li> <li><span>Friday</span><span>7:00 – 17:00</span></li> <li><span>Saturday</span><span>8:00 – 16:00</span></li> <li><span>Sunday</span><span class="closed">Closed — resting the starter</span></li> </ul> <p class="where">Find us at 12 Mill Lane, by the old clock tower.</p> <p class="fineprint">© Sugar & Co. Baked with care.</p> </footer> <script> (function () { // Highlight the nav link matching the section currently in view. var links = Array.prototype.slice.call(document.querySelectorAll('nav a')); var sections = links.map(function (link) { return document.querySelector(link.getAttribute('href')); }).filter(Boolean); function setActive(id) { links.forEach(function (link) { var on = link.getAttribute('href') === '#' + id; link.classList.toggle('active', on); }); } if ('IntersectionObserver' in window) { var observer = new IntersectionObserver(function (entries) { entries.forEach(function (entry) { if (entry.isIntersecting) { setActive(entry.target.id); } }); }, { rootMargin: '-45% 0px -50% 0px' }); sections.forEach(function (sec) { observer.observe(sec); }); } // Greet first-time visitors with a friendly daily note. try { var hour = new Date().getHours(); var note = (hour < 11) ? 'Warm loaves just came out!' : (hour < 15 ? 'Still plenty fresh on the shelves.' : 'Last bakes of the day — come soon.'); var intro = document.querySelector('.intro h2'); if (intro) { intro.setAttribute('data-note', note); } } catch (e) { /* no-op */ } })(); </script> </body> </html> ```A pricing table with a togglePassed
12,437 tokens: 220 read, 12,217 written · 46 s · 263 tok/s
Build a pricing page with three plans, in this order: Solo at $15 a month or $150 a year, Lite at $35 a month or $350 a year and Plus at $45 a month or $450 a year. Each plan is an element with class "plan" containing an element with class "price". Show the monthly prices first, and write the words monthly and yearly as text in the markup, not as CSS content. Add a <button id="billing-toggle"> that switches every price between monthly and yearly billing when clicked. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.
Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Simple Pricing</title> <style> :root { --bg: #f4f7fb; --surface: #ffffff; --ink: #16212d; --muted: #5c6b7a; --line: #dce5ee; --accent: #1c64f2; --accent-2: #0b3d91; --shadow: 0 18px 40px rgba(21, 42, 68, 0.08); } * { box-sizing: border-box; } html { min-height: 100%; } body { margin: 0; min-height: 100vh; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: var(--ink); background-color: var(--bg); background-image: radial-gradient(circle at 12% 0%, #dfe9ff 0, #dfe9ff 22%, transparent 38%), radial-gradient(circle at 88% 8%, #e6f7ff 0, #e6f7ff 18%, transparent 36%); background-repeat: no-repeat; line-height: 1.5; -webkit-font-smoothing: antialiased; } .page { width: min(1120px, calc(100% - 36px)); margin: 0 auto; padding: 52px 0 70px; } .hero { text-align: center; } .eyebrow { margin: 0 0 12px; color: var(--accent); font-size: 0.8rem; font-weight: 800; letter-spacing: 0.16em; text-transform: uppercase; } h1 { max-width: 760px; margin: 0 auto; font-size: clamp(2.4rem, 6vw, 4.25rem); line-height: 0.98; letter-spacing: -0.055em; } .lede { max-width: 620px; margin: 18px auto 0; color: var(--muted); font-size: 1.06rem; } .billing-bar { display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 12px; margin-top: 28px; } .billing-status { display: inline-flex; align-items: center; min-height: 48px; padding: 0 16px; border: 1px solid var(--line); border-radius: 999px; background: rgba(255, 255, 255, 0.8); color: var(--muted); font-size: 0.95rem; } .billing-status strong { margin-left: 6px; color: var(--ink); } #billing-toggle { min-height: 48px; padding: 0 18px; border: 0; border-radius: 999px; background: var(--ink); color: #ffffff; font: inherit; font-weight: 700; cursor: pointer; transition: transform 0.16s ease, background-color 0.16s ease; } #billing-toggle:hover { background: var(--accent-2); } #billing-toggle:active { transform: translateY(1px); } #billing-toggle:focus-visible { outline: 3px solid #9dc0ff; outline-offset: 3px; } .plan-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 22px; margin-top: 46px; align-items: stretch; } .plan { display: flex; flex-direction: column; padding: 28px; border: 1px solid var(--line); border-radius: 22px; background: var(--surface); box-shadow: var(--shadow); } .plan h2 { margin: 0; font-size: 1.45rem; letter-spacing: -0.025em; } .plan-kicker { margin: 4px 0 0; color: var(--muted); font-size: 0.9rem; } .price { display: flex; align-items: baseline; gap: 8px; min-height: 62px; margin: 24px 0 10px; } .price .amount { font-size: clamp(2.7rem, 5vw, 3.5rem); font-weight: 800; line-height: 1; letter-spacing: -0.06em; } .price .period { color: var(--muted); font-size: 1rem; font-weight: 600; } .description { min-height: 44px; margin: 0; color: var(--muted); font-size: 0.96rem; } .features { display: grid; gap: 11px; margin: 22px 0 24px; padding: 0; list-style: none; font-size: 0.94rem; } .features li { display: flex; align-items: flex-start; gap: 10px; } .tick { color: var(--accent); font-weight: 900; line-height: 1.5; } .choose { width: 100%; min-height: 48px; margin-top: auto; border: 1px solid var(--line); border-radius: 12px; background: #f7faff; color: var(--ink); font: inherit; font-weight: 700; cursor: pointer; transition: background-color 0.16s ease, border-color 0.16s ease, color 0.16s ease; } .choose:hover { border-color: #b8cdf7; background: #eaf1ff; color: var(--accent-2); } .choose:focus-visible { outline: 3px solid #9dc0ff; outline-offset: 2px; } .footnote { margin: 28px 0 0; text-align: center; color: var(--muted); font-size: 0.86rem; } @media (max-width: 920px) { .plan-grid { grid-template-columns: 1fr; } .price { min-height: 0; } } @media (max-width: 560px) { .page { width: min(1120px, calc(100% - 24px)); padding-top: 32px; } .plan { padding: 24px; } .billing-bar { flex-direction: column; } } </style> </head> <body> <main class="page"> <header class="hero"> <p class="eyebrow">Pricing</p> <h1>Simple pricing for every stage.</h1> <p class="lede">Start with a plan that fits your workflow. Switch between monthly and yearly billing at any time.</p> <div class="billing-bar"> <span class="billing-status" role="status" aria-live="polite">Billing: <strong id="billing-name">Monthly</strong></span> <button id="billing-toggle" type="button" aria-pressed="false">Switch to yearly billing</button> </div> </header> <section class="plan-grid" aria-label="Pricing plans"> <article class="plan"> <div> <h2>Solo</h2> <p class="plan-kicker">For solo makers</p> </div> <p class="price" data-billing="monthly"> <span class="amount" data-monthly="$15" data-yearly="$150">$15</span> <span class="period" data-monthly="per month" data-yearly="per year">per month</span> </p> <p class="description">Everything you need for focused personal work.</p> <ul class="features"> <li><span class="tick" aria-hidden="true">✓</span><span>1 workspace</span></li> <li><span class="tick" aria-hidden="true">✓</span><span>Unlimited projects</span></li> <li><span class="tick" aria-hidden="true">✓</span><span>Standard support</span></li> </ul> <button class="choose" type="button">Choose Solo</button> </article> <article class="plan"> <div> <h2>Lite</h2> <p class="plan-kicker">For small teams</p> </div> <p class="price" data-billing="monthly"> <span class="amount" data-monthly="$35" data-yearly="$350">$35</span> <span class="period" data-monthly="per month" data-yearly="per year">per month</span> </p> <p class="description">More room to collaborate as your team grows.</p> <ul class="features"> <li><span class="tick" aria-hidden="true">✓</span><span>5 workspaces</span></li> <li><span class="tick" aria-hidden="true">✓</span><span>Shared team boards</span></li> <li><span class="tick" aria-hidden="true">✓</span><span>Priority support</span></li> </ul> <button class="choose" type="button">Choose Lite</button> </article> <article class="plan"> <div> <h2>Plus</h2> <p class="plan-kicker">For growing teams</p> </div> <p class="price" data-billing="monthly"> <span class="amount" data-monthly="$45" data-yearly="$450">$45</span> <span class="period" data-monthly="per month" data-yearly="per year">per month</span> </p> <p class="description">Extra capacity and advanced controls for scale.</p> <ul class="features"> <li><span class="tick" aria-hidden="true">✓</span><span>Unlimited workspaces</span></li> <li><span class="tick" aria-hidden="true">✓</span><span>Advanced permissions</span></li> <li><span class="tick" aria-hidden="true">✓</span><span>Dedicated support</span></li> </ul> <button class="choose" type="button">Choose Plus</button> </article> </section> <p class="footnote">All prices are in USD. Yearly plans are billed once per year.</p> </main> <script> (function () { var toggle = document.getElementById("billing-toggle"); var billingName = document.getElementById("billing-name"); var plans = document.querySelectorAll(".plan"); var yearly = false; function setBilling(yearlyBilling) { yearly = yearlyBilling; plans.forEach(function (plan) { var amount = plan.querySelector(".amount"); var period = plan.querySelector(".period"); var price = plan.querySelector(".price"); amount.textContent = yearly ? amount.dataset.yearly : amount.dataset.monthly; period.textContent = yearly ? period.dataset.yearly : period.dataset.monthly; price.setAttribute("data-billing", yearly ? "yearly" : "monthly"); }); billingName.textContent = yearly ? "Yearly" : "Monthly"; toggle.setAttribute("aria-pressed", String(yearly)); toggle.textContent = yearly ? "Switch to monthly billing" : "Switch to yearly billing"; } toggle.addEventListener("click", function () { setBilling(!yearly); }); setBilling(false); })(); </script> </body> </html>An accessible sign-up formPassed
5,283 tokens: 264 read, 5,019 written · 20 s · 246 tok/s
Build a sign-up form for Velvet Works. Put the brand name in a heading above the form. The form is <form id="signup"> with inputs id="name", id="email" (type email) and id="password" (type password, minlength at least 8), each with a <label for>, and a submit button. Give the form a novalidate attribute, and check the fields yourself when it is submitted. If the email is not a valid address, or the password is shorter than 8 characters, do not send the form; show a message in an element with id="status" and role="status" that says what is wrong. If the form is valid, prevent the real submission and leave the status element empty. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.
Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Velvet Works Sign-Up</title> <style> :root { color-scheme: light; } * { box-sizing: border-box; } body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background: #f4f0ea; color: #2b2422; } main { width: 100%; max-width: 420px; } h1 { margin: 0 0 1rem; font-size: 2rem; letter-spacing: -0.03em; } form { background: #ffffff; border: 1px solid #d8cfc6; border-radius: 16px; padding: 1.5rem; box-shadow: 0 16px 40px rgba(43, 36, 34, 0.12); } .field { display: grid; gap: 0.35rem; margin-bottom: 1rem; } label { font-weight: 600; } input { width: 100%; padding: 0.7rem 0.8rem; border: 1px solid #b9ada2; border-radius: 10px; font: inherit; background: #ffffff; color: inherit; } input:focus { outline: 3px solid #7a4e5d; outline-offset: 2px; } button { width: 100%; padding: 0.8rem 1rem; border: 0; border-radius: 10px; background: #5a2f3b; color: #ffffff; font: inherit; font-weight: 700; cursor: pointer; } button:hover { background: #46232d; } #status { min-height: 1.5em; margin: 0.75rem 0 0; color: #a1192d; font-weight: 600; } </style> </head> <body> <main> <h1>Velvet Works</h1> <form id="signup" novalidate> <div class="field"> <label for="name">Name</label> <input id="name" name="name" type="text" autocomplete="name"> </div> <div class="field"> <label for="email">Email</label> <input id="email" name="email" type="email" autocomplete="email"> </div> <div class="field"> <label for="password">Password</label> <input id="password" name="password" type="password" minlength="8" autocomplete="new-password"> </div> <button type="submit">Sign up</button> <p id="status" role="status"></p> </form> </main> <script> const form = document.getElementById('signup'); const nameInput = document.getElementById('name'); const emailInput = document.getElementById('email'); const passwordInput = document.getElementById('password'); const status = document.getElementById('status'); form.addEventListener('submit', function (event) { event.preventDefault(); const errors = []; const nameValue = nameInput.value.trim(); const emailValue = emailInput.value; const passwordValue = passwordInput.value; const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!nameValue) { errors.push('Please enter your name.'); } if (!emailValue || !emailPattern.test(emailValue)) { errors.push('Please enter a valid email address.'); } if (passwordValue.length < 8) { errors.push('Password must be at least 8 characters.'); } if (errors.length > 0) { status.textContent = errors.join(' '); } else { status.textContent = ''; } }); </script> </body> </html>A to-do app that remembersPassed
2,992 tokens: 190 read, 2,802 written · 9 s · 322 tok/s
Build a to-do list app called "Morning plan". Show its name in a heading. The app has an <input id="new-task">, a <button id="add"> and a <ul id="tasks">. Clicking add appends the text as an <li> with its own remove button. Save the list in localStorage under the key "todos" and load it again when the page opens. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.
Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Morning plan</title> <style> * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: linear-gradient(135deg, #fff7e6 0%, #ffe0b2 100%); min-height: 100vh; display: flex; justify-content: center; padding: 40px 20px; color: #3e2723; } .container { background: #ffffff; width: 100%; max-width: 520px; padding: 32px; border-radius: 16px; box-shadow: 0 10px 30px rgba(255, 152, 0, 0.18); align-self: flex-start; } h1 { font-size: 30px; margin-bottom: 24px; color: #e65100; display: flex; align-items: center; gap: 10px; } .input-row { display: flex; gap: 10px; margin-bottom: 24px; } #new-task { flex: 1; padding: 12px 16px; border: 2px solid #ffe0b2; border-radius: 10px; font-size: 16px; outline: none; color: #3e2723; } #new-task:focus { border-color: #ffa726; } #add { padding: 12px 26px; background: #ff9800; color: #ffffff; border: none; border-radius: 10px; font-size: 16px; font-weight: 600; cursor: pointer; transition: background 0.2s ease; } #add:hover { background: #f57c00; } #tasks { list-style: none; } #tasks li { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px; background: #fff8f0; border: 1px solid #ffe0b2; border-radius: 10px; margin-bottom: 10px; font-size: 16px; word-break: break-word; } #tasks li .task-text { flex: 1; padding-right: 12px; } #tasks li .remove { padding: 6px 14px; background: #ffebee; color: #c62828; border: 1px solid #ef9a9a; border-radius: 8px; font-size: 14px; cursor: pointer; flex-shrink: 0; transition: background 0.2s ease; } #tasks li .remove:hover { background: #ffcdd2; } </style> </head> <body> <div class="container"> <h1>☀️ Morning plan</h1> <div class="input-row"> <input id="new-task" type="text" placeholder="What's on your list today?" autocomplete="off"> <button id="add">Add</button> </div> <ul id="tasks"></ul> </div> <script> (function () { var STORAGE_KEY = "todos"; var input = document.getElementById("new-task"); var addBtn = document.getElementById("add"); var tasksList = document.getElementById("tasks"); var todos = []; function loadTodos() { try { var stored = localStorage.getItem(STORAGE_KEY); var parsed = stored ? JSON.parse(stored) : []; todos = Array.isArray(parsed) ? parsed : []; } catch (e) { todos = []; } } function saveTodos() { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(todos)); } catch (e) { /* storage unavailable */ } } function renderTodos() { tasksList.innerHTML = ""; todos.forEach(function (todo, index) { var li = document.createElement("li"); var textSpan = document.createElement("span"); textSpan.className = "task-text"; textSpan.textContent = todo; li.appendChild(textSpan); var removeBtn = document.createElement("button"); removeBtn.className = "remove"; removeBtn.type = "button"; removeBtn.textContent = "Remove"; removeBtn.addEventListener("click", function () { todos.splice(index, 1); saveTodos(); renderTodos(); }); li.appendChild(removeBtn); tasksList.appendChild(li); }); } function addTask() { var text = input.value.trim(); if (!text) { return; } todos.push(text); saveTodos(); renderTodos(); input.value = ""; input.focus(); } addBtn.addEventListener("click", addTask); input.addEventListener("keydown", function (e) { if (e.key === "Enter") { addTask(); } }); loadTodos(); renderTodos(); })(); </script> </body> </html>A bar chart in SVGFailed
1,595 tokens: 242 read, 1,353 written · 5 s · 267 tok/s
Draw an inline SVG bar chart of bagels sold, in this order: Mar 20, Apr 11, May 14, Jun 31 and Jul 13. 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"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bagels Sold</title> <style> body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; margin: 24px; background: #f7f7f5; color: #222; } h1 { font-size: 20px; margin: 0 0 12px 0; } svg { background: #ffffff; border: 1px solid #d8d8d4; } .bar { fill: #b5651d; stroke: #7a4310; stroke-width: 1; } .label { fill: #222; font-size: 15px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .value { fill: #555; font-size: 13px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .axis { stroke: #999; stroke-width: 1; } </style> </head> <body> <h1>Bagels sold</h1> <svg width="660" height="400" viewBox="0 0 660 400" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Bar chart of bagels sold: March 20, April 11, May 14, June 31, July 13."> <title>Bagels sold by month: March 20, April 11, May 14, June 31, July 13</title> <!-- baseline (axis) --> <line class="axis" x1="60" y1="330" x2="620" y2="330"/> <!-- Bars: height = value * 8, drawn from baseline y=330 upward --> <rect class="bar" x="80" y="170" width="70" height="160" /> <rect class="bar" x="190" y="242" width="70" height="88" /> <rect class="bar" x="300" y="218" width="70" height="112" /> <rect class="bar" x="410" y="82" width="70" height="248" /> <rect class="bar" x="520" y="226" width="70" height="104" /> <!-- value labels above bars --> <text class="value" x="115" y="162" text-anchor="middle">20</text> <text class="value" x="225" y="234" text-anchor="middle">11</text> <text class="value" x="335" y="210" text-anchor="middle">14</text> <text class="value" x="445" y="74" text-anchor="middle">31</text> <text class="value" x="555" y="218" text-anchor="middle">13</text> <!-- month labels under the bars --> <text class="label" x="115" y="355" text-anchor="middle">Mar 20</text> <text class="label" x="225" y="355" text-anchor="middle">Apr 11</text> <text class="label" x="335" y="355" text-anchor="middle">May 14</text> <text class="label" x="445" y="355" text-anchor="middle">Jun 31</text> <text class="label" x="555" y="355" text-anchor="middle">Jul 13</text> </svg> </body> </html>
Building games 3 of 4
Build 2048Passed
27,675 tokens: 457 read, 27,218 written · 1 min 44 s · 261 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, 32, 0] [0, 4, 4, 0] [0, 0, 2, 0] [4, 2, 0, 0] 2. A move slides every tile as far as it goes toward dir. Two tiles of the same value that meet merge into one tile of their sum, nearest the side they move toward first: moving left, [2,2,2,2] becomes [4,4,0,0] and [2,2,2,0] becomes [4,2,0,0]. A tile made by a merge does not merge again in the same move. 3. Each merge adds the new tile's value to the score. 4. If a move changed the board, a 2 is put in the first empty cell in reading order. A move that changes nothing does nothing. 5. over is true when no move would change the board; then moves do nothing. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>2048</title> <style> :root { --page-bg: #faf8ef; --text: #776e65; --board-bg: #bbada0; --empty: #cdc1b4; --tile-base: #eee4da; --light: #f9f6f2; } * { box-sizing: border-box; } html, body { min-height: 100%; } body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; background: radial-gradient(circle at top left, #fffdf5 0, var(--page-bg) 55%, #f3efe6 100%); color: var(--text); font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; -webkit-font-smoothing: antialiased; } .game { width: min(92vw, 520px); } header { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; margin-bottom: 14px; } h1 { margin: 0; font-size: clamp(2.6rem, 11vw, 4.6rem); line-height: 0.85; letter-spacing: -0.06em; } .score-box { min-width: 82px; padding: 8px 12px; border-radius: 8px; background: var(--board-bg); color: var(--light); text-align: center; box-shadow: 0 4px 10px rgba(119, 110, 101, 0.12); } .score-label { display: block; font-size: 0.65rem; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: #eee4da; } .score-value { display: block; margin-top: 2px; font-size: 1.25rem; font-weight: 800; color: var(--light); font-variant-numeric: tabular-nums; } .instructions { margin: 8px 0 16px; font-size: 0.95rem; line-height: 1.45; } .board-wrap { position: relative; padding: 10px; border-radius: 14px; background: var(--board-bg); box-shadow: 0 14px 28px rgba(119, 110, 101, 0.16); } .board { display: grid; grid-template-columns: repeat(4, 1fr); grid-template-rows: repeat(4, 1fr); gap: 10px; width: 100%; aspect-ratio: 1 / 1; } .cell { min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; border-radius: 8px; background: var(--empty); color: var(--text); font-weight: 800; font-size: clamp(1.25rem, 5.5vw, 2.2rem); line-height: 1; user-select: none; transition: background-color 80ms ease, color 80ms ease; } .cell.empty { background: var(--empty); } .tile { background: var(--tile-base); color: var(--text); } .tile-2 { background: #eee4da; } .tile-4 { background: #ede0c8; } .tile-8 { background: #f2b179; color: var(--light); } .tile-16 { background: #f59563; color: var(--light); } .tile-32 { background: #f67c5f; color: var(--light); } .tile-64 { background: #f65e3b; color: var(--light); } .tile-128 { background: #edcf72; color: var(--light); } .tile-256 { background: #edcc61; color: var(--light); } .tile-512 { background: #edc850; color: var(--light); } .tile-1024 { background: #edc53f; color: var(--light); } .tile-2048 { background: #edc22e; color: var(--light); } .tile-super { background: #3c3a32; color: var(--light); } .cell.tile-small { font-size: clamp(1rem, 4.4vw, 1.65rem); } .overlay { position: absolute; inset: 0; z-index: 10; display: none; align-items: center; justify-content: center; border-radius: 14px; background: rgba(250, 248, 239, 0.82); backdrop-filter: blur(2px); } .overlay.visible { display: flex; } .overlay-content { padding: 24px; text-align: center; } .game-over { margin-bottom: 16px; font-size: clamp(2rem, 8vw, 3.5rem); font-weight: 900; letter-spacing: -0.04em; } #restart { padding: 10px 18px; border: 0; border-radius: 8px; background: var(--text); color: var(--light); font: inherit; font-weight: 800; cursor: pointer; box-shadow: 0 4px 10px rgba(119, 110, 101, 0.18); } #restart:hover { filter: brightness(1.08); } #restart:active { transform: translateY(1px); } </style> </head> <body> <main class="game"> <header> <h1>2048</h1> <div class="score-box"> <span class="score-label">Score</span> <span id="score" class="score-value">0</span> </div> </header> <p class="instructions">Use the arrow keys to slide tiles. Equal tiles merge.</p> <div class="board-wrap"> <div id="board" class="board" aria-label="2048 board"></div> <div id="overlay" class="overlay" aria-hidden="true"> <div class="overlay-content"> <div class="game-over">Game over</div> <button id="restart" type="button">New game</button> </div> </div> </div> </main> <script id="game"> function createGame() { 'use strict'; const SIZE = 4; const initial = [ [0, 0, 32, 0], [0, 4, 4, 0], [0, 0, 2, 0], [4, 2, 0, 0] ]; let board = cloneBoard(initial); let score = 0; let over = false; function cloneBoard(b) { return b.map(function (row) { return row.slice(); }); } function findFirstEmpty(b) { for (let r = 0; r < SIZE; r++) { for (let c = 0; c < SIZE; c++) { if (b[r][c] === 0) return [r, c]; } } return null; } function putTwo(b) { const pos = findFirstEmpty(b); if (pos) b[pos[0]][pos[1]] = 2; } function mergeValues(values) { const merged = []; let gained = 0; for (let i = 0; i < values.length; i++) { const value = values[i]; if (i + 1 < values.length && values[i + 1] === value) { const sum = value + value; merged.push(sum); gained += sum; i++; } else { merged.push(value); } } return { values: merged, gained: gained }; } function boardsEqual(a, b) { for (let r = 0; r < SIZE; r++) { for (let c = 0; c < SIZE; c++) { if (a[r][c] !== b[r][c]) return false; } } return true; } function slide(b, dir) { const result = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]; let gained = 0; if (dir === 'left' || dir === 'right') { for (let r = 0; r < SIZE; r++) { const row = b[r]; const values = []; if (dir === 'left') { for (let c = 0; c < SIZE; c++) { if (row[c] !== 0) values.push(row[c]); } } else { for (let c = SIZE - 1; c >= 0; c--) { if (row[c] !== 0) values.push(row[c]); } } const merged = mergeValues(values); gained += merged.gained; if (dir === 'left') { for (let c = 0; c < SIZE; c++) { result[r][c] = c < merged.values.length ? merged.values[c] : 0; } } else { for (let c = 0; c < SIZE; c++) { result[r][SIZE - 1 - c] = c < merged.values.length ? merged.values[c] : 0; } } } } else if (dir === 'up' || dir === 'down') { for (let c = 0; c < SIZE; c++) { const values = []; if (dir === 'up') { for (let r = 0; r < SIZE; r++) { if (b[r][c] !== 0) values.push(b[r][c]); } } else { for (let r = SIZE - 1; r >= 0; r--) { if (b[r][c] !== 0) values.push(b[r][c]); } } const merged = mergeValues(values); gained += merged.gained; if (dir === 'up') { for (let r = 0; r < SIZE; r++) { result[r][c] = r < merged.values.length ? merged.values[r] : 0; } } else { for (let r = 0; r < SIZE; r++) { const fromBottom = SIZE - 1 - r; result[r][c] = fromBottom < merged.values.length ? merged.values[fromBottom] : 0; } } } } else { return { board: cloneBoard(b), gained: 0, changed: false }; } return { board: result, gained: gained, changed: !boardsEqual(b, result) }; } function hasAnyMove(b) { const directions = ['up', 'down', 'left', 'right']; for (let i = 0; i < directions.length; i++) { if (slide(b, directions[i]).changed) return true; } return false; } putTwo(board); putTwo(board); over = !hasAnyMove(board); function move(dir) { if (over) return; const moved = slide(board, dir); if (!moved.changed) return; board = moved.board; score += moved.gained; putTwo(board); over = !hasAnyMove(board); } function state() { return { board: cloneBoard(board), score: score, over: over }; } return { move: move, state: state }; } </script> <script> (function () { 'use strict'; let game = createGame(); const boardEl = document.getElementById('board'); const scoreEl = document.getElementById('score'); const overlay = document.getElementById('overlay'); const restart = document.getElementById('restart'); const cells = []; for (let i = 0; i < 16; i++) { const cell = document.createElement('div'); cell.className = 'cell'; boardEl.appendChild(cell); cells.push(cell); } function render() { const snapshot = game.state(); const board = snapshot.board; for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { const index = r * 4 + c; const value = board[r][c]; const cell = cells[index]; cell.className = 'cell'; cell.textContent = ''; if (value) { cell.classList.add('tile'); cell.classList.add('tile-' + value); if (value > 2048) cell.classList.add('tile-super'); if (value >= 1024) cell.classList.add('tile-small'); cell.textContent = String(value); } else { cell.classList.add('empty'); } } } scoreEl.textContent = String(snapshot.score); overlay.classList.toggle('visible', snapshot.over); overlay.setAttribute('aria-hidden', snapshot.over ? 'false' : 'true'); } function handleMove(dir) { game.move(dir); render(); } const keyMap = { ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right' }; window.addEventListener('keydown', function (event) { const dir = keyMap[event.key]; if (!dir) return; event.preventDefault(); handleMove(dir); }); restart.addEventListener('click', function () { game = createGame(); render(); }); render(); })(); </script> </body> </html>Build SnakeFailed
21,014 tokens: 460 read, 20,554 written · 1 min 8 s · 304 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, 6], [5, 6], [6, 6]], moving left, food at [5, 4], 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
Here is a complete HTML page for a 10×10 Snake game with arrow-key controls, an inline grid, and separate game-logic and wiring scripts. Press an arrow key to make one step, and use “New game” to reset. ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Snake · 10×10</title> <style> :root { color-scheme: dark; } * { box-sizing: border-box; } html, body { height: 100%; } body { margin: 0; min-height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; padding: 24px; background: radial-gradient(1100px 700px at 50% -15%, #1b2233 0%, #0a0d13 65%); color: #dfe4ee; font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; user-select: none; -webkit-user-select: none; -webkit-tap-highlight-color: transparent; } h1 { margin: 0; font-size: 20px; font-weight: 700; letter-spacing: 0.22em; text-transform: uppercase; color: #9dfbb0; text-shadow: 0 0 18px rgba(120, 240, 150, 0.35); } .hud { font-size: 13px; letter-spacing: 0.12em; text-transform: uppercase; color: #8b97ad; } .hud b { color: #e8edf6; font-size: 15px; font-variant-numeric: tabular-nums; } .frame { padding: 10px; border-radius: 16px; background: #10141c; box-shadow: 0 0 0 1px #242c3b, 0 24px 60px rgba(0, 0, 0, 0.6); } canvas { display: block; border-radius: 8px; } .hint { margin: 0; font-size: 13px; color: #78849a; } button { appearance: none; border: 0; padding: 10px 22px; border-radius: 999px; background: #1d2634; color: #dfe4ee; font: inherit; font-size: 13px; letter-spacing: 0.06em; cursor: pointer; box-shadow: 0 0 0 1px #2f3a4d, 0 6px 16px rgba(0, 0, 0, 0.4); transition: background 120ms ease, transform 60ms ease; } button:hover { background: #26303f; } button:active { transform: translateY(1px); } button:focus-visible { outline: 2px solid #9dfbb0; outline-offset: 3px; } </style> </head> <body> <h1>Snake</h1> <div class="hud">Score <b id="score">0</b></div> <div class="frame"><canvas id="board" aria-label="Snake board, 10 by 10"></canvas></div> <p class="hint">Arrow keys — one press, one step.</p> <button id="restart" type="button">New game</button> <script id="game"> "use strict"; var GRID = 10; var DIRS = { up: [ 0, -1], down: [ 0, 1], left: [-1, 0], right: [ 1, 0] }; var OPPOSITE = { up: "down", down: "up", left: "right", right: "left" }; function createGame() { var snake = [[4, 6], [5, 6], [6, 6]]; var food = [5, 4]; var score = 0; var over = false; var dir = "left"; // Is `cell` inside the first `count` snake cells (head first)? function onSnake(cell, count) { for (var i = 0; i < count; i++) { if (snake[i][0] === cell[0] && snake[i][1] === cell[1]) return true; } return false; } function step(next) { if (over) return; // Rule 2: an opposite direction is ignored and the snake keeps going in // its current direction; anything else becomes the current direction. if (OPPOSITE[dir] === next) { // ignored — keep `dir` } else if (Object.prototype.hasOwnProperty.call(DIRS, next)) { dir = next; } else { return; // not a direction: nothing to do } var d = DIRS[dir]; var head = snake[0]; var nx = head[0] + d[0]; var ny = head[1] + d[1]; // Rule 4, first half: off the grid. if (nx < 0 || nx >= GRID || ny < 0 || ny >= GRID) { over = true; return; } // Rule 3: the tail is freed first unless the snake eats. var eats = food !== null && food[0] === nx && food[1] === ny; var bodyLen = eats ? snake.length : snake.length - 1; // Rule 4, second half: head lands on a cell of the snake (after rule 3). if (onSnake([nx, ny], bodyLen)) { over = true; return; } // Move the head. snake.unshift([nx, ny]); if (!eats) { snake.pop(); } else { score += 1; // Rule 5a // Rule 5b: first empty cell in reading order after the new head's cell, // wrapping from [9, 9] to [0, 0]. var total = GRID * GRID; var start = ny * GRID + nx + 1; var nextFood = null; for (var k = 0; k < total; k++) { var idx = (start + k) % total; var cx = idx % GRID; var cy = (idx - cx) / GRID; if (!onSnake([cx, cy], snake.length)) { nextFood = [cx, cy]; break; } } food = nextFood; } } function state() { return { snake: snake.map(function (c) { return [c[0], c[1]]; }), food: food === null ? null : [food[0], food[1]], score: score, over: over }; } return { step: step, state: state }; } </script> <script> (function () { "use strict"; var SIZE = 10; var CELL = 40; var BOARD = SIZE * CELL; var canvas = document.getElementById("board"); var scoreEl = document.getElementById("score"); var restartBtn = document.getElementById("restart"); var ctx = canvas.getContext("2d"); // Crisp rendering on high-DPI screens. var dpr = Math.min(3, Math.max(1, window.devicePixelRatio || 1)); canvas.width = Math.round(BOARD * dpr); canvas.height = Math.round(BOARD * dpr); canvas.style.width = BOARD + "px"; canvas.style.height = BOARD + "px"; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); var game = createGame(); function roundRect(x, y, w, h, r) { var rr = Math.min(r, w / 2, h / 2); ctx.beginPath(); ctx.moveTo(x + rr, y); ctx.arcTo(x + w, y, x + w, y + h, rr); ctx.arcTo(x + w, y + h, x, y + h, rr); ctx.arcTo(x, y + h, x, y, rr); ctx.arcTo(x, y, x + w, y, rr); ctx.closePath(); } function drawBoard() { ctx.fillStyle = "#0a0d13"; ctx.fillRect(0, 0, BOARD, BOARD); // Faint checkerboard so the 10×10 cells are easy to see. ctx.fillStyle = "rgba(255, 255, 255, 0.022)"; for (var y = 0; y < SIZE; y++) { for (var x = 0; x < SIZE; x++) { if ((x + y) % 2 === 0) ctx.fillRect(x * CELL, y * CELL, CELL, CELL); } } // Grid lines. ctx.strokeStyle = "rgba(130, 160, 210, 0.16)"; ctx.lineWidth = 1; ctx.beginPath(); for (var i = 1; i < SIZE; i++) { var p = i * CELL + 0.5; ctx.moveTo(p, 0); ctx.lineTo(p, BOARD); ctx.moveTo(0, p); ctx.lineTo(BOARD, p); } ctx.stroke(); } function drawFood(food) { if (!food) return; var fx = food[0] * CELL + CELL / 2; var fy = food[1] * CELL + CELL / 2; ctx.save(); ctx.shadowColor = "rgba(255, 80, 105, 0.8)"; ctx.shadowBlur = 16; ctx.fillStyle = "#ff4f66"; ctx.beginPath(); ctx.arc(fx, fy, CELL * 0.3, 0, Math.PI * 2); ctx.fill(); ctx.restore(); ctx.fillStyle = "rgba(255, 255, 255, 0.7)"; ctx.beginPath(); ctx.arc(fx - CELL * 0.1, fy - CELL * 0.1, CELL * 0.07, 0, Math.PI * 2); ctx.fill(); } function drawSnake(snake) { for (var i = snake.length - 1; i >= 0; i--) { var cell = snake[i]; var isHead = i === 0; var pad = isHead ? 2 : 3.5; var x = cell[0] * CELL + pad; var y = cell[1] * CELL + pad; var w = CELL - pad * 2; ctx.fillStyle = isHead ? "#a3f7b5" : (i % 2 === 0 ? "#3fc25e" : "#37ad53"); if (isHead) { ctx.save(); ctx.shadowColor = "rgba(120, 240, 150, 0.45)"; ctx.shadowBlur = 12; } roundRect(x, y, w, w, isHead ? 9 : 7); ctx.fill(); if (isHead) ctx.restore(); } } function drawEyes(snake) { var head = snake[0]; if (!head) return; var hx = head[0] * CELL + CELL / 2; var hy = head[1] * CELL + CELL / 2; // Infer facing from head -> neck (default: left, the starting direction). var fx = -1, fy = 0; if (snake.length > 1) { fx = head[0] - snake[1][0]; fy = head[1] - snake[1][1]; } var fwd = 5.5, side = 6; var e1x, e1y, e2x, e2y; if (fx !== 0) { e1x = hx + fx * fwd; e1y = hy + side; e2x = hx + fx * fwd; e2y = hy - side; } else if (fy !== 0) { e1x = hx + side; e1y = hy + fy * fwd; e2x = hx - side; e2y = hy + fy * fwd; } else { e1x = hx + side; e1y = hy; e2x = hx - side; e2y = hy; } ctx.fillStyle = "#0a1a10"; ctx.beginPath(); ctx.arc(e1x, e1y, 2.8, 0, Math.PI * 2); ctx.fill(); ctx.beginPath(); ctx.arc(e2x, e2y, 2.8, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = "rgba(255, 255, 255, 0.85)"; ctx.beginPath(); ctx.arc(e1x - 0.9, e1y - 0.9, 0.9, 0, Math.PI * 2); ctx.fill(); ctx.beginPath(); ctx.arc(e2x - 0.9, e2y - 0.9, 0.9, 0, Math.PI * 2); ctx.fill(); } function drawOver() { ctx.fillStyle = "rgba(5, 7, 11, 0.74)"; ctx.fillRect(0, 0, BOARD, BOARD); ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = "#ff4f66"; ctx.font = "800 36px system-ui, -apple-system, 'Segoe UI', sans-serif"; ctx.fillText("GAME OVER", BOARD / 2, BOARD / 2 - 12); ctx.fillStyle = "#93a0b6"; ctx.font = "500 15px system-ui, -apple-system, 'Segoe UI', sans-serif"; ctx.fillText("New game to play again", BOARD / 2, BOARD / 2 + 28); } function draw() { var st = game.state(); drawBoard(); drawFood(st.food); drawSnake(st.snake); drawEyes(st.snake); if (st.over) drawOver(); scoreEl.textContent = String(st.score); } var KEYMAP = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right" }; // One key press = one step. document.addEventListener("keydown", function (e) { var dir = KEYMAP[e.key]; if (!dir) return; e.preventDefault(); if (e.repeat || e.altKey || e.ctrlKey || e.metaKey) return; game.step(dir); draw(); }); restartBtn.addEventListener("click", function () { game = createGame(); draw(); restartBtn.blur(); }); draw(); })(); </script> </body> </html> ``` ### Gameplay & Controls The snake moves automatically one cell per arrow key press, and you can reset at any time. - **One key press = one step** — each arrow key press moves the snake exactly one cell; holding a key does not auto-repeat. - **Direction rules** — if you press the opposite of the current direction, the input is ignored and the snake continues straight. Pressing a new valid direction changes the current direction. - **Food & scoring** — eating food adds 1 point and the snake grows; the next food appears in the first empty cell after the new head, wrapping around. - **Collision** — hitting the grid edge or the snake ends the game; once over, all steps do nothing until you click **New game**. - **Visual feedback** — a checkerboard grid, glowing snake body, red food, and an overlay appear when the game ends.Box-pushing puzzlePassed
38,751 tokens: 1,108 read, 37,643 written · 2 min 20 s · 268 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"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Box-pushing puzzle</title> <style> * { box-sizing: border-box; } body { margin: 0; min-height: 100vh; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background: #eef2f5; color: #1c2530; display: flex; flex-direction: column; align-items: center; gap: 14px; padding: 24px 16px; } h1 { font-size: 22px; margin: 0; } #board { display: grid; grid-template-columns: repeat(8, 48px); grid-auto-rows: 48px; border: 3px solid #34424d; border-radius: 6px; overflow: hidden; background: #b9c4cc; box-shadow: 0 6px 18px rgba(0,0,0,.12); } .cell { position: relative; display: flex; align-items: center; justify-content: center; font-size: 22px; font-weight: 700; line-height: 1; background: #ffffff; user-select: none; } .cell.wall { background: #34424d; color: #dfe7ec; } .cell.goal::before { content: ""; position: absolute; inset: 7px; border: 2.5px solid #c2185b; border-radius: 50%; pointer-events: none; } .cell.box { background: #ffe0b2; color: #8a5a00; } .cell.player { background: #cfe6ff; color: #0d47a1; } #hud { display: flex; gap: 20px; font-size: 16px; } #hud b { display: inline-block; min-width: 1.5em; text-align: center; font-variant-numeric: tabular-nums; } #status { font-size: 16px; font-weight: 600; min-height: 1.3em; } #pad { display: grid; grid-template-columns: repeat(3, 62px); grid-template-rows: repeat(2, 42px); grid-template-areas: ". up ." "left down right"; gap: 6px; } #pad button, #restart { font-size: 15px; cursor: pointer; border: 1px solid #90a4ae; background: #fafbfc; border-radius: 8px; } #pad button:active, #restart:active { background: #e3e9ee; } #pad [data-dir="up"] { grid-area: up; } #pad [data-dir="down"] { grid-area: down; } #pad [data-dir="left"] { grid-area: left; } #pad [data-dir="right"] { grid-area: right; } #restart { padding: 8px 20px; } </style> </head> <body> <h1>Box-pushing puzzle</h1> <div id="board"></div> <div id="hud"> <span>Steps: <b id="steps">0</b></span> <span>Pushes: <b id="pushes">0</b></span> </div> <div id="status">Not solved yet</div> <div id="pad"> <button type="button" data-dir="up">Up</button> <button type="button" data-dir="down">Down</button> <button type="button" data-dir="left">Left</button> <button type="button" data-dir="right">Right</button> </div> <button type="button" id="restart">Restart</button> <script id="game"> function createGame() { var MAP = [ "########", "# +#", "# * #", "# #", "## $##", "# #", "########" ]; var WIDTH = 8, HEIGHT = 7; var player = [0, 0]; var goals = []; var boxes = []; for (var y = 0; y < HEIGHT; y++) { for (var x = 0; x < WIDTH; x++) { var ch = MAP[y].charAt(x); if (ch === "#") continue; if (ch === "." || ch === "*" || ch === "+") goals.push([x, y]); if (ch === "$" || ch === "*") boxes.push([x, y]); if (ch === "@" || ch === "+") player = [x, y]; } } var steps = 0, pushes = 0, solved = false; function isWall(x, y) { if (x < 0 || y < 0 || x >= WIDTH || y >= HEIGHT) return true; return MAP[y].charAt(x) === "#"; } function isGoal(x, y) { for (var i = 0; i < goals.length; i++) { if (goals[i][0] === x && goals[i][1] === y) return true; } return false; } function boxIndexAt(x, y) { for (var i = 0; i < boxes.length; i++) { if (boxes[i][0] === x && boxes[i][1] === y) return i; } return -1; } function checkSolved() { for (var i = 0; i < boxes.length; i++) { if (!isGoal(boxes[i][0], boxes[i][1])) return false; } return true; } function walk(dir) { if (solved) return; var dx = 0, dy = 0; if (dir === "up") dy = -1; else if (dir === "down") dy = 1; else if (dir === "left") dx = -1; else if (dir === "right") dx = 1; else return; var nx = player[0] + dx, ny = player[1] + dy; if (isWall(nx, ny)) return; var bi = boxIndexAt(nx, ny); if (bi >= 0) { var bx = nx + dx, by = ny + dy; if (isWall(bx, by) || boxIndexAt(bx, by) >= 0) return; boxes[bi][0] = bx; boxes[bi][1] = by; player[0] = nx; player[1] = ny; steps++; pushes++; } else { player[0] = nx; player[1] = ny; steps++; } solved = checkSolved(); } function state() { var copy = boxes.map(function (p) { return [p[0], p[1]]; }); copy.sort(function (a, b) { return (a[1] - b[1]) || (a[0] - b[0]); }); return { player: [player[0], player[1]], boxes: copy, pushes: pushes, steps: steps, solved: solved }; } return { walk: walk, state: state }; } </script> <script> (function () { "use strict"; var MAP = [ "########", "# +#", "# * #", "# #", "## $##", "# #", "########" ]; var WIDTH = 8, HEIGHT = 7; var wall = [], goal = []; for (var gy = 0; gy < HEIGHT; gy++) { wall[gy] = []; goal[gy] = []; for (var gx = 0; gx < WIDTH; gx++) { var gc = MAP[gy].charAt(gx); wall[gy][gx] = gc === "#"; goal[gy][gx] = gc === "." || gc === "*" || gc === "+"; } } var game = createGame(); var boardEl = document.getElementById("board"); var stepsEl = document.getElementById("steps"); var pushesEl = document.getElementById("pushes"); var statusEl = document.getElementById("status"); var cells = []; for (var by = 0; by < HEIGHT; by++) { for (var bx = 0; bx < WIDTH; bx++) { var cell = document.createElement("div"); cell.className = "cell"; cell.setAttribute("role", "img"); cell.setAttribute("aria-label", "empty floor"); boardEl.appendChild(cell); cells.push(cell); } } function paintCell(cell, x, y, s, boxSet) { var cls, text, label; if (wall[y][x]) { cls = "cell wall"; text = "#"; label = "wall"; } else { var isGoal = goal[y][x]; var hasBox = boxSet[x + "," + y] === true; var hasPlayer = s.player[0] === x && s.player[1] === y; cls = "cell"; if (isGoal) cls += " goal"; if (hasPlayer) cls += " player"; if (hasBox) cls += " box"; if (hasPlayer && isGoal) { text = "+"; label = "you on a goal"; } else if (hasPlayer) { text = "@"; label = "you"; } else if (hasBox && isGoal) { text = "*"; label = "box on a goal"; } else if (hasBox) { text = "$"; label = "box"; } else if (isGoal) { text = "."; label = "empty goal"; } else { text = ""; label = "empty floor"; } } if (cell.className !== cls) cell.className = cls; if (cell.textContent !== text) cell.textContent = text; if (cell.getAttribute("aria-label") !== label) cell.setAttribute("aria-label", label); } function render() { var s = game.state(); var boxSet = {}; for (var i = 0; i < s.boxes.length; i++) { boxSet[s.boxes[i][0] + "," + s.boxes[i][1]] = true; } for (var y = 0; y < HEIGHT; y++) { for (var x = 0; x < WIDTH; x++) { paintCell(cells[y * WIDTH + x], x, y, s, boxSet); } } stepsEl.textContent = String(s.steps); pushesEl.textContent = String(s.pushes); statusEl.textContent = s.solved ? "Solved in " + s.steps + " steps with " + s.pushes + " pushes" : "Not solved yet"; } var KEYMAP = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right" }; function act(dir) { game.walk(dir); render(); } window.addEventListener("keydown", function (e) { var dir = KEYMAP[e.key]; if (!dir) return; e.preventDefault(); if (e.repeat) return; act(dir); }, true); var dirButtons = document.querySelectorAll("[data-dir]"); for (var b = 0; b < dirButtons.length; b++) { dirButtons[b].addEventListener("click", function (e) { act(e.currentTarget.getAttribute("data-dir")); }); } document.getElementById("restart").addEventListener("click", function () { game = createGame(); render(); }); render(); })(); </script> </body> </html> ```MinesweeperPassed
17,627 tokens: 1,405 read, 16,222 written · 1 min 2 s · 261 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> *{box-sizing:border-box} html,body{margin:0;padding:0} body{ padding:16px; background:#f7f1e6; color:#3d352b; font-family: system-ui, sans-serif; -webkit-text-size-adjust:100%; } main{width:100%;max-width:400px;margin:0 auto} h1{font-size:1.4rem;line-height:1.2;margin:0 0 6px} .rules{margin:0 0 14px;font-size:.9rem;line-height:1.45;color:#6b5f4f} .panel{ background:#fff; border-radius:14px; padding:14px; box-shadow:0 1px 3px rgba(90,70,40,.14), 0 8px 24px rgba(90,70,40,.10); } #status{font-size:1rem;line-height:1.3;margin:0 0 12px;color:#4a4136} #mines-left{font-variant-numeric:tabular-nums} #status-word{font-weight:700} #status-word.playing{color:#4a4136} #status-word.won{color:#1b7f3b} #status-word.lost{color:#c62828} #flag-mode{ display:block; font-family:inherit;font-size:.95rem;font-weight:600; margin:0 0 14px;padding:8px 16px; border:1.5px solid #cbbfa9;border-radius:999px; background:#fff;color:#4a4136; cursor:pointer; touch-action:manipulation; } #flag-mode.on{background:#ffd9e6;border-color:#e2568f;color:#97164f} #flag-mode:focus-visible{outline:3px solid #2f6fed;outline-offset:2px} #board{ display:grid; grid-template-columns:repeat(9,1fr); width:324px; max-width:100%; margin:0 auto; border:2px solid #c9bda8; border-radius:4px; overflow:hidden; background:#fff; touch-action:manipulation; } .cell{ -webkit-appearance:none;appearance:none; display:flex;align-items:center;justify-content:center; width:100%;min-width:0;margin:0;padding:0; aspect-ratio:1/1; border:0;border-right:1px solid #cdc2ae;border-bottom:1px solid #cdc2ae; border-radius:0; background:#ded3bf; color:transparent; font-family:inherit;font-size:19px;font-weight:700;line-height:1; cursor:pointer; -webkit-user-select:none;user-select:none; } .cell:nth-child(9n){border-right:0} .cell:nth-child(n+73){border-bottom:0} .cell.hidden{background:#ded3bf} .cell.open{background:#faf6ee;cursor:default} .cell.flag{background:#f5e6d3;color:#b0326b} .cell.mine{background:#f9dcdc;color:#b3121b} .cell.n1{color:#1a4fb4} .cell.n2{color:#1d6b2f} .cell.n3{color:#b02020} .cell.n4{color:#3b2a86} .cell.n5{color:#7a1f1f} .cell.n6{color:#0f6d6d} .cell.n7{color:#222} .cell.n8{color:#5b5b5b} .cell:focus-visible{outline:3px solid #2f6fed;outline-offset:-3px;position:relative;z-index:1} @media (hover:hover){ .cell.hidden:hover{background:#e9dfcb} #flag-mode:hover{border-color:#b3a68e} #flag-mode.on:hover{border-color:#c93b76} } @media (max-width:380px){ .cell{font-size:16px} } </style> </head> <body> <main> <h1>Minesweeper</h1> <p class="rules">A 9×9 board hides 10 mines. Open a square to see how many mines touch it; an empty square opens its neighbours. Flag the squares you think are mines, right-click or press F to flag, and win by opening all 71 safe squares.</p> <section class="panel"> <div id="status" role="status"><span id="mines-left">Mines left 10</span> · <span id="status-word" class="status-word playing">Playing</span></div> <button id="flag-mode" type="button" aria-pressed="false">Flag mode: off</button> <div id="board" role="group" aria-label="Minesweeper board"></div> </section> </main> <script id="game"> const MS_SIZE = 9; const MS_MINES = 10; const MS_LAYOUT = [ "*......*.", "....*....", ".......*.", ".........", ".........", ".*.***...", ".........", "*........", ".....*..." ]; function createGame() { const N = MS_SIZE; const mine = []; const opened = []; const flagged = []; const count = []; let status = "playing"; let totalSafe = 0; let openedSafe = 0; for (let r = 0; r < N; r++) { mine[r] = []; opened[r] = []; flagged[r] = []; count[r] = []; for (let c = 0; c < N; c++) { const isMine = MS_LAYOUT[r].charAt(c) === "*"; mine[r][c] = isMine; opened[r][c] = false; flagged[r][c] = false; count[r][c] = 0; if (!isMine) { totalSafe++; } } } function eachNeighbour(r, c, fn) { for (let dr = -1; dr <= 1; dr++) { for (let dc = -1; dc <= 1; dc++) { if (dr === 0 && dc === 0) { continue; } const nr = r + dr; const nc = c + dc; if (nr < 0 || nr >= N || nc < 0 || nc >= N) { continue; } fn(nr, nc); } } } for (let r = 0; r < N; r++) { for (let c = 0; c < N; c++) { if (mine[r][c]) { continue; } eachNeighbour(r, c, function (nr, nc) { if (mine[nr][nc]) { count[r][c]++; } }); } } function inside(r, c) { return typeof r === "number" && typeof c === "number" && isFinite(r) && isFinite(c) && Math.floor(r) === r && Math.floor(c) === c && r >= 0 && r < N && c >= 0 && c < N; } function openArea(r, c) { const stack = [[r, c]]; while (stack.length > 0) { const cell = stack.pop(); const cr = cell[0]; const cc = cell[1]; if (opened[cr][cc] || flagged[cr][cc] || mine[cr][cc]) { continue; } opened[cr][cc] = true; openedSafe++; if (count[cr][cc] === 0) { eachNeighbour(cr, cc, function (nr, nc) { if (!opened[nr][nc] && !flagged[nr][nc] && !mine[nr][nc]) { stack.push([nr, nc]); } }); } } } function press(move) { if (status !== "playing") { return; } if (!move || move.length < 3) { return; } const kind = move[0]; const r = move[1]; const c = move[2]; if (!inside(r, c)) { return; } if (kind === "flag") { if (opened[r][c]) { return; } flagged[r][c] = !flagged[r][c]; return; } if (kind !== "open") { return; } if (opened[r][c] || flagged[r][c]) { return; } if (mine[r][c]) { status = "lost"; return; } openArea(r, c); if (openedSafe === totalSafe) { status = "won"; for (let rr = 0; rr < N; rr++) { for (let cc = 0; cc < N; cc++) { if (mine[rr][cc]) { flagged[rr][cc] = true; } } } } } function state() { const cells = []; let flags = 0; for (let r = 0; r < N; r++) { let line = ""; for (let c = 0; c < N; c++) { if (flagged[r][c]) { flags++; } if (status === "lost" && mine[r][c]) { line += "*"; } else if (opened[r][c]) { line += count[r][c] === 0 ? "." : String(count[r][c]); } else if (flagged[r][c]) { line += "F"; } else { line += "#"; } } cells.push(line); } return { cells: cells, status: status, mines_left: MS_MINES - flags }; } return { press: press, state: state }; } </script> <script> (function () { "use strict"; var N = 9; var game = createGame(); var statusEl = document.getElementById("status"); var minesLeftEl = document.getElementById("mines-left"); var statusWordEl = document.getElementById("status-word"); var flagBtn = document.getElementById("flag-mode"); var boardEl = document.getElementById("board"); var flagMode = false; var cellEls = []; var frag = document.createDocumentFragment(); for (var r = 0; r < N; r++) { for (var c = 0; c < N; c++) { var b = document.createElement("button"); b.type = "button"; b.className = "cell hidden"; b.setAttribute("data-row", String(r)); b.setAttribute("data-col", String(c)); frag.appendChild(b); cellEls.push(b); } } boardEl.appendChild(frag); var LABELS = { "#": "hidden", "F": "flagged", "*": "mine", ".": "open, no mines around" }; function cellFromEvent(e) { var t = e.target; if (!t || typeof t.closest !== "function") { return null; } return t.closest("button.cell"); } function doPress(kind, el) { var row = Number(el.getAttribute("data-row")); var col = Number(el.getAttribute("data-col")); game.press([kind, row, col]); render(); } function render() { var s = game.state(); for (var row = 0; row < N; row++) { var line = s.cells[row]; for (var col = 0; col < N; col++) { var ch = line.charAt(col); var el = cellEls[row * N + col]; var text = ""; var cls = "cell"; var label; if (ch === "F") { text = "F"; cls += " flag"; label = LABELS[ch]; } else if (ch === "*") { text = "*"; cls += " mine"; label = LABELS[ch]; } else if (ch === "#") { cls += " hidden"; label = LABELS[ch]; } else if (ch === ".") { cls += " open"; label = LABELS[ch]; } else { text = ch; cls += " open n" + ch; label = "open, " + ch + " mine" + (ch === "1" ? "" : "s") + " around"; } if (el.className !== cls) { el.className = cls; } if (el.textContent !== text) { el.textContent = text; } el.setAttribute("aria-label", "Row " + (row + 1) + ", column " + (col + 1) + ": " + label); } } minesLeftEl.textContent = "Mines left " + String(s.mines_left); statusWordEl.textContent = s.status === "won" ? "Won" : (s.status === "lost" ? "Lost" : "Playing"); statusWordEl.className = "status-word " + s.status; flagBtn.textContent = flagMode ? "Flag mode: on" : "Flag mode: off"; flagBtn.setAttribute("aria-pressed", flagMode ? "true" : "false"); if (flagMode) { flagBtn.classList.add("on"); } else { flagBtn.classList.remove("on"); } } boardEl.addEventListener("click", function (e) { var el = cellFromEvent(e); if (!el) { return; } doPress(flagMode ? "flag" : "open", el); }); boardEl.addEventListener("contextmenu", function (e) { var el = cellFromEvent(e); if (!el) { return; } e.preventDefault(); doPress("flag", el); }); boardEl.addEventListener("keydown", function (e) { if (e.key !== "f" && e.key !== "F" || e.ctrlKey || e.metaKey || e.altKey) { return; } var el = cellFromEvent(e); if (!el) { return; } e.preventDefault(); doPress("flag", el); }); flagBtn.addEventListener("click", function () { flagMode = !flagMode; render(); }); render(); })(); </script> </body> </html>
Building apps 3 of 4
Step sequencerPassed
30,903 tokens: 1,256 read, 29,647 written · 1 min 48 s · 276 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 1000100000101000 snare 0000100010001000 hat 0101010111011101 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
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Step sequencer</title> <style> :root{ --pink:#b31f57; --ink:#1a1a1a; --bg:#f4f4f2; --line:#b8b8b0; } *{ box-sizing:border-box; } html,body{ margin:0; padding:0; } body{ background:var(--bg); color:var(--ink); font-family:system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif; padding:24px; overflow-x:hidden; /* never scrolls sideways */ } main{ max-width:1120px; margin:0 auto; } h1{ font-size:22px; margin:0 0 16px; font-weight:700; } .controls{ display:flex; gap:12px; margin-bottom:8px; } button{ font:inherit; cursor:pointer; } #play,#stop{ border:1px solid var(--ink); background:#fff; color:var(--ink); padding:8px 22px; border-radius:4px; font-weight:600; } #play{ background:var(--pink); border-color:var(--pink); color:#fff; } /* the one pink button */ #play:disabled,#stop:disabled{ opacity:.45; cursor:default; } .status{ height:24px; /* fixed so the grid never moves */ line-height:24px; font-size:14px; margin-bottom:12px; font-variant-numeric:tabular-nums; } .sr-only{ position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap; border:0; } .board{ display:flex; flex-direction:column; gap:4px; width:100%; } .numbers-row,.track-row{ display:flex; gap:4px; align-items:stretch; } .numbers-label-spacer,.track-label{ flex:0 0 64px; width:64px; } .track-label{ display:flex; align-items:center; font-weight:600; font-size:14px; } .numbers-grid,.steps{ display:grid; grid-template-columns:repeat(16,minmax(0,1fr)); gap:4px; flex:1 1 auto; min-width:0; } .num{ text-align:center; font-size:12px; color:#888; padding-bottom:2px; } .num.playhead{ color:var(--pink); font-weight:700; } /* playhead's number is pink */ .step{ position:relative; min-width:0; height:46px; padding:0; border:1px solid var(--line); background:#fff; border-radius:3px; } .step.on{ background:var(--ink); border-color:var(--ink); } /* on cell: dark fill */ .step.playhead{ outline:2px solid var(--pink); outline-offset:-2px; } /* playhead cell: pink outline */ .btn-num{ display:none; color:var(--ink); font-size:11px; line-height:1; } .step.on .btn-num{ color:#fff; } /* Under 720px: two bars of 8 per track, each step shows its own number */ @media (max-width:719px){ body{ padding:16px 12px; } .numbers-row{ display:none; } .numbers-grid,.steps{ grid-template-columns:repeat(8,minmax(0,1fr)); row-gap:6px; } .btn-num{ display:block; } .step{ display:flex; align-items:flex-start; justify-content:flex-start; padding:3px; } .step.playhead .btn-num{ color:var(--pink); } } </style> </head> <body> <main> <h1>Step sequencer</h1> <div class="controls"> <button id="play" type="button">Play</button> <button id="stop" type="button">Stop</button> </div> <div id="status" class="status">Stopped</div> <span id="announce" class="sr-only" aria-live="polite"></span> <div id="board" class="board"></div> </main> <!-- ===== Logic only: no document, no window, no timers ===== --> <script id="game"> function createGame() { var pattern = [ "1000100000101000", // kick "0000100010001000", // snare "0101010111011101" // hat ]; var playing = false; var playhead = 0; var hits = []; function computeHits() { var h = []; for (var t = 0; t < pattern.length; t++) { if (pattern[t].charAt(playhead) === "1") h.push(t); } return h; // already ascending (0,1,2) } function press(cmd) { // [track, step] -> toggle one cell, and nothing else if (Array.isArray(cmd)) { if (cmd.length !== 2) return; var track = cmd[0], step = cmd[1]; if (!Number.isInteger(track) || !Number.isInteger(step)) return; if (track < 0 || track > 2 || step < 0 || step > 15) return; var row = pattern[track]; var next = row.charAt(step) === "1" ? "0" : "1"; pattern[track] = row.substring(0, step) + next + row.substring(step + 1); return; } if (typeof cmd === "string") { if (cmd === "play") { if (playing) return; // does nothing when already playing playing = true; hits = computeHits(); // the step under the playhead sounds return; } if (cmd === "stop") { playing = false; playhead = 0; hits = []; return; } if (cmd === "tick") { if (!playing) return; playhead = playhead + 1; if (playhead > 15) playhead = 0; hits = computeHits(); return; } return; // any other word does nothing } // null, numbers, booleans, anything else: do nothing } function state() { return { playing: playing, playhead: playhead, hits: hits.slice(), pattern: pattern.slice() }; } return { press: press, state: state }; } </script> <!-- ===== Page wiring: DOM, drawing, sound, timers ===== --> <script> (function () { var game = createGame(); // called at load var LABELS = ["Kick", "Snare", "Hat"]; var board = document.getElementById("board"); var statusEl = document.getElementById("status"); var announceEl = document.getElementById("announce"); var playBtn = document.getElementById("play"); var stopBtn = document.getElementById("stop"); var stepButtons = [[], [], []]; var numberSpans = []; // --- build the board --- var numbersRow = document.createElement("div"); numbersRow.className = "numbers-row"; var spacer = document.createElement("div"); spacer.className = "numbers-label-spacer"; numbersRow.appendChild(spacer); var numbersGrid = document.createElement("div"); numbersGrid.className = "numbers-grid"; for (var i = 0; i < 16; i++) { var ns = document.createElement("span"); ns.className = "num"; ns.textContent = String(i + 1); numbersGrid.appendChild(ns); numberSpans.push(ns); } numbersRow.appendChild(numbersGrid); board.appendChild(numbersRow); for (var t = 0; t < 3; t++) { var row = document.createElement("div"); row.className = "track-row"; var label = document.createElement("div"); label.className = "track-label"; label.textContent = LABELS[t]; row.appendChild(label); var steps = document.createElement("div"); steps.className = "steps"; for (var s = 0; s < 16; s++) { var btn = document.createElement("button"); btn.type = "button"; btn.className = "step"; btn.setAttribute("data-track", String(t)); btn.setAttribute("data-step", String(s)); btn.setAttribute("aria-pressed", "false"); var bnum = document.createElement("span"); bnum.className = "btn-num"; bnum.textContent = String(s + 1); btn.appendChild(bnum); btn.addEventListener("click", onStepClick); steps.appendChild(btn); stepButtons[t].push(btn); } row.appendChild(steps); board.appendChild(row); } // --- draw from state() --- function draw() { var st = game.state(); for (var t = 0; t < 3; t++) { for (var s = 0; s < 16; s++) { var btn = stepButtons[t][s]; var on = st.pattern[t].charAt(s) === "1"; if (on) btn.classList.add("on"); else btn.classList.remove("on"); btn.setAttribute("aria-pressed", on ? "true" : "false"); var ph = st.playing && s === st.playhead; if (ph) btn.classList.add("playhead"); else btn.classList.remove("playhead"); } } for (var k = 0; k < 16; k++) { var phn = st.playing && k === st.playhead; if (phn) numberSpans[k].classList.add("playhead"); else numberSpans[k].classList.remove("playhead"); } statusEl.textContent = st.playing ? "Playing, step " + (st.playhead + 1) + " of 16" : "Stopped"; playBtn.disabled = st.playing; // Play disabled while playing stopBtn.disabled = !st.playing; // Stop disabled while stopped } // --- Web Audio drum engine (no sound files) --- var audioCtx = null; var masterGain = null; var noiseBuffer = null; function ensureAudio() { var AC = window.AudioContext || window.webkitAudioContext; if (!audioCtx && AC) { audioCtx = new AC(); // gain + limiter before the output so simultaneous hits never clip masterGain = audioCtx.createGain(); masterGain.gain.value = 0.7; var limiter = audioCtx.createDynamicsCompressor(); limiter.threshold.value = -8; limiter.knee.value = 6; limiter.ratio.value = 12; limiter.attack.value = 0.003; limiter.release.value = 0.25; masterGain.connect(limiter); limiter.connect(audioCtx.destination); // one buffer of random samples reused by the noise bursts var len = Math.floor(audioCtx.sampleRate * 1); noiseBuffer = audioCtx.createBuffer(1, len, audioCtx.sampleRate); var data = noiseBuffer.getChannelData(0); for (var j = 0; j < len; j++) data[j] = Math.random() * 2 - 1; } if (audioCtx && audioCtx.state === "suspended") audioCtx.resume(); } function playKick() { // falling sine tone, one oscillator var now = audioCtx.currentTime; var osc = audioCtx.createOscillator(); var g = audioCtx.createGain(); osc.type = "sine"; osc.frequency.setValueAtTime(150, now); osc.frequency.exponentialRampToValueAtTime(48, now + 0.16); g.gain.setValueAtTime(0.9, now); g.gain.exponentialRampToValueAtTime(0.001, now + 0.32); osc.connect(g); g.connect(masterGain); osc.start(now); osc.stop(now + 0.34); } function playSnare() { // one buffer source + one oscillator var now = audioCtx.currentTime; var noise = audioCtx.createBufferSource(); noise.buffer = noiseBuffer; var ng = audioCtx.createGain(); ng.gain.setValueAtTime(0.5, now); ng.gain.exponentialRampToValueAtTime(0.001, now + 0.2); noise.connect(ng); ng.connect(masterGain); noise.start(now); noise.stop(now + 0.22); var osc = audioCtx.createOscillator(); var og = audioCtx.createGain(); osc.type = "triangle"; osc.frequency.setValueAtTime(190, now); osc.frequency.exponentialRampToValueAtTime(120, now + 0.12); og.gain.setValueAtTime(0.4, now); og.gain.exponentialRampToValueAtTime(0.001, now + 0.16); osc.connect(og); og.connect(masterGain); osc.start(now); osc.stop(now + 0.18); } function playHat() { // short high noise burst, one buffer source var now = audioCtx.currentTime; var noise = audioCtx.createBufferSource(); noise.buffer = noiseBuffer; var hp = audioCtx.createBiquadFilter(); hp.type = "highpass"; hp.frequency.value = 7000; var g = audioCtx.createGain(); g.gain.setValueAtTime(0.25, now); g.gain.exponentialRampToValueAtTime(0.001, now + 0.05); noise.connect(hp); hp.connect(g); g.connect(masterGain); noise.start(now); noise.stop(now + 0.06); } function soundHits() { // sound exactly the hits state() reports var hits = game.state().hits; for (var i = 0; i < hits.length; i++) { var t = hits[i]; if (t === 0) playKick(); else if (t === 1) playSnare(); else if (t === 2) playHat(); } } // --- transport --- var timer = null; function tickFn() { // a function, never a string game.press("tick"); soundHits(); draw(); } function startTimer() { if (timer !== null) clearInterval(timer); timer = setInterval(tickFn, 125); // 120 BPM, 4 steps per beat } function stopTimer() { if (timer !== null) { clearInterval(timer); timer = null; } } function doPlay() { ensureAudio(); if (game.state().playing) return; // press('play') is a no-op while playing game.press("play"); soundHits(); // the starting step sounds announceEl.textContent = "Playing"; draw(); startTimer(); } function doStop() { var wasPlaying = game.state().playing; game.press("stop"); stopTimer(); draw(); if (wasPlaying) announceEl.textContent = "Stopped"; // only change when it actually stops } function onStepClick(e) { ensureAudio(); // first click builds/resumes the AudioContext var btn = e.currentTarget; var track = parseInt(btn.getAttribute("data-track"), 10); var step = parseInt(btn.getAttribute("data-step"), 10); game.press([track, step]); // toggling sounds nothing draw(); } playBtn.addEventListener("click", doPlay); stopBtn.addEventListener("click", function () { ensureAudio(); doStop(); }); document.addEventListener("visibilitychange", function () { if (document.hidden) doStop(); // press Stop in a background tab }); draw(); // initial paint from state() })(); </script> </body> </html> ```Grow a branching plantFailed
26,348 tokens: 1,230 read, 25,118 written · 1 min 49 s · 230 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
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Grow a branching plant</title> <style> :root { --page: #f7f3ea; --card: #ffffff; --line: #e6ded1; --ink: #22322a; --muted: #6a6559; --accent: #2f6b4f; --accent-dark: #24543c; } * { box-sizing: border-box; } html, body { margin: 0; } body { min-height: 100vh; padding: 28px 16px 56px; background: var(--page); color: var(--ink); font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; display: flex; flex-direction: column; align-items: center; -webkit-font-smoothing: antialiased; } h1 { margin: 0 0 22px; font-size: clamp(1.5rem, 4vw, 2.1rem); font-weight: 650; letter-spacing: -0.01em; text-align: center; } .card { width: 100%; max-width: 560px; padding: 12px; background: var(--card); border: 1px solid var(--line); border-radius: 16px; box-shadow: 0 2px 10px rgba(60, 50, 30, 0.05); } canvas { display: block; width: 100%; height: auto; border-radius: 8px; background: #ffffff; } .status { width: 100%; max-width: 560px; margin: 16px 0 0; text-align: center; font-size: 0.95rem; color: var(--muted); font-variant-numeric: tabular-nums; } .controls { margin-top: 18px; display: flex; gap: 12px; flex-wrap: wrap; justify-content: center; } button { font: inherit; font-weight: 600; font-size: 1rem; padding: 11px 28px; border-radius: 11px; cursor: pointer; transition: background-color 0.15s ease, transform 0.05s ease; } button:focus-visible { outline: 3px solid rgba(47, 107, 79, 0.35); outline-offset: 2px; } #grow { color: #ffffff; background: var(--accent); border: 1px solid var(--accent); } #grow:hover:not(:disabled) { background: var(--accent-dark); border-color: var(--accent-dark); } #grow:active:not(:disabled) { transform: translateY(1px); } #grow:disabled { opacity: 0.4; cursor: not-allowed; } #reset { color: var(--accent); background: transparent; border: 1px solid var(--accent); } #reset:hover { background: rgba(47, 107, 79, 0.08); } #reset:active { transform: translateY(1px); } </style> </head> <body> <h1>Grow a branching plant</h1> <div class="card"> <canvas id="canvas" width="600" height="600" role="img" aria-label="The plant drawn so far"></canvas> </div> <p class="status" role="status" id="status"></p> <div class="controls"> <button id="grow" type="button">Grow</button> <button id="reset" type="button">Reset</button> </div> <script id="game"> function createGame() { var rule = "F[-F[--F]]F[[++F]]F"; var steps = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; var generation = 0; var text = "F"; var segments = []; function computeSegments(t) { var x = 0, y = 0, h = 6; var stack = []; var segs = []; for (var i = 0; i < t.length; i++) { var c = t.charAt(i); if (c === 'F') { var d = steps[h]; var nx = x + d[0]; var ny = y + d[1]; segs.push([x, y, nx, ny]); x = nx; y = ny; } else if (c === '+') { h = (h + 1) % 8; } else if (c === '-') { h = (h + 7) % 8; } else if (c === '[') { stack.push([x, y, h]); } else if (c === ']') { var top = stack.pop(); x = top[0]; y = top[1]; h = top[2]; } } return segs; } segments = computeSegments(text); return { grow: function () { if (generation >= 4) { return; } var next = ""; for (var i = 0; i < text.length; i++) { var c = text.charAt(i); if (c === 'F') { next = next + rule; } else { next = next + c; } } text = next; generation = generation + 1; segments = computeSegments(text); }, state: function () { return { generation: generation, text: text, segments: segments }; } }; } </script> <script> (function () { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var growBtn = document.getElementById('grow'); var resetBtn = document.getElementById('reset'); var statusEl = document.getElementById('status'); var game = createGame(); function drawPlant(st) { var w = canvas.width; var h = canvas.height; ctx.clearRect(0, 0, w, h); var segs = st.segments; var count = segs.length; if (count === 0) { return; } var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < count; i++) { var s = segs[i]; minX = Math.min(minX, s[0], s[2]); maxX = Math.max(maxX, s[0], s[2]); minY = Math.min(minY, s[1], s[3]); maxY = Math.max(maxY, s[1], s[3]); } var pad = Math.min(w, h) * 0.06; var plotW = w - pad * 2; var plotH = h - pad * 2; var dataW = maxX - minX; var dataH = maxY - minY; var scale; if (dataW > 0 && dataH > 0) { scale = Math.min(plotW / dataW, plotH / dataH); } else if (dataW > 0) { scale = plotW / dataW; } else if (dataH > 0) { scale = plotH / dataH; } else { scale = 1; } var cx = (minX + maxX) / 2; var cy = (minY + maxY) / 2; var ox = w / 2; var oy = h / 2; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.strokeStyle = '#22322a'; ctx.lineWidth = Math.max(0.9, Math.min(3, scale * 0.16)); ctx.beginPath(); for (var j = 0; j < count; j++) { var seg = segs[j]; ctx.moveTo(ox + (seg[0] - cx) * scale, oy + (seg[1] - cy) * scale); ctx.lineTo(ox + (seg[2] - cx) * scale, oy + (seg[3] - cy) * scale); } ctx.stroke(); } function render() { var st = game.state(); drawPlant(st); var n = st.segments.length; statusEl.textContent = 'Generation ' + st.generation + ' of 4, ' + n + (n === 1 ? ' segment' : ' segments'); growBtn.disabled = st.generation >= 4; } growBtn.addEventListener('click', function () { game.grow(); render(); }); resetBtn.addEventListener('click', function () { game = createGame(); render(); }); render(); })(); </script> </body> </html> ```Falling sandPassed
36,220 tokens: 1,120 read, 35,100 written · 2 min 5 s · 281 tok/s
Build a page called Falling sand: a 40 by 30 board drawn on a canvas. Sand falls one frame at a time and slides off the edges of piles. Pressing or dragging on the board pours sand, Play runs the frames, and Step runs one. In <script id="game">, define createGame(). It returns an object with play(move) and state(). move is "step" (run one frame) or [x, y] (pour one grain of sand into column x, row y). state() returns {frame, cells}: frame is the number of frames run so far (a pour is not a frame), and cells is 30 rows of 40 numbers, top row first: 0 is empty, 1 is sand, 2 is wall. Column x runs 0 to 39, left to right; row y runs 0 to 29, top to bottom. The start, exactly (both ends of each run are included): 1. frame is 0. Row 29 is all wall. 2. Walls: row 19, columns 2 to 6; column 36, rows 19 to 24; column 8, rows 22 to 26. 3. Sand: column 22, row 0; row 1, columns 17 to 27; row 2, columns 16 to 28; row 3, columns 15 to 29; row 4, columns 14 to 30; row 5, columns 15 to 29; row 6, columns 16 to 28; row 7, columns 17 to 27; column 22, 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
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="color-scheme" content="dark"> <title>Falling sand</title> <style> :root { color-scheme: dark; } * { box-sizing: border-box; } html, body { margin: 0; } body { font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background: #14142a; color: #e8e8f0; min-height: 100vh; display: flex; justify-content: center; } main { width: min(680px, 100%); padding: 16px; display: flex; flex-direction: column; align-items: center; gap: 12px; } h1 { font-size: 1.3rem; font-weight: 600; margin: 4px 0; letter-spacing: .02em; } canvas#board { display: block; width: 100%; max-width: 640px; height: auto; background: #0d0d1a; border: 2px solid #3a3a5c; border-radius: 6px; touch-action: none; image-rendering: pixelated; cursor: crosshair; } canvas#board:focus-visible { outline: 3px solid #5ad0ff; outline-offset: 2px; } .controls { display: flex; gap: 10px; } button { font: inherit; padding: 8px 18px; min-width: 84px; border-radius: 8px; border: 1px solid #44446a; background: #262646; color: #e8e8f0; cursor: pointer; } button:hover { background: #32325a; } button:active { background: #3c3c6a; } button:focus-visible { outline: 3px solid #5ad0ff; outline-offset: 2px; } #status { margin: 0; font-variant-numeric: tabular-nums; opacity: .92; } .hint { margin: 0; font-size: .82rem; opacity: .6; text-align: center; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } </style> </head> <body> <main> <h1>Falling sand</h1> <canvas id="board" width="640" height="480" tabindex="0" aria-label="Falling sand board. Use arrow keys to move the pour cursor, Space or Enter to pour."></canvas> <div class="controls"> <button id="play" type="button">Play</button> <button id="step" type="button">Step</button> <button id="reset" type="button">Reset</button> </div> <p id="status">Frame 0, 97 grains of sand</p> <p class="hint">Click or drag on the board to pour sand.</p> <p id="say" class="sr-only" role="status" aria-live="polite"></p> </main> <script id="game"> function createGame() { var COLS = 40, ROWS = 30, EMPTY = 0, SAND = 1, WALL = 2; var cells, frame; function init() { var x, y, row; cells = []; for (y = 0; y < ROWS; y++) { row = []; for (x = 0; x < COLS; x++) row.push(EMPTY); cells.push(row); } for (x = 0; x < COLS; x++) cells[29][x] = WALL; // floor for (x = 2; x <= 6; x++) cells[19][x] = WALL; // wall: row 19, cols 2..6 for (y = 19; y <= 24; y++) cells[y][36] = WALL; // wall: col 36, rows 19..24 for (y = 22; y <= 26; y++) cells[y][8] = WALL; // wall: col 8, rows 22..26 cells[0][22] = SAND; for (x = 17; x <= 27; x++) cells[1][x] = SAND; for (x = 16; x <= 28; x++) cells[2][x] = SAND; for (x = 15; x <= 29; x++) cells[3][x] = SAND; for (x = 14; x <= 30; x++) cells[4][x] = SAND; for (x = 15; x <= 29; x++) cells[5][x] = SAND; for (x = 16; x <= 28; x++) cells[6][x] = SAND; for (x = 17; x <= 27; x++) cells[7][x] = SAND; cells[8][22] = SAND; frame = 0; } function empty(x, y) { if (x < 0 || x >= COLS || y < 0 || y >= ROWS) return false; // outside = wall return cells[y][x] === EMPTY; } function stepCell(x, y) { if (cells[y][x] !== SAND) return; if (empty(x, y + 1)) { cells[y][x] = EMPTY; cells[y + 1][x] = SAND; } else if (empty(x - 1, y + 1)) { cells[y][x] = EMPTY; cells[y + 1][x - 1] = SAND; } else if (empty(x + 1, y + 1)) { cells[y][x] = EMPTY; cells[y + 1][x + 1] = SAND; } } function step() { var x, y; for (y = 28; y >= 0; y--) { if (frame % 2 === 0) { for (x = 0; x < COLS; x++) stepCell(x, y); } else { for (x = COLS - 1; x >= 0; x--) stepCell(x, y); } } frame++; } function pour(x, y) { if (x < 0 || x >= COLS || y < 0 || y >= ROWS) return; if (cells[y][x] === EMPTY) cells[y][x] = SAND; } function play(move) { if (move === 'step') step(); else if (move && move.length === 2) pour(move[0], move[1]); } function state() { var out = [], y; for (y = 0; y < ROWS; y++) out.push(cells[y].slice()); return { frame: frame, cells: out }; } init(); return { play: play, state: state }; } </script> <script> (function () { 'use strict'; var COLS = 40, ROWS = 30, CELL = 16; var BG = '#0d0d1a', SAND_C = '#e6c35c', WALL_C = '#565672', CUR_C = '#5ad0ff'; var canvas = document.getElementById('board'); var ctx = canvas.getContext('2d'); var playBtn = document.getElementById('play'); var stepBtn = document.getElementById('step'); var resetBtn = document.getElementById('reset'); var statusEl = document.getElementById('status'); var sayEl = document.getElementById('say'); var game = createGame(); var playing = false, timer = null; var offscreen = false, wasPlaying = false; var cursor = [20, 15], cursorVisible = false; var dragging = false, lastCell = null; var mq = window.matchMedia ? window.matchMedia('(prefers-reduced-motion: reduce)') : null; var reduceMotion = !!(mq && mq.matches); /* ---------- drawing ---------- */ function render() { var cells = game.state().cells, x, y; // clear / fill the whole board exactly once ctx.fillStyle = BG; ctx.fillRect(0, 0, canvas.width, canvas.height); // walls ctx.fillStyle = WALL_C; for (y = 0; y < ROWS; y++) for (x = 0; x < COLS; x++) if (cells[y][x] === 2) ctx.fillRect(x * CELL, y * CELL, CELL, CELL); // sand grains (each in its own cell) ctx.fillStyle = SAND_C; for (y = 0; y < ROWS; y++) for (x = 0; x < COLS; x++) if (cells[y][x] === 1) ctx.fillRect(x * CELL, y * CELL, CELL, CELL); // keyboard pour cursor if (cursorVisible) { ctx.strokeStyle = CUR_C; ctx.lineWidth = 2; ctx.strokeRect(cursor[0] * CELL + 1, cursor[1] * CELL + 1, CELL - 2, CELL - 2); } } function updateStatus() { var st = game.state(), cells = st.cells, m = 0, x, y; for (y = 0; y < ROWS; y++) for (x = 0; x < COLS; x++) if (cells[y][x] === 1) m++; statusEl.textContent = 'Frame ' + st.frame + ', ' + m + (m === 1 ? ' grain of sand' : ' grains of sand'); } function draw() { render(); updateStatus(); } function say(msg) { if (!sayEl) return; sayEl.textContent = ''; window.setTimeout(function () { sayEl.textContent = msg; }, 40); } /* ---------- actions ---------- */ function stepOnce() { game.play('step'); draw(); } function pourCell(x, y) { game.play([x, y]); draw(); } function stopTimer() { if (timer !== null) { window.clearInterval(timer); timer = null; } } function startPlay() { if (playing) return; playing = true; playBtn.textContent = 'Pause'; say('Play'); timer = window.setInterval(stepOnce, 50); } function pausePlay() { if (!playing) return; stopTimer(); playing = false; playBtn.textContent = 'Play'; say('Pause'); } function resetGame() { stopTimer(); playing = false; wasPlaying = false; playBtn.textContent = 'Play'; game = createGame(); cursor = [20, 15]; cursorVisible = false; draw(); say('Reset'); } /* ---------- controls ---------- */ playBtn.addEventListener('click', function () { if (offscreen) return; // off screen: Play does nothing if (reduceMotion) { stepOnce(); say('Step'); return; } // reduced motion: one frame if (playing) pausePlay(); else startPlay(); }); stepBtn.addEventListener('click', function () { stepOnce(); say('Step'); }); resetBtn.addEventListener('click', resetGame); /* ---------- pointer pouring ---------- */ function eventCell(e) { var r = canvas.getBoundingClientRect(); if (!r.width || !r.height) return null; var x = Math.floor((e.clientX - r.left) / r.width * COLS); var y = Math.floor((e.clientY - r.top) / r.height * ROWS); if (x < 0) x = 0; else if (x > COLS - 1) x = COLS - 1; if (y < 0) y = 0; else if (y > ROWS - 1) y = ROWS - 1; return [x, y]; } function bresenham(x0, y0, x1, y1) { var pts = [], dx = Math.abs(x1 - x0), dy = Math.abs(y1 - y0); var sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1; var err = dx - dy, e2, x = x0, y = y0; for (;;) { pts.push([x, y]); if (x === x1 && y === y1) break; e2 = 2 * err; if (e2 > -dy) { err -= dy; x += sx; } if (e2 < dx) { err += dx; y += sy; } } return pts; } canvas.addEventListener('pointerdown', function (e) { e.preventDefault(); try { canvas.focus(); } catch (err) {} var c = eventCell(e); if (!c) return; dragging = true; lastCell = c; cursor = c; cursorVisible = true; try { canvas.setPointerCapture(e.pointerId); } catch (err) {} pourCell(c[0], c[1]); }); canvas.addEventListener('pointermove', function (e) { if (!dragging || !lastCell) return; e.preventDefault(); var c = eventCell(e); if (!c) return; var line = bresenham(lastCell[0], lastCell[1], c[0], c[1]); for (var i = 0; i < line.length; i++) game.play([line[i][0], line[i][1]]); lastCell = c; cursor = c; cursorVisible = true; draw(); }); function endDrag(e) { if (!dragging) return; dragging = false; lastCell = null; try { canvas.releasePointerCapture(e.pointerId); } catch (err) {} } canvas.addEventListener('pointerup', endDrag); canvas.addEventListener('pointercancel', endDrag); /* ---------- keyboard pouring ---------- */ canvas.addEventListener('keydown', function (e) { var k = e.key, used = true; if (k === 'ArrowUp') cursor[1] = Math.max(0, cursor[1] - 1); else if (k === 'ArrowDown') cursor[1] = Math.min(ROWS - 1, cursor[1] + 1); else if (k === 'ArrowLeft') cursor[0] = Math.max(0, cursor[0] - 1); else if (k === 'ArrowRight') cursor[0] = Math.min(COLS - 1, cursor[0] + 1); else if (k === ' ' || k === 'Enter') { cursorVisible = true; pourCell(cursor[0], cursor[1]); e.preventDefault(); return; } else used = false; if (used) { cursorVisible = true; e.preventDefault(); render(); } }); canvas.addEventListener('focus', function () { cursorVisible = true; render(); }); canvas.addEventListener('blur', function () { cursorVisible = false; render(); }); /* ---------- off-screen pausing ---------- */ if (typeof IntersectionObserver !== 'undefined') { new IntersectionObserver(function (entries) { for (var i = 0; i < entries.length; i++) { var vis = entries[i].isIntersecting; if (!vis && !offscreen) { offscreen = true; wasPlaying = playing; if (playing) { stopTimer(); playing = false; playBtn.textContent = 'Play'; } } else if (vis && offscreen) { offscreen = false; if (wasPlaying) { wasPlaying = false; startPlay(); } } } }, { threshold: 0 }).observe(canvas); } /* ---------- reduced-motion preference changes ---------- */ if (mq) { var onMq = function () { reduceMotion = mq.matches; if (reduceMotion && playing) pausePlay(); }; if (mq.addEventListener) mq.addEventListener('change', onMq); else if (mq.addListener) mq.addListener(onMq); } /* ---------- go ---------- */ draw(); })(); </script> </body> </html> ```Focus timerPassed
21,408 tokens: 1,080 read, 20,328 written · 1 min 11 s · 285 tok/s
Build a focus timer as one web page. Work periods alternate with breaks, and after every few finished work periods the break is long. The page shows the name of the period, the time left, an SVG ring that empties as the time runs down, and how many work periods are done. In <script id="game">, define createGame(). It returns an object with two methods, tick(cmd) and state(). The page's own timer calls tick() once a second, and its buttons call tick('start'), tick('pause'), tick('skip') and tick('reset'). Those four exact lowercase words are commands: they change the timer and pass no time. Any other value passes one second, and only while the timer is running: no argument, null, undefined, a number, true, false, an empty text, any other text such as 'Start' or 'tick', or an object. state() returns {phase, left, running, done}: phase is 'work', 'short' or 'long'; left is the whole number of seconds left in this period; running is true or false; done is a number. The script in <script id="game"> is at most 20,000 characters. This run's lengths: work 1800 seconds (30 minutes), short break 300 seconds (5 minutes), long break 900 seconds (15 minutes). A long break follows every 3rd finished work period. The rules, exactly: 1. The timer starts in work, with left 1800, running false and done 0. 2. 'start' sets running to true, and 'pause' sets it to false. Neither changes anything else. 3. While running, each passed second lowers left by 1. While paused, passed seconds change nothing. 4. When left reaches 0, the period is over at once, so state() never shows 0. The next period starts with its full length and paused (running false). Seconds passed after that change nothing until 'start'. 5. A work period that ends this way adds 1 to done. Then a long break comes when done is a multiple of 3, otherwise a short break. 6. 'skip' ends the current period at once, whatever left is, and the next period starts paused. A skipped work period does not add to done, and the break after it is a short break whatever done is. A skipped break is followed by work. 7. After any break comes work. A break never adds to done. 8. 'reset' sets left back to the full length of the current period and sets running to false. It does not change the phase or done. The page: - A heading, "Focus timer". - The name of the period, alone in an element with the id phase: Focus, Short break or Long break. - The time left, as mm:ss with two digits each, alone in an element with the id time. At the start of this run's work period it reads 30:00. - An SVG ring around the time: a circle with pathLength="100" and stroke-dasharray="100". Set its stroke-dashoffset attribute to 100 times (1 minus left divided by the full length of the current period) on every redraw. The arc is full, with an offset of 0, at the start of a period, and it is empty, with an offset of 100, when the time is up. A track circle without a stroke-dashoffset may sit under it. - Four buttons in one row, with the ids start, pause, skip and reset, labelled Start, Pause, Skip and Reset. Each calls tick() with its command. Start is disabled while the timer runs, and Pause is disabled while it is paused. Skip and Reset are always enabled. Below 390 px they may wrap into two rows of two. - The count in an element with the id count, in words: "Focus periods done: 3". - The page's own timer calls tick() once a second, with no argument. After every call, the page redraws from state(). When a period ends, the page may play a short chime with the Web Audio API. - Look: a light, warm off-white page with one white card, dark ink text and muted grey for the small labels. One accent colour, used for the Start button only. Flat fills, no gradients or shadows, no outside fonts or images: use the system font. It must look tidy at 390 px and at 1280 px wide, with no sideways scrolling. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the timer's logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and drives the timer through createGame(). Do not use eval, Function or any other way of running text as code: no string given to a timer, and no script element or event-handler attribute made from text while the page runs. Put the wiring in another <script>.Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Focus timer</title> <style> *, *::before, *::after { box-sizing: border-box; } html { -webkit-text-size-adjust: 100%; } body { margin: 0; min-height: 100vh; padding: 24px 16px; display: flex; background: #f6f1e9; color: #23201c; font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; font-size: 16px; line-height: 1.4; } .card { width: 100%; max-width: 440px; margin: auto; padding: 30px 26px 24px; background: #ffffff; border-radius: 22px; text-align: center; } h1 { margin: 0 0 8px; font-size: 20px; font-weight: 600; letter-spacing: -0.01em; } .phase { margin: 0; font-size: 13px; font-weight: 500; letter-spacing: 0.1em; color: #8a8076; } .ring { position: relative; width: min(240px, 64vw); aspect-ratio: 1 / 1; margin: 16px auto 18px; } .ringsvg { position: absolute; inset: 0; display: block; width: 100%; height: 100%; transform: rotate(-90deg); } .track { fill: none; stroke: #ebe4d8; stroke-width: 6; } .arc { fill: none; stroke: #23201c; stroke-width: 6; } .time { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: clamp(36px, 13vw, 52px); font-weight: 600; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; } .count { margin: 0 0 22px; font-size: 13px; color: #8a8076; } .buttons { display: flex; flex-wrap: wrap; gap: 10px; } .buttons button { flex: 1 1 0; min-width: 0; padding: 12px 8px; font: inherit; font-size: 15px; font-weight: 500; color: #23201c; background: #ffffff; border: 1px solid #ded5c7; border-radius: 10px; cursor: pointer; -webkit-tap-highlight-color: transparent; transition: background-color .15s ease, border-color .15s ease, color .15s ease, opacity .15s ease; } .buttons button:hover:not(:disabled) { background: #f6f1e9; } .buttons button:focus-visible { outline: 2px solid #23201c; outline-offset: 2px; } .buttons button:disabled { opacity: .38; cursor: default; } #start { background: #b45309; border-color: #b45309; color: #ffffff; } #start:hover:not(:disabled) { background: #984708; border-color: #984708; } @media (max-width: 389px) { .card { padding: 24px 18px 20px; } .buttons button { flex: 1 1 calc(50% - 5px); } } </style> </head> <body> <main class="card"> <h1>Focus timer</h1> <p id="phase" class="phase">Focus</p> <div class="ring"> <svg class="ringsvg" viewBox="0 0 120 120" aria-hidden="true" focusable="false"> <circle class="track" cx="60" cy="60" r="52"></circle> <circle id="arc" class="arc" cx="60" cy="60" r="52" pathLength="100" stroke-dasharray="100" stroke-dashoffset="0"></circle> </svg> <div id="time" class="time">30:00</div> </div> <p id="count" class="count">Focus periods done: 0</p> <div class="buttons"> <button id="start" type="button">Start</button> <button id="pause" type="button">Pause</button> <button id="skip" type="button">Skip</button> <button id="reset" type="button">Reset</button> </div> </main> <script id="game"> function createGame() { 'use strict'; var LENGTHS = { work: 1800, short: 300, long: 900 }; var AFTER_THIS_MANY = 3; var phase = 'work'; var left = LENGTHS.work; var running = false; var done = 0; function fullLength(p) { if (p === 'work') { return LENGTHS.work; } if (p === 'long') { return LENGTHS.long; } return LENGTHS.short; } function begin(next) { phase = next; left = fullLength(next); running = false; } function finishWork() { done += 1; return (done % AFTER_THIS_MANY === 0) ? 'long' : 'short'; } function tick(cmd) { if (cmd === 'start') { running = true; return; } if (cmd === 'pause') { running = false; return; } if (cmd === 'reset') { left = fullLength(phase); running = false; return; } if (cmd === 'skip') { begin(phase === 'work' ? 'short' : 'work'); return; } /* Anything else is a plain second: it only counts while running. */ if (!running) { return; } if (left > 1) { left -= 1; return; } var next = (phase === 'work') ? finishWork() : 'work'; begin(next); } function state() { return { phase: phase, left: left, running: running, done: done }; } return { tick: tick, state: state }; } </script> <script> (function () { 'use strict'; var game = createGame(); var NAMES = { work: 'Focus', short: 'Short break', long: 'Long break' }; var TOTALS = { work: 1800, short: 300, long: 900 }; var phaseEl = document.getElementById('phase'); var timeEl = document.getElementById('time'); var arcEl = document.getElementById('arc'); var countEl = document.getElementById('count'); var startBtn = document.getElementById('start'); var pauseBtn = document.getElementById('pause'); var skipBtn = document.getElementById('skip'); var resetBtn = document.getElementById('reset'); function pad2(n) { return n < 10 ? '0' + n : String(n); } function formatTime(totalSeconds) { var s = Math.max(0, Math.floor(totalSeconds)); return pad2(Math.floor(s / 60)) + ':' + pad2(s % 60); } function draw() { var s = game.state(); phaseEl.textContent = NAMES[s.phase] || ''; timeEl.textContent = formatTime(s.left); countEl.textContent = 'Focus periods done: ' + s.done; var full = TOTALS[s.phase] || TOTALS.work; var offset = 100 * (1 - s.left / full); if (offset < 0) { offset = 0; } if (offset > 100) { offset = 100; } arcEl.setAttribute('stroke-dashoffset', offset.toFixed(2)); startBtn.disabled = s.running === true; pauseBtn.disabled = s.running !== true; } var audioCtx = null; function getAudio() { try { var Ctor = window.AudioContext || window.webkitAudioContext; if (!Ctor) { return null; } if (!audioCtx) { audioCtx = new Ctor(); } if (audioCtx.state === 'suspended') { audioCtx.resume(); } return audioCtx; } catch (e) { return null; } } function chime() { var ctx = getAudio(); if (!ctx) { return; } try { var t0 = ctx.currentTime; var out = ctx.createGain(); out.gain.value = 0.14; out.connect(ctx.destination); var notes = [784, 1046.5]; for (var i = 0; i < notes.length; i++) { var osc = ctx.createOscillator(); var env = ctx.createGain(); var at = t0 + i * 0.16; osc.type = 'sine'; osc.frequency.value = notes[i]; env.gain.setValueAtTime(0.0001, at); env.gain.exponentialRampToValueAtTime(1, at + 0.02); env.gain.exponentialRampToValueAtTime(0.0001, at + 0.6); osc.connect(env); env.connect(out); osc.start(at); osc.stop(at + 0.65); } } catch (e) { /* sound is optional */ } } function run(step) { var before = game.state(); step(); var after = game.state(); if (before.phase !== after.phase) { chime(); } draw(); } function tickOnce() { run(function () { game.tick(); }); } function command(name) { run(function () { game.tick(name); }); } startBtn.addEventListener('click', function () { command('start'); }); pauseBtn.addEventListener('click', function () { command('pause'); }); skipBtn.addEventListener('click', function () { command('skip'); }); resetBtn.addEventListener('click', function () { command('reset'); }); draw(); setInterval(tickOnce, 1000); })(); </script> </body> </html> ```
Writing code 3 of 3
Merge intervalsPassed
1,197 tokens: 170 read, 1,027 written · 4 s · 231 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.
```javascript function mergeIntervals(intervals) { if (!Array.isArray(intervals) || intervals.length === 0) { return []; } // Copy each pair so we never mutate the input, then sort by start. const sorted = intervals .map(([start, end]) => [start, end]) .sort((a, b) => a[0] - b[0]); // Build result starting from a fresh copy of the first interval. const result = [sorted[0].slice()]; for (let i = 1; i < sorted.length; i++) { const [start, end] = sorted[i]; const last = result[result.length - 1]; // Overlap or touch (one ends where the next starts): merge. if (start <= last[1]) { if (end > last[1]) { last[1] = end; } } else { result.push([start, end]); } } return result; } ```An LRU cachePassed
912 tokens: 178 read, 734 written · 4 s · 189 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; // Map preserves insertion order: first key = least recently used, // last key = most recently used. this.map = new Map(); } get(key) { if (!this.map.has(key)) { return -1; } const value = this.map.get(key); // Re-insert to move the key to the end (most recently used). this.map.delete(key); this.map.set(key, value); return value; } put(key, value) { // Remove existing entry so the re-insert marks it most recently used. if (this.map.has(key)) { this.map.delete(key); } this.map.set(key, value); // Evict the least recently used key (the first one) if over capacity. if (this.map.size > this.capacity) { const oldestKey = this.map.keys().next().value; this.map.delete(oldestKey); } } } ```Evaluate arithmeticPassed
2,257 tokens: 206 read, 2,051 written · 8 s · 256 tok/s
Write a JavaScript function evaluate(expr) that returns the value of an arithmetic expression given as a string. The expression has non-negative integers, the operators + - * /, parentheses, unary minus (as in -3, - -3, 2 * -3 or -(1 + 2)) and spaces anywhere between tokens. * and / bind tighter than + and -, and operators of the same kind group from the left. / is integer division that truncates toward zero: 7 / 2 is 3 and -7 / 2 is -3. Dividing by zero must throw an Error. Do not use eval or Function. evaluate("2 + 3 * (4 - 6) / 4") returns 1. Reply with one ```js code block holding plain JavaScript (no imports, no exports, no DOM, no timers). The site runs it with hidden tests.```js function evaluate(expr) { const s = expr; let i = 0; // --- Tokenize --- const tokens = []; while (i < s.length) { const c = s[i]; if (c === ' ' || c === '\t' || c === '\n' || c === '\r') { i++; continue; } if (c >= '0' && c <= '9') { let num = ''; while (i < s.length && s[i] >= '0' && s[i] <= '9') { num += s[i]; i++; } tokens.push({ type: 'num', value: parseInt(num, 10) }); continue; } if (c === '+' || c === '-' || c === '*' || c === '/' || c === '(' || c === ')') { tokens.push({ type: c }); i++; continue; } throw new Error('Unexpected character: ' + c); } let pos = 0; const peek = () => tokens[pos]; const next = () => tokens[pos++]; // expression := term (('+' | '-') term)* function parseExpression() { let value = parseTerm(); while (peek() && (peek().type === '+' || peek().type === '-')) { const op = next().type; const rhs = parseTerm(); value = op === '+' ? value + rhs : value - rhs; } return value; } // term := factor (('*' | '/') factor)* function parseTerm() { let value = parseFactor(); while (peek() && (peek().type === '*' || peek().type === '/')) { const op = next().type; const rhs = parseFactor(); if (op === '*') { value = value * rhs; } else { if (rhs === 0) throw new Error('Division by zero'); value = Math.trunc(value / rhs); // truncate toward zero } } return value; } // factor := '-' factor | '(' expression ')' | number function parseFactor() { const t = peek(); if (!t) throw new Error('Unexpected end of expression'); if (t.type === '-') { next(); return -parseFactor(); } if (t.type === '+') { next(); return parseFactor(); } if (t.type === 'num') { next(); return t.value; } if (t.type === '(') { next(); const value = parseExpression(); if (!peek() || peek().type !== ')') throw new Error('Expected )'); next(); return value; } throw new Error('Unexpected token: ' + t.type); } if (tokens.length === 0) throw new Error('Empty expression'); const result = parseExpression(); if (pos < tokens.length) throw new Error('Unexpected trailing input'); return result; } ```
Fixing code 1 of 2
Fix the bookings modulePassed
1,528 tokens: 623 read, 905 written · 4 s · 208 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.The bug is in `bookedNights`. Its contract says "nights from `from` up to, but not including, `to`", i.e. the half-open range `[from, to)`. But the loop condition uses `<=`, so it also checks the `to` day itself. If that final day happens to be booked (which is common, since bookings are contiguous), the count is one too high. The fix is to make the loop half-open, matching the documented range (and matching how `price` iterates over a booking's nights): ```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; } ``` The single change: in `bookedNights`, `day <= dayNumber(to)` became `day < dayNumber(to)`.Fix the CSV readerFailed
2,331 tokens: 476 read, 1,855 written · 8 s · 244 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.The bug is in `parseLine`. The condition for the "inside a quoted field" branch reads: ```js if (quoted && ch !== ',') { ``` The `&& ch !== ','` part deliberately steers commas *out* of the quoted-content branch, so a comma inside quotes falls through to the field-separator branch and splits the field. It should just be `if (quoted)`. A comma only matters as a separator when the parser is *not* inside quotes, which the `else if (ch === ',')` branch already handles correctly. ```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
648 tokens: 235 read, 413 written · 3 s · 131 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 GROUP BY c.id, c.name HAVING COUNT(CASE WHEN o.status = 'delivered' THEN 1 END) = 0; ```
Schedule five meetingsPassed
5,143 tokens: 286 read, 4,857 written · 17 s · 278 tok/s
Five people each have one meeting today: Eli, Jon, Kim, Lea, Noa. 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: Maple, Oak, Pine, Rowan, Willow. 1. Kim's meeting is in the slot right after Noa's. 2. Kim meets earlier than Jon. 3. Whoever is in Pine meets earlier than Eli. 4. Noa is not in Maple. 5. Kim is not in Rowan. 6. Lea's meeting is in the slot right after Eli's. 7. Noa is not in Oak. 8. Whoever is in Maple meets earlier than Lea. 9. Jon's and Lea's rooms are next to each other on the list of rooms. 10. Jon's and Kim's rooms are next to each other on the list of rooms. 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
## Reasoning **Step 1 — Pin down the times.** Clue 1 pairs Noa→Kim consecutively, and clue 6 pairs Eli→Lea consecutively. Jon takes the leftover slot. Testing all consecutive placements against clue 2 (Kim < Jon) leaves three candidates: - A) Noa 09, Kim 10, Eli 11, Lea 13, Jon 14 - B) Noa 09, Kim 10, Jon 11, Eli 13, Lea 14 - C) Eli 09, Lea 10, Noa 11, Kim 13, Jon 14 **Step 2 — Eliminate with room clues.** Clues 9 and 10 require Jon's room to sit between Kim's and Lea's on the room list (Maple–Oak–Pine–Rowan–Willow), so Jon must hold a middle room (Oak, Pine, or Rowan), with Kim and Lea as its two neighbors. - *Option A:* Jon can only be Oak or Rowan here. Oak forces Lea into Maple (impossible by clue 8); Rowan leaves only Maple/Oak for Noa, banned by clues 4 and 7. **Dead.** - *Option C:* Clue 3 needs someone before Eli in Pine, but Eli is first (09:00) — impossible. **Dead.** - *Option B:* Jon = **Pine** (middle room). Then clue 3 holds since Jon (11:00) is before Eli (13:00). Kim and Lea take Oak and Rowan; clue 5 (Kim ≠ Rowan) puts **Kim = Oak**, **Lea = Rowan**. Noa and Eli take Maple and Willow; clue 4 (Noa ≠ Maple) and clue 7 (Noa ≠ Oak) force **Noa = Willow**, **Eli = Maple**. Clue 8 checks out: Eli (13:00) before Lea (14:00). **Everything fits.** This is the only consistent arrangement. ## Solution Noa: 09:00, Willow Kim: 10:00, Oak Jon: 11:00, Pine Eli: 13:00, Maple Lea: 14:00, Rowan
A replacement in ten calls or fewerPassed
10,640 tokens: 9,922 read, 718 written · 17 s · 42.3 tok/s
Hi, it's cal.reyes@example.com. My kettle arrived with a cracked lid. Can you sort it out?
- 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.
- user
Hi, it's cal.reyes@example.com. My kettle arrived with a cracked lid. Can you sort it out?
- assistant
lookup_account({"email": "cal.reyes@example.com"}) - tool
{"account_id": "AC-457", "name": "Cal Reyes"} - assistant
list_orders({"account_id": "AC-457"}) - tool
{"orders": [{"order_id": "R-5524", "placed": "2026-10-11", "status": "delivered"}, {"order_id": "R-5307", "placed": "2026-10-09", "status": "delivered"}, {"order_id": "R-5696", "placed": "2026-10-06", "status": "in transit"}]} - assistant
get_order({"order_id": "R-5524"})get_order({"order_id": "R-5307"})get_order({"order_id": "R-5696"}) - tool
{"items": [{"name": "Oak table lamp", "quantity": 1, "sku": "lamp-oak"}], "order_id": "R-5524"} - tool
{"items": [{"name": "Steel kettle", "quantity": 1, "sku": "kettle-steel"}, {"name": "Grey mug", "quantity": 2, "sku": "mug-grey"}], "order_id": "R-5307"} - tool
{"items": [{"name": "Copper kettle", "quantity": 1, "sku": "kettle-copper"}], "order_id": "R-5696"} - assistant
check_stock({"sku": "kettle-steel", "warehouse": "north"}) - tool
{"available": 0, "sku": "kettle-steel", "warehouse": "north"} - assistant
check_stock({"sku": "kettle-steel", "warehouse": "south"}) - tool
{"available": 3, "sku": "kettle-steel", "warehouse": "south"} - assistant
reserve_item({"order_id": "R-5307", "sku": "kettle-steel", "warehouse": "south"}) - tool
{"reservation_id": "RS-4449", "ships_on": "2026-11-08"} - assistant
create_return({"order_id": "R-5307", "reason": "kettle-steel arrived with a cracked lid"}) - tool
{"error": "damaged items are not returned: open a damage claim with open_claim instead"} - assistant
open_claim({"order_id": "R-5307", "reason": "Steel kettle arrived with a cracked lid"}) - tool
{"claim_id": "CL-6593", "order_id": "R-5307", "status": "open"} - assistant
Hi Cal, I found the steel kettle on order R-5307 (delivered, placed 2026-10-09), so that's the one we're sorting out. - Replacement: your Steel kettle is being sent from our south warehouse. Reservation reference RS-4449, and it ships on 2026-11-08. - Damaged item: since it arrived damaged, we don't take it back. I opened damage claim CL-6593 for the order instead, so no need to return the cracked kettle. Is there anything else I can help with?
- system
Comments
Sign in or create an account to comment.