nvidia/nemotron-3-ultra-550b-a55b:free run
OpenRouter · OpenCode 2.2.7 · every run of this model · uwu · 2026-11-13
Run nvidia/nemotron-3-ultra-550b-a55b:free on your computer to see the two side by side.
A full run: 50 tasks, 82 points
- Score
- 3,453 Gold Speed times the share of points, times 100. Platinum starts at 6,000: 76.9 tok/s with these answers. How scores work44.2 tok/s × 78% 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
- 42/50
- Points
- 64/82Harder tasks count 3. How scores work
- Tokens
- 111,35233,066 read, 78,286 written.
- Speed
- 44.2 tok/sTokens a second, as the runner measured it. The site checks only that the machine could reach it. How speeds are checked
- Summarizing 4/5
- Extracting 5/5
- Following instructions 5/5
- Reasoning 5/5
- Reading code 4/4
- Using tools 4/5
- Building pages 4/5
- Building games 1/4
- Building apps 2/4
- Writing code 3/3
- Fixing code 2/2
- Planning and data 3/3
Run details
Flag this run
Failed 8
Meeting notes in three bulletsFailed
747 tokens: 196 read, 551 written · 9 s · 58.5 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, product team. Present: Pablo, Luis, Emeka, Kofi. - Emeka reported that the payment provider fixed the invoice bug; no action needed. - The launch date moves from February 12 to February 17 because the supplier delivery slipped. - Kofi showed the new onboarding screens. Everyone liked them. Small copy changes only. - The marketing budget of $22,000 was approved by finance on Monday. - Pablo will own end-to-end testing from now on; Luis hands over the test plan by Tuesday. - Next sync is moved to Wednesday at 09:15. - Coffee machine on floor 2 is broken again.
- Launch date shifted to Feb 17; marketing budget $22k approved; next sync Wednesday 09:15. - Pablo assumes end‑to‑end testing ownership; Luis delivers test plan by Tuesday. - Onboarding screens approved with minor copy tweaks; payment invoice bug resolved.
Two calls for two answersFailed
1,728 tokens: 1,324 read, 404 written · 8 s · 49.8 tok/s
Convert 150 GBP to JPY and to CHF.
- user
Convert 150 GBP to JPY and to CHF.
- assistant
convert_currency({"to":"JPY","amount":150,"from":"GBP"}) - tool
{"amount": 27994, "currency": "JPY"} - assistant
convert_currency({"to":"CHF","from":"GBP","amount":150}) - tool
{"amount": 163.95, "currency": "CHF"} - assistant
**Currency Conversion Results for 150 GBP:** | From | To | Amount | Converted Amount | |------|-----|--------|------------------| | GBP | JPY | 150 | **27,994 JPY** | | GBP | CHF | 150 | **163.95 CHF** | *Rates based on today's exchange rates.*
- user
A pricing table with a toggleFailed
277 tokens: 220 read, 57 written · 17 s · 3.4 tok/s
Build a pricing page with three plans, in this order: Studio at $4 a month or $40 a year, Max at $24 a month or $240 a year and Basic at $26 a month or $260 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.
Build 2048Failed
4,465 tokens: 454 read, 4,011 written · 1 min 10 s · 57.4 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. [2, 0, 0, 0] [0, 0, 2, 4] [4, 2, 0, 0] [4, 0, 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.0"> <title>2048</title> <style> * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: system-ui, sans-serif; background: #faf8ef; min-height: 100vh; display: flex; flex-direction: column; align-items: center; padding: 20px; } h1 { color: #776e65; margin-bottom: 10px; } .score-container { background: #bbada0; border-radius: 6px; padding: 10px 20px; color: white; font-weight: bold; margin-bottom: 20px; } .board { background: #bbada0; border-radius: 6px; padding: 10px; display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; width: 400px; height: 400px; } .cell { background: #cdc1b4; border-radius: 4px; position: relative; } .tile { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 32px; transition: transform 0.1s, background 0.1s; user-select: none; } .tile-2 { background: #eee4da; color: #776e65; } .tile-4 { background: #ede0c8; color: #776e65; } .tile-8 { background: #f2b179; color: #f9f6f2; } .tile-16 { background: #f59563; color: #f9f6f2; } .tile-32 { background: #f67c5f; color: #f9f6f2; } .tile-64 { background: #f65e3b; color: #f9f6f2; } .tile-128 { background: #edcf72; color: #f9f6f2; font-size: 28px; } .tile-256 { background: #edcc61; color: #f9f6f2; font-size: 28px; } .tile-512 { background: #edc850; color: #f9f6f2; font-size: 28px; } .tile-1024 { background: #edc53f; color: #f9f6f2; font-size: 24px; } .tile-2048 { background: #edc22e; color: #f9f6f2; font-size: 24px; } .tile-4096, .tile-8192, .tile-16384 { background: #3c3a32; color: #f9f6f2; font-size: 20px; } .overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(238, 228, 218, 0.73); display: none; flex-direction: column; align-items: center; justify-content: center; z-index: 10; } .overlay.visible { display: flex; } .overlay-content { background: white; padding: 40px; border-radius: 6px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.2); } .overlay h2 { color: #776e65; margin-bottom: 10px; } .overlay p { color: #776e65; margin-bottom: 20px; } button { background: #8f7a66; color: white; border: none; border-radius: 4px; padding: 10px 20px; font-size: 16px; cursor: pointer; } button:hover { background: #7d6a58; } @media (max-width: 440px) { .board { width: 90vw; height: 90vw; max-width: 400px; max-height: 400px; } .tile { font-size: 24px; } .tile-128, .tile-256, .tile-512 { font-size: 20px; } .tile-1024, .tile-2048 { font-size: 18px; } } </style> </head> <body> <h1>2048</h1> <div class="score-container">Score: <span id="score">0</span></div> <div class="board" id="board"></div> <div class="overlay" id="overlay"> <div class="overlay-content"> <h2>Game Over</h2> <p>Final Score: <span id="final-score">0</span></p> <button id="restart">Play Again</button> </div> </div> <script id="game"> function createGame() { const initialBoard = [ [2, 0, 0, 0], [0, 0, 2, 4], [4, 2, 0, 0], [4, 0, 0, 0] ]; let board = initialBoard.map(row => [...row]); let score = 0; let over = false; function addInitialTwos() { let count = 0; for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (board[r][c] === 0) { board[r][c] = 2; count++; if (count === 2) return; } } } } function cloneBoard(b) { return b.map(row => [...row]); } function boardsEqual(a, b) { for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (a[r][c] !== b[r][c]) return false; } } return true; } function processLine(line) { const result = []; let mergeScore = 0; const filtered = line.filter(v => v !== 0); for (let i = 0; i < filtered.length; i++) { if (i + 1 < filtered.length && filtered[i] === filtered[i + 1]) { const merged = filtered[i] * 2; result.push(merged); mergeScore += merged; i++; } else { result.push(filtered[i]); } } while (result.length < 4) result.push(0); return { line: result, score: mergeScore }; } function moveLeft(b) { const newBoard = cloneBoard(b); let totalScore = 0; let changed = false; for (let r = 0; r < 4; r++) { const { line, score: lineScore } = processLine(newBoard[r]); totalScore += lineScore; if (!boardsEqual([newBoard[r]], [line])) changed = true; newBoard[r] = line; } return { board: newBoard, score: totalScore, changed }; } function moveRight(b) { const newBoard = b.map(row => [...row].reverse()); const { board, score, changed } = moveLeft(newBoard); return { board: board.map(row => [...row].reverse()), score, changed }; } function moveUp(b) { const newBoard = cloneBoard(b); let totalScore = 0; let changed = false; for (let c = 0; c < 4; c++) { const col = [newBoard[0][c], newBoard[1][c], newBoard[2][c], newBoard[3][c]]; const { line, score: lineScore } = processLine(col); totalScore += lineScore; const oldCol = [newBoard[0][c], newBoard[1][c], newBoard[2][c], newBoard[3][c]]; if (!boardsEqual([oldCol], [line])) changed = true; for (let r = 0; r < 4; r++) newBoard[r][c] = line[r]; } return { board: newBoard, score: totalScore, changed }; } function moveDown(b) { const newBoard = cloneBoard(b); let totalScore = 0; let changed = false; for (let c = 0; c < 4; c++) { const col = [newBoard[3][c], newBoard[2][c], newBoard[1][c], newBoard[0][c]]; const { line, score: lineScore } = processLine(col); totalScore += lineScore; const oldCol = [newBoard[3][c], newBoard[2][c], newBoard[1][c], newBoard[0][c]]; if (!boardsEqual([oldCol], [line])) changed = true; for (let r = 0; r < 4; r++) newBoard[3-r][c] = line[r]; } return { board: newBoard, score: totalScore, changed }; } function addRandomTwo(b) { for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (b[r][c] === 0) { b[r][c] = 2; return true; } } } return false; } function checkGameOver(b) { const dirs = ['up', 'down', 'left', 'right']; for (const dir of dirs) { let result; if (dir === 'left') result = moveLeft(b); else if (dir === 'right') result = moveRight(b); else if (dir === 'up') result = moveUp(b); else result = moveDown(b); if (result.changed) return false; } return true; } addInitialTwos(); return { move(dir) { if (over) return; let result; if (dir === 'left') result = moveLeft(board); else if (dir === 'right') result = moveRight(board); else if (dir === 'up') result = moveUp(board); else if (dir === 'down') result = moveDown(board); else return; if (result.changed) { board = result.board; score += result.score; addRandomTwo(board); over = checkGameOver(board); } }, state() { return { board: cloneBoard(board), score, over }; } }; } </script> <script> const game = createGame(); const boardEl = document.getElementById('board'); const scoreEl = document.getElementById('score'); const overlay = document.getElementById('overlay'); const finalScoreEl = document.getElementById('final-score'); const restartBtn = document.getElementById('restart'); function render() { const { board, score, over } = game.state(); scoreEl.textContent = score; boardEl.innerHTML = ''; for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { const cell = document.createElement('div'); cell.className = 'cell'; const val = board[r][c]; if (val !== 0) { const tile = document.createElement('div'); tile.className = `tile tile-${val}`; tile.textContent = val; cell.appendChild(tile); } boardEl.appendChild(cell); } } if (over) { finalScoreEl.textContent = score; overlay.classList.add('visible'); } else { overlay.classList.remove('visible'); } } function handleKey(e) { const dirMap = { 'ArrowUp': 'up', 'ArrowDown': 'down', 'ArrowLeft': 'left', 'ArrowRight': 'right' }; const dir = dirMap[e.key]; if (dir) { e.preventDefault(); game.move(dir); render(); } } restartBtn.addEventListener('click', () => { location.reload(); }); document.addEventListener('keydown', handleKey); render(); </script> </body> </html>Build SnakeFailed
3,026 tokens: 458 read, 2,568 written · 44 s · 57.8 tok/s
Build Snake as one web page on a 10 by 10 grid, playable with the arrow keys (one key press, one step), with the grid drawn on the page. In <script id="game">, define createGame() returning an object with step(dir) and state(). dir is "up", "down", "left" or "right". state() returns {snake, food, score, over}: snake is a list of [x, y] cells, head first; food is [x, y]; score is a number; over is a boolean. x is the column (0 to 9, left to right), y the row (0 to 9, top to bottom); up is y - 1. The rules, exactly: 1. The game starts with snake [[6, 3], [5, 3], [4, 3]], moving right, food at [6, 0], score 0. 2. step(dir): if dir is the opposite of the current direction it is ignored and the snake keeps going; otherwise dir becomes the current direction. The head moves one cell that way. 3. If the new head cell holds the food, the snake grows: its tail stays. Otherwise the tail cell is freed first. 4. If the new head is off the grid or on a cell of the snake (after rule 3), the game is over: over becomes true and nothing else changes. Once over, step does nothing. 5. Eating adds 1 to the score, and the next food goes to the first empty cell in reading order (row by row from the top, left to right) after the new head's cell, wrapping from [9, 9] to [0, 0]. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Snake</title> <style> * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: monospace; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; background: #1a1a2e; color: #eee; gap: 16px; } h1 { font-size: 1.5rem; letter-spacing: 2px; } .score { font-size: 1.2rem; } .grid { display: grid; grid-template-columns: repeat(10, 32px); grid-template-rows: repeat(10, 32px); gap: 1px; background: #16213e; border: 2px solid #0f3460; } .cell { width: 32px; height: 32px; background: #0f3460; } .cell.snake { background: #e94560; } .cell.snake.head { background: #ff6b6b; } .cell.food { background: #4ecca3; animation: pulse 1s infinite; } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } } .controls { font-size: 0.85rem; color: #888; text-align: center; } .game-over { position: fixed; inset: 0; background: rgba(0,0,0,0.85); display: none; flex-direction: column; align-items: center; justify-content: center; gap: 16px; z-index: 10; } .game-over.visible { display: flex; } .game-over h2 { font-size: 2rem; color: #e94560; } .game-over p { font-size: 1.2rem; } .game-over button { padding: 10px 24px; font-size: 1rem; background: #e94560; color: white; border: none; border-radius: 4px; cursor: pointer; } .game-over button:hover { background: #ff6b6b; } </style> </head> <body> <h1>SNAKE</h1> <div class="score">Score: <span id="score">0</span></div> <div class="grid" id="grid"></div> <div class="controls">Arrow keys to move — one press, one step</div> <div class="game-over" id="gameOver"> <h2>GAME OVER</h2> <p>Final Score: <span id="finalScore">0</span></p> <button id="restartBtn">Play Again</button> </div> <script id="game"> function createGame() { const GRID_SIZE = 10; let snake = [[6, 3], [5, 3], [4, 3]]; let direction = "right"; let food = [6, 0]; let score = 0; let over = false; const opposite = { up: "down", down: "up", left: "right", right: "left" }; function nextHead(head, dir) { const [x, y] = head; switch (dir) { case "up": return [x, y - 1]; case "down": return [x, y + 1]; case "left": return [x - 1, y]; case "right": return [x + 1, y]; } } function isOnSnake(cell, snakeArr) { return snakeArr.some(([sx, sy]) => sx === cell[0] && sy === cell[1]); } function findNextFood(startX, startY, snakeArr) { const startIndex = startY * GRID_SIZE + startX; for (let offset = 1; offset <= GRID_SIZE * GRID_SIZE; offset++) { const idx = (startIndex + offset) % (GRID_SIZE * GRID_SIZE); const x = idx % GRID_SIZE; const y = Math.floor(idx / GRID_SIZE); if (!isOnSnake([x, y], snakeArr)) { return [x, y]; } } return null; } function step(dir) { if (over) return; if (opposite[dir] === direction) { dir = direction; } else { direction = dir; } const head = snake[0]; const newHead = nextHead(head, direction); const [nx, ny] = newHead; if (nx < 0 || nx >= GRID_SIZE || ny < 0 || ny >= GRID_SIZE) { over = true; return; } const eating = nx === food[0] && ny === food[1]; if (eating) { snake.unshift(newHead); score += 1; food = findNextFood(nx, ny, snake); } else { snake.unshift(newHead); snake.pop(); if (isOnSnake(newHead, snake)) { over = true; return; } } } function state() { return { snake: snake.map(([x, y]) => [x, y]), food: [...food], score, over }; } return { step, state }; } </script> <script> const game = createGame(); const gridEl = document.getElementById("grid"); const scoreEl = document.getElementById("score"); const finalScoreEl = document.getElementById("finalScore"); const gameOverEl = document.getElementById("gameOver"); const restartBtn = document.getElementById("restartBtn"); const cells = []; for (let y = 0; y < 10; y++) { for (let x = 0; x < 10; x++) { const cell = document.createElement("div"); cell.className = "cell"; cell.dataset.x = x; cell.dataset.y = y; gridEl.appendChild(cell); cells.push(cell); } } function getCell(x, y) { return cells[y * 10 + x]; } function render() { const { snake, food, score, over } = game.state(); cells.forEach(c => c.className = "cell"); snake.forEach(([x, y], i) => { const cell = getCell(x, y); cell.classList.add("snake"); if (i === 0) cell.classList.add("head"); }); const [fx, fy] = food; getCell(fx, fy).classList.add("food"); scoreEl.textContent = score; if (over) { finalScoreEl.textContent = score; gameOverEl.classList.add("visible"); } } function handleKey(e) { const map = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right" }; const dir = map[e.key]; if (!dir) return; e.preventDefault(); game.step(dir); render(); } function restart() { // Re-run the game script to get a fresh createGame // Since createGame is a function, we can just call it again // But the script only defines it once. We'll recreate by re-evaluating? // Simpler: the game logic is pure, so we can just create a new instance. // However, the script tag only runs once. We'll store the factory. // Actually, createGame is already defined globally from the script. // We can just call it again. window.game = createGame(); gameOverEl.classList.remove("visible"); render(); } // Make createGame accessible globally for restart // The script#game defines createGame in global scope window.createGame = createGame; window.game = game; document.addEventListener("keydown", handleKey); restartBtn.addEventListener("click", restart); render(); </script> </body> </html>MinesweeperFailed
4,658 tokens: 1,437 read, 3,221 written · 1 min 3 s · 51.1 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; } body { margin: 0; min-height: 100vh; background: #fdf6e3; font-family: system-ui, sans-serif; color: #333; display: flex; flex-direction: column; align-items: center; padding: 16px; } h1 { margin: 0 0 8px; font-size: 1.5rem; } .rules { max-width: 360px; margin: 0 0 16px; font-size: 0.9rem; line-height: 1.5; color: #555; } .panel { background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); padding: 16px; width: 100%; max-width: 360px; } .status-line { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; font-size: 0.95rem; } .status-line .mines { font-weight: 600; } .status-line .state { font-weight: 600; } .state.playing { color: #333; } .state.won { color: #2e7d32; } .state.lost { color: #c62828; } #flag-mode { background: #fff; border: 2px solid #ccc; border-radius: 6px; padding: 8px 12px; font-size: 0.85rem; cursor: pointer; transition: all 0.15s; } #flag-mode[aria-pressed="true"] { background: #fce4ec; border-color: #ec407a; color: #c2185b; } #flag-mode:focus { outline: 2px solid #1976d2; outline-offset: 2px; } #board { display: block; width: 324px; height: 324px; background: #eee; border: 1px solid #ddd; border-radius: 4px; touch-action: none; } @media (max-width: 360px) { .panel { padding: 12px; } #board { width: 100%; height: auto; aspect-ratio: 1/1; } } </style> </head> <body> <h1>Minesweeper</h1> <p class="rules">Open cells by clicking. Numbers show how many mines touch that cell. Open a cell with no adjacent mines and it spreads automatically. Right-click or use Flag mode to place flags. Win by opening all safe cells. Lose by opening a mine.</p> <div class="panel" role="region" aria-label="Game board"> <div class="status-line" role="status" aria-live="polite" id="status"> <span class="mines">Mines left: <span id="mines-left">10</span></span> <span class="state playing" id="game-state">Playing</span> </div> <button id="flag-mode" aria-pressed="false">Flag mode: off</button> <canvas id="board" width="324" height="324" aria-label="Minesweeper board" tabindex="0"></canvas> </div> <script id="game"> const MINE_LAYOUT = [ "*........", ".........", "*...*..*.", "....*....", "**.......", ".........", "...*.**..", ".........", "........." ]; function createGame() { const mines = new Set(); for (let r = 0; r < 9; r++) { for (let c = 0; c < 9; c++) { if (MINE_LAYOUT[r][c] === '*') mines.add(r * 9 + c); } } const opened = new Array(81).fill(false); const flagged = new Array(81).fill(false); let status = "playing"; function idx(r, c) { return r * 9 + c; } function inBounds(r, c) { return r >= 0 && r < 9 && c >= 0 && c < 9; } function countAdjacentMines(r, c) { let n = 0; for (let dr = -1; dr <= 1; dr++) { for (let dc = -1; dc <= 1; dc++) { if (dr === 0 && dc === 0) continue; const nr = r + dr, nc = c + dc; if (inBounds(nr, nc) && mines.has(idx(nr, nc))) n++; } } return n; } function floodOpen(r, c) { const queue = [[r, c]]; while (queue.length) { const [cr, cc] = queue.shift(); const i = idx(cr, cc); if (opened[i] || flagged[i]) continue; opened[i] = true; const adj = countAdjacentMines(cr, cc); if (adj === 0) { for (let dr = -1; dr <= 1; dr++) { for (let dc = -1; dc <= 1; dc++) { if (dr === 0 && dc === 0) continue; const nr = cr + dr, nc = cc + dc; if (inBounds(nr, nc) && !opened[idx(nr, nc)] && !flagged[idx(nr, nc)]) { queue.push([nr, nc]); } } } } } } function checkWin() { for (let i = 0; i < 81; i++) { if (!mines.has(i) && !opened[i]) return false; } return true; } function press(move) { if (status !== "playing") return; const [kind, r, c] = move; const i = idx(r, c); if (kind === "open") { if (flagged[i] || opened[i]) return; if (mines.has(i)) { status = "lost"; return; } const adj = countAdjacentMines(r, c); if (adj === 0) { floodOpen(r, c); } else { opened[i] = true; } if (checkWin()) status = "won"; } else if (kind === "flag") { if (opened[i]) return; flagged[i] = !flagged[i]; } } function state() { const cells = []; let flaggedCount = 0; for (let r = 0; r < 9; r++) { let rowStr = ""; for (let c = 0; c < 9; c++) { const i = idx(r, c); const isMine = mines.has(i); if (status === "won" && isMine) { rowStr += "F"; flaggedCount++; } else if (status === "lost" && isMine) { rowStr += "*"; if (flagged[i]) flaggedCount++; } else if (flagged[i]) { rowStr += "F"; flaggedCount++; } else if (opened[i]) { const adj = countAdjacentMines(r, c); rowStr += adj === 0 ? "." : String(adj); } else { rowStr += "#"; } } cells.push(rowStr); } const minesLeft = 10 - flaggedCount; return { cells, status, mines_left: minesLeft }; } return { press, state }; } </script> <script> const game = createGame(); const canvas = document.getElementById("board"); const ctx = canvas.getContext("2d"); const minesLeftEl = document.getElementById("mines-left"); const gameStateEl = document.getElementById("game-state"); const flagModeBtn = document.getElementById("flag-mode"); let flagMode = false; const CELL_SIZE = 36; const BOARD_SIZE = 324; function draw() { const { cells, status, mines_left } = game.state(); ctx.clearRect(0, 0, BOARD_SIZE, BOARD_SIZE); // Draw grid ctx.strokeStyle = "#ccc"; ctx.lineWidth = 1; for (let i = 0; i <= 9; i++) { const pos = i * CELL_SIZE; ctx.beginPath(); ctx.moveTo(pos, 0); ctx.lineTo(pos, BOARD_SIZE); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, pos); ctx.lineTo(BOARD_SIZE, pos); ctx.stroke(); } // Draw cell contents ctx.font = "bold 20px system-ui, sans-serif"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; for (let r = 0; r < 9; r++) { const row = cells[r]; for (let c = 0; c < 9; c++) { const ch = row[c]; const x = c * CELL_SIZE + CELL_SIZE / 2; const y = r * CELL_SIZE + CELL_SIZE / 2; if (ch === "#" || ch === ".") continue; if (ch >= "1" && ch <= "8") { const colors = ["", "#1976d2", "#388e3c", "#d32f2f", "#7b1fa2", "#f57c00", "#0097a7", "#5d4037", "#616161"]; ctx.fillStyle = colors[parseInt(ch)]; ctx.fillText(ch, x, y + 1); } else if (ch === "F") { ctx.fillStyle = "#ec407a"; ctx.fillText("🚩", x, y + 1); } else if (ch === "*") { ctx.fillStyle = "#c62828"; ctx.fillText("💣", x, y + 1); } } } // Update status minesLeftEl.textContent = mines_left; gameStateEl.textContent = status.charAt(0).toUpperCase() + status.slice(1); gameStateEl.className = "state " + status; } function getCellFromEvent(e) { const rect = canvas.getBoundingClientRect(); const scaleX = canvas.width / rect.width; const scaleY = canvas.height / rect.height; const clientX = e.touches ? e.touches[0].clientX : e.clientX; const clientY = e.touches ? e.touches[0].clientY : e.clientY; const x = (clientX - rect.left) * scaleX; const y = (clientY - rect.top) * scaleY; const col = Math.floor(x / CELL_SIZE); const row = Math.floor(y / CELL_SIZE); if (row >= 0 && row < 9 && col >= 0 && col < 9) { return [row, col]; } return null; } function handlePress(row, col, kind) { game.press([kind, row, col]); draw(); } canvas.addEventListener("click", (e) => { const cell = getCellFromEvent(e); if (!cell) return; const [row, col] = cell; handlePress(row, col, flagMode ? "flag" : "open"); }); canvas.addEventListener("contextmenu", (e) => { e.preventDefault(); const cell = getCellFromEvent(e); if (!cell) return; const [row, col] = cell; handlePress(row, col, "flag"); }); flagModeBtn.addEventListener("click", () => { flagMode = !flagMode; flagModeBtn.textContent = "Flag mode: " + (flagMode ? "on" : "off"); flagModeBtn.setAttribute("aria-pressed", flagMode); }); canvas.addEventListener("keydown", (e) => { // Simple keyboard support: arrow keys to navigate would be complex // Just handle F for flag on focused cell? But canvas is single focusable. // For simplicity, we'll skip full keyboard nav as it's "welcome but not checked" if (e.key === "f" || e.key === "F") { // Could implement but not required } }); draw(); </script> </body> </html>Step sequencerFailed
4,849 tokens: 1,322 read, 3,527 written · 1 min 19 s · 44.5 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 1001000010001010 snare 0000100100101000 hat 1011101010111010 The rules, exactly: 1. At the start, playing is false, playhead is 0 and hits is []. 2. press([track, step]) toggles one cell: track 0 is kick, 1 snare, 2 hat; step is 0 to 15, where 0 is the first step. Toggling changes the pattern and nothing else. 3. press('play') does nothing when playing is already true. Otherwise it sets playing to true, and hits becomes the list of track numbers (0 kick, 1 snare, 2 hat) whose cell at the playhead is 1, in ascending order ([] when there are none). So the step under the playhead sounds as play starts. 4. press('stop') sets playing to false, playhead to 0 and hits to []. 5. press('tick') does nothing unless playing is true. When it is, playhead goes on by one, and after 15 it goes back to 0. hits becomes the list of track numbers whose cell at the new playhead is 1, in ascending order ([] when there are none). 6. Any other cmd does nothing: a list that is not exactly two whole numbers (such as [0, 1, 2], [1], [] or [true, 0]), null, a number, true or false, a word other than play, stop or tick, and a track or step outside the ranges above. Track and step are whole numbers. state() returns {playing, playhead, hits, pattern}: playing is true or false; playhead is 0 to 15; hits lists the track numbers set by the last tick or by the play that started playback, in ascending order ([] at the start and after stop); pattern is three strings of 16 characters, kick first, each character 1 or 0. The page: - Each step button is a real button with the attributes data-track (0, 1 or 2) and data-step (0 to 15), and aria-pressed set to true or false to match its state. A click calls press([track, step]), and after every press, the page draws from state(). - A step that is on has the class on, and the stylesheet fills it dark; a step that is off has no class on. - Play has the id play and Stop the id stop. Play calls press('play') and starts one timer that calls press('tick') every 125 ms: 120 quarter-note beats a minute, four steps to a beat. Stop calls press('stop') and clears the timer. Each play and each tick sounds the hits that state() then reports, and nothing else sounds. - Play has the disabled attribute while playing, and Stop has it while stopped. - A status line with the id status reads "Stopped", or "Playing, step N of 16" with N the playhead plus 1. Give it a fixed height, so the grid does not move when its text changes. - A span with the id announce, set to aria-live polite, is empty until playback starts for the first time. From then on it says "Playing" when playback starts and "Stopped" when it stops, and changes at no other time. - The cells in the playhead column have the class playhead while playing, and no cell has it while stopped. - The numbers 1 to 16, as text, sit above the grid, and the playhead's number is pink. Under 720 px each step shows its number. - When the page becomes hidden, it presses Stop, so nothing sounds in a background tab. - Each track in hits plays its drum: kick is a falling sine tone, snare a short noise burst with a low body tone, hat a short high noise burst. Tones use oscillators; noise bursts use buffer sources playing a buffer of random samples: the kick is one oscillator, the snare one buffer source and one oscillator, the hat one buffer source. Hits that land together must not clip, so put a gain or a limiter before the output. Create the AudioContext inside the first click (browsers need a click before they make sound), and resume it if it is suspended. - Flat and plain: a light background, dark ink, no shadows or gradients, Play the one pink button (#b31f57), and the playhead cell outlined in pink where you are. At 1280 px the 16 steps sit in one row; under 720 px they form two bars of 8. The page never scrolls sideways. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and drives the sequencer through createGame(). Wire the page in another <script>.Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Step sequencer</title> <style> :root { --pink:#b31f57; --ink:#111; --bg:#fafafa; --cell:60px; --gap:4px; } *{box-sizing:border-box;margin:0;padding:0} body{font-family:system-ui,sans-serif;background:var(--bg);color:var(--ink);min-height:100vh;display:flex;flex-direction:column;align-items:center;padding:24px 12px} h1{font-size:1.5rem;margin-bottom:16px;font-weight:600} .seq{display:flex;flex-direction:column;align-items:center;gap:12px;width:100%;max-width:1200px} .track{display:flex;align-items:center;gap:var(--gap);flex-wrap:wrap;justify-content:center} .track-label{width:4.5ch;text-align:right;font-size:.85rem;font-variant-numeric:tabular-nums;color:#555;user-select:none} .step{width:var(--cell);height:var(--cell);border:2px solid #ccc;background:#fff;border-radius:4px;cursor:pointer;transition:background .1s,border-color .1s;display:flex;align-items:center;justify-content:center;font-size:.75rem;color:#666;position:relative} .step:focus-visible{outline:2px solid var(--pink);outline-offset:2px} .step.on{background:var(--ink);border-color:var(--ink);color:#fff} .step.playhead{box-shadow:0 0 0 3px var(--pink);z-index:1} .step.playhead::after{content:"";position:absolute;inset:-5px;border:2px solid var(--pink);border-radius:6px;pointer-events:none} .controls{display:flex;gap:12px;margin-top:8px} button{padding:10px 28px;font-size:1rem;border:none;border-radius:4px;cursor:pointer;transition:opacity .15s} button:disabled{opacity:.45;cursor:not-allowed} #play{background:var(--pink);color:#fff} #stop{background:#eee;color:var(--ink);border:1px solid #ccc} #status{height:1.5em;font-size:.9rem;color:#555;text-align:center;width:100%;max-width:1200px} #announce{position:absolute;left:-9999px} .step-numbers{display:flex;gap:var(--gap);justify-content:center;flex-wrap:wrap;width:100%;max-width:calc(16*var(--cell)+15*var(--gap));padding-left:calc(4.5ch+var(--gap));margin-bottom:4px} .step-num{width:var(--cell);height:24px;display:flex;align-items:center;justify-content:center;font-size:.75rem;color:#888;font-variant-numeric:tabular-nums} .step-num.playhead{color:var(--pink);font-weight:700} @media (max-width:1280px){ :root{--cell:52px} } @media (max-width:720px){ :root{--cell:44px} .track{flex-wrap:wrap} .step-numbers{display:none} .step::before{content:attr(data-step-num);position:absolute;top:-16px;left:50%;transform:translateX(-50%);font-size:.65rem;color:#888;white-space:nowrap} .step.playhead::before{color:var(--pink);font-weight:700} } @media (max-width:480px){ :root{--cell:38px} button{padding:10px 16px;font-size:.9rem} .track-label{width:4ch;font-size:.75rem} } </style> </head> <body> <h1>Step sequencer</h1> <div class="seq"> <div class="step-numbers" id="stepNumbers"></div> <div class="track" id="track0"><span class="track-label">Kick</span></div> <div class="track" id="track1"><span class="track-label">Snare</span></div> <div class="track" id="track2"><span class="track-label">Hat</span></div> <div class="controls"> <button id="play" disabled>Play</button> <button id="stop" disabled>Stop</button> </div> <div id="status">Stopped</div> <span id="announce" aria-live="polite"></span> </div> <script id="game"> function createGame(){ const pattern = [ "1001000010001010".split("").map(Number), "0000100100101000".split("").map(Number), "1011101010111010".split("").map(Number) ]; let playing = false; let playhead = 0; let hits = []; function press(cmd){ if(Array.isArray(cmd) && cmd.length===2 && Number.isInteger(cmd[0]) && Number.isInteger(cmd[1])){ const [track, step] = cmd; if(track>=0 && track<=2 && step>=0 && step<=15){ pattern[track][step] ^= 1; } return; } if(cmd==="play"){ if(playing) return; playing = true; hits = []; for(let t=0;t<3;t++) if(pattern[t][playhead]) hits.push(t); return; } if(cmd==="stop"){ playing = false; playhead = 0; hits = []; return; } if(cmd==="tick"){ if(!playing) return; playhead = (playhead+1)%16; hits = []; for(let t=0;t<3;t++) if(pattern[t][playhead]) hits.push(t); return; } } function state(){ return { playing, playhead, hits: [...hits], pattern: pattern.map(row=>row.join("")) }; } return {press, state}; } </script> <script> const game = createGame(); let audioCtx = null; let tickTimer = null; let hasStarted = false; const trackEls = [document.getElementById("track0"), document.getElementById("track1"), document.getElementById("track2")]; const playBtn = document.getElementById("play"); const stopBtn = document.getElementById("stop"); const statusEl = document.getElementById("status"); const announceEl = document.getElementById("announce"); const stepNumbersEl = document.getElementById("stepNumbers"); function initAudio(){ if(audioCtx) return; audioCtx = new (window.AudioContext||window.webkitAudioContext)(); const masterGain = audioCtx.createGain(); masterGain.gain.value = 0.5; masterGain.connect(audioCtx.destination); audioCtx.masterGain = masterGain; } function resumeAudio(){ if(audioCtx && audioCtx.state==="suspended") audioCtx.resume(); } function playKick(time){ const osc = audioCtx.createOscillator(); const gain = audioCtx.createGain(); osc.type = "sine"; osc.frequency.setValueAtTime(150, time); osc.frequency.exponentialRampToValueAtTime(40, time+0.5); gain.gain.setValueAtTime(1, time); gain.gain.exponentialRampToValueAtTime(0.001, time+0.5); osc.connect(gain).connect(audioCtx.masterGain); osc.start(time); osc.stop(time+0.55); } function playSnare(time){ const bufferSize = audioCtx.sampleRate * 0.2; const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate); const data = buffer.getChannelData(0); for(let i=0;i<bufferSize;i++) data[i] = (Math.random()*2-1) * Math.exp(-i/bufferSize*8); const noise = audioCtx.createBufferSource(); noise.buffer = buffer; const noiseGain = audioCtx.createGain(); noiseGain.gain.setValueAtTime(0.6, time); noiseGain.gain.exponentialRampToValueAtTime(0.001, time+0.2); noise.connect(noiseGain).connect(audioCtx.masterGain); noise.start(time); noise.stop(time+0.22); const osc = audioCtx.createOscillator(); const oscGain = audioCtx.createGain(); osc.type = "sine"; osc.frequency.setValueAtTime(180, time); osc.frequency.exponentialRampToValueAtTime(80, time+0.15); oscGain.gain.setValueAtTime(0.4, time); oscGain.gain.exponentialRampToValueAtTime(0.001, time+0.15); osc.connect(oscGain).connect(audioCtx.masterGain); osc.start(time); osc.stop(time+0.17); } function playHat(time){ const bufferSize = audioCtx.sampleRate * 0.06; const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate); const data = buffer.getChannelData(0); for(let i=0;i<bufferSize;i++) data[i] = (Math.random()*2-1) * Math.exp(-i/bufferSize*20); const noise = audioCtx.createBufferSource(); noise.buffer = buffer; const gain = audioCtx.createGain(); gain.gain.setValueAtTime(0.35, time); gain.gain.exponentialRampToValueAtTime(0.001, time+0.06); noise.connect(gain).connect(audioCtx.masterGain); noise.start(time); noise.stop(time+0.07); } function playHits(hits, time){ if(hits.includes(0)) playKick(time); if(hits.includes(1)) playSnare(time); if(hits.includes(2)) playHat(time); } function render(){ const s = game.state(); for(let t=0;t<3;t++){ const steps = trackEls[t].querySelectorAll(".step"); steps.forEach((btn, i)=>{ const on = s.pattern[t][i]==="1"; btn.classList.toggle("on", on); btn.setAttribute("aria-pressed", on); btn.classList.toggle("playhead", s.playing && i===s.playhead); }); } playBtn.disabled = s.playing; stopBtn.disabled = !s.playing; statusEl.textContent = s.playing ? `Playing, step ${s.playhead+1} of 16` : "Stopped"; const nums = stepNumbersEl.querySelectorAll(".step-num"); nums.forEach((el, i)=> el.classList.toggle("playhead", s.playing && i===s.playhead)); } function buildUI(){ for(let t=0;t<3;t++){ const track = trackEls[t]; for(let i=0;i<16;i++){ const btn = document.createElement("button"); btn.type="button"; btn.className="step"; btn.dataset.track = t; btn.dataset.step = i; btn.dataset.stepNum = i+1; btn.setAttribute("aria-pressed","false"); btn.textContent = ""; btn.addEventListener("click",()=>{ initAudio(); resumeAudio(); game.press([t,i]); render(); }); track.appendChild(btn); } } for(let i=1;i<=16;i++){ const span = document.createElement("span"); span.className="step-num"; span.textContent = i; stepNumbersEl.appendChild(span); } playBtn.addEventListener("click",()=>{ initAudio(); resumeAudio(); if(!hasStarted){ hasStarted=true; announceEl.textContent="Playing"; } game.press("play"); const st = game.state(); playHits(st.hits, audioCtx.currentTime); render(); if(tickTimer) clearInterval(tickTimer); tickTimer = setInterval(()=>{ game.press("tick"); const s = game.state(); playHits(s.hits, audioCtx.currentTime); render(); },125); }); stopBtn.addEventListener("click",()=>{ if(tickTimer){ clearInterval(tickTimer); tickTimer=null; } game.press("stop"); render(); if(hasStarted) announceEl.textContent="Stopped"; }); document.addEventListener("visibilitychange",()=>{ if(document.hidden){ if(tickTimer){ clearInterval(tickTimer); tickTimer=null; } game.press("stop"); render(); if(hasStarted) announceEl.textContent="Stopped"; } }); render(); } buildUI(); </script> </body> </html>Grow a branching plantFailed
1,273 tokens: 1,253 read, 20 written · 5 s · 3.9 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.
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.Failed · 4.5k tokens · 57.4 tok/s
-
Build SnakeRuns a game where a snake grows and the game ends on a crash.Failed · 3k tokens · 57.8 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 · 5.9k tokens · 36.5 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.Failed · 4.7k tokens · 51.1 tok/s
-
A small websiteLays out a small website with a menu and a footer.Passed · 1.9k tokens · 34.3 tok/s
-
An accessible sign-up formChecks a sign-up form and labels each of its fields.Passed · 2.5k tokens · 78.1 tok/s
-
A to-do app that remembersKeeps data across a reload.Passed · 1.3k tokens · 48.5 tok/s
-
A bar chart in SVGDraws data to scale.Passed · 2k tokens · 72.4 tok/s
-
Step sequencerShows whether a model can keep a beat in time, step by step.Failed · 4.8k tokens · 44.5 tok/s
-
Falling sandShows whether a model can follow exact falling rules, cell by cell and frame by frame.Passed · 12k tokens · 60.7 tok/s
-
Focus timerShows whether a model keeps a focus timer exact through pauses, skips and resets.Passed · 12k tokens · 46.5 tok/s
Scored tasks
Summarizing 4 of 5
One-sentence summaryPassed
438 tokens: 116 read, 322 written · 7 s · 49.4 tok/s
Summarize this in one sentence of at most 30 words. Starting January 23, the Cresswell Public Library will open at 6:35 a.m. instead of 9:15 a.m. on weekdays. The change follows a survey in which 79% of respondents asked for earlier hours. Weekend hours stay the same. The library will hire three part-time staff to cover the extra time, paid for by a grant from the city council.
Starting January 23, Cresswell Public Library will open weekdays at 6:35 a.m. after a survey showed 79% wanted earlier hours, adding three grant-funded part-time staff.
Meeting notes in three bulletsFailed
747 tokens: 196 read, 551 written · 9 s · 58.5 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, product team. Present: Pablo, Luis, Emeka, Kofi. - Emeka reported that the payment provider fixed the invoice bug; no action needed. - The launch date moves from February 12 to February 17 because the supplier delivery slipped. - Kofi showed the new onboarding screens. Everyone liked them. Small copy changes only. - The marketing budget of $22,000 was approved by finance on Monday. - Pablo will own end-to-end testing from now on; Luis hands over the test plan by Tuesday. - Next sync is moved to Wednesday at 09:15. - Coffee machine on floor 2 is broken again.
- Launch date shifted to Feb 17; marketing budget $22k approved; next sync Wednesday 09:15. - Pablo assumes end‑to‑end testing ownership; Luis delivers test plan by Tuesday. - Onboarding screens approved with minor copy tweaks; payment invoice bug resolved.
Review sentiment and complaintPassed
316 tokens: 128 read, 188 written · 4 s · 51.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 keyboard every day for a month. Honestly, it is light and easy to carry and it feels much more solid than its price. But the tilt foot that came in the box wore through in a month, and support took 10 days to reply. I bought a replacement tilt foot myself. Would I buy it again? Probably, but I'm annoyed.
Sentiment: mixed Complaint: tilt foot broke quickly and slow support response
Faithful summary of a studyPassed
568 tokens: 141 read, 427 written · 8 s · 55.9 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, 700 adults with chronic migraine took either Veltra or a placebo for 24 weeks. Those on Veltra had 2.8 fewer headache days per month on average, compared with 0.3 fewer days for placebo. Dry mouth was the most common side effect, reported by 12% of the drug group. The authors note the trial lasted only 24 weeks and call for longer studies before any recommendation is made.
A randomized trial of 700 chronic migraine adults over 24 weeks found Veltra reduced headache days by 2.8 monthly versus 0.3 for placebo. Dry mouth affected 12% of Veltra patients. Authors urge longer studies before recommendations due to the short duration.
Action items from an email threadPassed
646 tokens: 218 read, 428 written · 18 s · 23.3 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: Sofia Hi all, quick recap of what's still open for the autumn summit. I'll send the revised contract to the hotel by Friday. From: Tom I can book the venue for the dinner if that helps? From: Cal Thanks Tom, 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: Eli I'll update the budget sheet with the new hotel price tonight. From: Sofia Great. Oh, and I'll email the caterer about the vegetarian options. Tom, could you just double-check the date on the invitations? Actually never mind, I checked them this morning, they're correct.
- Sofia: send the revised contract to the hotel by Friday - Cal: book the venue for the dinner - Eli: update the budget sheet with the new hotel price tonight - Sofia: email the caterer about the vegetarian options
Extracting 5 of 5
Fields from an email as JSONPassed
464 tokens: 125 read, 339 written · 9 s · 39.7 tok/s
Extract these fields from the email as a JSON object with exactly these keys: "name" (the sender's full name), "company", "meeting_date" (YYYY-MM-DD) and "attendees" (a number). Output only the JSON. Hello! This is Amara Moreau from Silverpine Media. We'd love to visit your workshop. Could we meet on the 7th of January 2025, any time after lunch? We'll be eight people in total, including me. Best, Amara
{ "name": "Amara Moreau", "company": "Silverpine Media", "meeting_date": "2025-01-07", "attendees": 8 }Every email address, oncePassed
713 tokens: 149 read, 564 written · 13 s · 43.6 tok/s
List every email address written out in full in this text (like name@example.com), one per line, in the order they first appear, without duplicates. Leave out any inbox the text says is closed. Output only the addresses. Contacts for the conference: write to hello@harbor-events.net for general questions, or to program@harbor-events.net if you are presenting. Our designer (tariq.c@brightpoint.co) made the poster. Billing questions: finance@harbor-events.net. Again, presenters use program@harbor-events.net. Please don't write to sol at harbor dot net, that inbox is closed.
hello@harbor-events.net program@harbor-events.net tariq.c@brightpoint.co finance@harbor-events.net
A list as CSVPassed
398 tokens: 110 read, 288 written · 5 s · 61.2 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 @ $1.40 Oats (500 g) - 11 @ $5.65 Butter (250 g) - 22 @ $7.10 Tomatoes - 1 @ $7.40
item,qty,price Yogurt,16,1.40 Oats (500 g),11,5.65 Butter (250 g),22,7.10 Tomatoes,1,7.40
The real deadlinePassed
212 tokens: 107 read, 105 written · 5 s · 19.3 tok/s
What is the final submission deadline? Answer with the date only, in YYYY-MM-DD format. The call for papers opened on 3 January 2025. Drafts were originally due June 24, but the committee extended the final submission deadline to 25 June 2025. Reviews are due by 23 July, and results will be announced on August 12, 2025.
2025-06-25
Warnings and errors from a logPassed
961 tokens: 287 read, 674 written · 11 s · 61.2 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-11-18 09:48:11 INFO server started on port 5432 2025-11-18 09:51:10 WARN config key "pool size" is deprecated 2025-11-18 09:57:07 INFO user tariq logged in 2025-11-18 09:57:59 ERROR database connection lost 2025-11-18 10:01:36 INFO retrying in 30s 2025-11-18 10:03:51 INFO database reconnected 2025-11-18 10:05:20 DEBUG cache hit ratio 0.94 2025-11-18 10:07:27 ERROR payment webhook returned 504
[ { "time": "09:51:10", "level": "WARN", "message": "config key \"pool size\" is deprecated" }, { "time": "09:57:59", "level": "ERROR", "message": "database connection lost" }, { "time": "10:07:27", "level": "ERROR", "message": "payment webhook returned 504" } ]
Following instructions 5 of 5
Exactly one wordPassed
56 tokens: 28 read, 28 written · 2 s · 15.1 tok/s
Reply with exactly the word Agreed and nothing else.
Agreed
Three lowercase linesPassed
1,942 tokens: 95 read, 1,847 written · 53 s · 35 tok/s
Write exactly three lines about a marsh. Use the word marsh in every line. Start every line with the letter q, and do not use any of these words: station, waterfall, pond, quarry, meadow, dune, winter, forest, market or sea. Every line must be entirely lowercase, and the third line must end with a question mark. Output only the three lines.
quiet mist drifts over the marsh at dawn quivering reeds whisper across the marsh silently questing firefly glows near the marsh?
Exact JSON shapePassed
378 tokens: 68 read, 310 written · 7 s · 47.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 z and use only the plain letters a to z, and "count", the number 2. Output only the JSON.
{"words":["zebra","zenith"],"count":2}Sort a listPassed
206 tokens: 51 read, 155 written · 8 s · 20.5 tok/s
Sort these words alphabetically, ignoring case. Output only the sorted words, on one line separated by commas: carrot, Orange, leek, onion, Cherry.
carrot, Cherry, leek, onion, Orange
A name with three rulesPassed
806 tokens: 78 read, 728 written · 18 s · 41.3 tok/s
Suggest a product name for a solar-powered fan. 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 U, and the letter p must not appear anywhere. Output only the name.
Radiant Umbra
Reasoning 5 of 5
Unit pricePassed
498 tokens: 62 read, 436 written · 8 s · 56.8 tok/s
A shop sells pencils at 4 for $0.80. How much do 10 pencils cost, in dollars? Work it out, then end with a line "ANSWER: <number>".
The cost for 4 pencils is $0.80. Cost per pencil = $0.80 ÷ 4 = $0.20. Cost for 10 pencils = 10 × $0.20 = $2.00. ANSWER: 2
Day and datePassed
5,367 tokens: 76 read, 5,291 written · 2 min 13 s · 39.8 tok/s
Today is Thursday, 17 December 2026. What day of the week, and what date, is it 111 days from today? Work it out, then end with a line "ANSWER: <day of the week>, <YYYY-MM-DD>".
We start from Thursday, 17 December 2026. Adding 111 days: - Days left in December 2026 after 17th: 31 – 17 = 14 days (18–31 Dec). 111 – 14 = 97 days remain after 31 December. - The 97 days are added starting from 1 January 2027 (since 31 Dec + 1 day = 1 Jan). Actually, after using 14 days to reach 31 Dec, we have 97 days to add to 31 Dec, which is equivalent to adding 96 days to 1 Jan. - January 2027: 31 days → 96 – 31 = 65 days left, date becomes 1 February. - February 2027 (non‑leap): 28 days → 65 – 28 = 37 days left, date becomes 1 March. - March 2027: 31 days → 37 – 31 = 6 days left, date becomes 1 April. - Add the remaining 6 days to 1 April → 7 April 2027. Day of the week: 111 ≡ 6 (mod 7). Thursday + 6 days = Wednesday. Verification with Zeller’s congruence for 7 April 2027 also gives Wednesday. ANSWER: Wednesday, 2027-04-07
Who owns each petPassed
807 tokens: 193 read, 614 written · 15 s · 39.7 tok/s
Five people, Jon, Eli, Ana, Ivy and Hal, 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 owns the bird or the rabbit. - Ana owns the cat or the bird. - Ivy does not own the cat. - Ana owns the cat or the rabbit. - Hal owns the fish or the rabbit. - Jon owns the cat or the fish. - Eli owns the cat or the bird. - Ana does not own the dog. Who owns each pet? Work it out, then end with a line "ANSWER: <owner of the cat>, <owner of the dog>, <owner of the fish>, <owner of the bird>, <owner of the rabbit>", with the five names in that order, separated by commas.
ANSWER: Ana, Ivy, Jon, Eli, Hal
Arrival timePassed
354 tokens: 71 read, 283 written · 7 s · 42.5 tok/s
A train leaves at 20:15 and the trip takes 1 hour 10 minutes. At what time does it arrive? Work it out, then end with a line "ANSWER: <HH:MM>" in 24-hour time.
The train departs at 20:15. Adding 1 hour gives 21:15. Adding 10 minutes gives 21:25. ANSWER: 21:25
Filling a tankPassed
380 tokens: 97 read, 283 written · 4 s · 64.2 tok/s
A tank holds 312 liters and starts empty. Pipe A adds 22 liters an hour, pipe B adds 6 liters an hour, and a drain takes 16 liters an hour out of it. With all three open, how many hours until the tank is full? Work it out, then end with a line "ANSWER: <number>".
The net fill rate with all three open is 22 + 6 - 16 = 12 liters per hour. The tank capacity is 312 liters. Time to fill = 312 / 12 = 26 hours. ANSWER: 26
Reading code 4 of 4
What does it printPassed
659 tokens: 94 read, 565 written · 11 s · 51.1 tok/s
What numbers does this Python program print, in order? Work it out, then end with a line "ANSWER: <numbers, separated by commas>". def f(xs): return sorted(xs)[::-1][:3] print(f([35, 34, 42, 39, 10, 28]))The function `f` sorts the list in ascending order, reverses it to get descending order, and then takes the first three elements (the three largest numbers). For the input `[35, 34, 42, 39, 10, 28]`, the sorted list is `[10, 28, 34, 35, 39, 42]`, reversed gives `[42, 39, 35, 34, 28, 10]`, and the first three are `42, 39, 35`. The program prints these numbers as a list. ANSWER: 42, 39, 35
Trace a loopPassed
763 tokens: 97 read, 666 written · 17 s · 39.9 tok/s
What does this Python program print? Work it out, then end with a line "ANSWER: <output>". def g(n): total = 0 for i in range(1, n + 1): if i % 2 == 0 or i % 8 == 0: total += i return total print(g(67))The function `g(n)` sums all integers `i` from 1 to `n` that satisfy `i % 2 == 0 or i % 8 == 0`. Since any number divisible by 8 is also divisible by 2, the condition is equivalent to `i % 2 == 0`. Thus `g(67)` is the sum of even numbers from 2 to 66 inclusive. There are 33 even numbers (2, 4, ..., 66). Their sum is \(33 \times 34 = 1122\). ANSWER: 1122
Find the bugPassed
1,105 tokens: 112 read, 993 written · 25 s · 39.6 tok/s
The function biggest should return the largest number in a non-empty 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 biggest(readings): best = readings[0] for item in readings: if item < best: best = item return bestThe bug is in the comparison: the function updates `best` when `item < best`, which finds the minimum. To find the maximum, it should update when `item > best`. ANSWER: if item > best:
Run a query in your headPassed
448 tokens: 149 read, 299 written · 10 s · 30.2 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 | 115 2 | ana | 30 3 | cal | 45 4 | ben | 55 5 | cal | 35 6 | ben | 130 Query: SELECT customer, SUM(amount) AS total FROM orders GROUP BY customer HAVING SUM(amount) > 100 ORDER BY total DESC;
ben,185 ana,145
Using tools 4 of 5
Call one toolPassed
849 tokens: 731 read, 118 written · 3 s · 37 tok/s
What's the weather in Perth right now, in celsius?
- user
What's the weather in Perth right now, in celsius?
- assistant
get_weather({"city":"Perth","unit":"celsius"}) - tool
{"city": "Perth", "conditions": "sunny", "temperature": 27, "unit": "celsius"} - assistant
The current weather in Perth is **sunny** with a temperature of **27°C**.
- user
Don't call a tool when none is neededPassed
527 tokens: 460 read, 67 written · 2 s · 36.4 tok/s
What is 30 times 26?
- user
What is 30 times 26?
- assistant
30 × 26 = 780
- user
Two calls for two answersFailed
1,728 tokens: 1,324 read, 404 written · 8 s · 49.8 tok/s
Convert 150 GBP to JPY and to CHF.
- user
Convert 150 GBP to JPY and to CHF.
- assistant
convert_currency({"to":"JPY","amount":150,"from":"GBP"}) - tool
{"amount": 27994, "currency": "JPY"} - assistant
convert_currency({"to":"CHF","from":"GBP","amount":150}) - tool
{"amount": 163.95, "currency": "CHF"} - assistant
**Currency Conversion Results for 150 GBP:** | From | To | Amount | Converted Amount | |------|-----|--------|------------------| | GBP | JPY | 150 | **27,994 JPY** | | GBP | CHF | 150 | **163.95 CHF** | *Rates based on today's exchange rates.*
- user
Chain two toolsPassed
1,568 tokens: 1,281 read, 287 written · 8 s · 36.5 tok/s
What is the status of each order for the customer with the email lee.morgan@example.com?
- user
What is the status of each order for the customer with the email lee.morgan@example.com?
- assistant
find_customer({"email":"lee.morgan@example.com"}) - tool
{"customer_id": "C-2291", "name": "Lee Morgan"} - assistant
get_orders({"customer_id":"C-2291"}) - tool
{"orders": [{"carrier": "DHL", "order_id": "A-67", "status": "shipped"}, {"order_id": "A-62", "status": "delivered"}]} - assistant
Based on the customer information, Lee Morgan (customer ID: C-2291) has two orders with the following statuses: | Order ID | Status | Carrier | |----------|--------|---------| | A-67 | **shipped** | DHL | | A-62 | **delivered** | (not specified) | So order A-67 is currently shipped via DHL, and order A-62 has been delivered.
- user
Handle a failed call honestlyPassed
1,115 tokens: 823 read, 292 written · 10 s · 28 tok/s
Book a table for 2 people at Casa Lumen tonight at 18:45. If that time is not free, do not book another time without asking me first.
- user
Book a table for 2 people at Casa Lumen tonight at 18:45. If that time is not free, do not book another time without asking me first.
- assistant
book_table({"people":2,"restaurant":"Casa Lumen","time":"18:45"}) - tool
{"available_times": ["18:15", "20:15"], "error": "fully booked at that time"} - assistant
I tried to book a table for 2 at Casa Lumen at 18:45, but that time is fully booked. The restaurant has availability at **18:15** and **20:15** instead. Would you like me to book one of those times for you, or would you prefer to check another option?
- user
Building pages 4 of 5
A small websitePassed
1,855 tokens: 193 read, 1,662 written · 48 s · 34.3 tok/s
Build a one-page website for a bakery called "Golden Bakery". It must have a <header> containing an <h1> with the bakery's name; a <nav> with exactly 3 links; a <main> with a <section id="menu"> listing at least 4 items in a list, including Banana bread, Rosemary bread, Bagel and Scone; and a <footer> with the opening hours. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.
Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Golden Bakery</title> <style> body {font-family: Arial, sans-serif; margin:0; padding:0; line-height:1.6; color:#333;} header {background:#f5e6c8; padding:1rem; text-align:center;} header h1 {margin:0; font-size:2.5rem; color:#5d4037;} nav {background:#8d6e63; padding:0.5rem; text-align:center;} nav a {color:#fff; text-decoration:none; margin:0 1rem; font-weight:bold;} nav a:hover {text-decoration:underline;} main {padding:1rem; max-width:800px; margin:auto;} section {margin-bottom:2rem;} section h2 {color:#5d4037; border-bottom:2px solid #8d6e63; padding-bottom:0.3rem;} ul.menu {list-style:none; padding:0;} ul.menu li {background:#fff8e1; margin:0.5rem 0; padding:0.8rem; border-left:5px solid #ffb300;} footer {background:#5d4037; color:#fff; text-align:center; padding:1rem; margin-top:2rem;} </style> </head> <body> <header> <h1>Golden Bakery</h1> </header> <nav> <a href="#menu">Menu</a> <a href="#about">About</a> <a href="#contact">Contact</a> </nav> <main> <section id="menu"> <h2>Our Menu</h2> <ul class="menu"> <li>Banana bread</li> <li>Rosemary bread</li> <li>Bagel</li> <li>Scone</li> </ul> </section> <section id="about"> <h2>About Us</h2> <p>Golden Bakery has been serving fresh, handcrafted baked goods since 2010.</p> </section> <section id="contact"> <h2>Contact</h2> <p>Visit us at 123 Flour Lane, Sweet Town.</p> </section> </main> <footer> <p>Opening Hours: Mon–Fri 7:00 am–7:00 pm, Sat 8:00 am–6:00 pm, Sun 9:00 am–3:00 pm</p> </footer> <script> console.log('Golden Bakery page loaded'); </script> </body> </html>A pricing table with a toggleFailed
277 tokens: 220 read, 57 written · 17 s · 3.4 tok/s
Build a pricing page with three plans, in this order: Studio at $4 a month or $40 a year, Max at $24 a month or $240 a year and Basic at $26 a month or $260 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.
An accessible sign-up formPassed
2,457 tokens: 257 read, 2,200 written · 28 s · 78.1 tok/s
Build a sign-up form for Orchard 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>Orchard Works — Sign Up</title> <style> * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif; background: #f5f2eb; color: #2d2a26; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; } .container { width: 100%; max-width: 420px; } .brand { text-align: center; margin-bottom: 2.5rem; } .brand h1 { font-size: 2.25rem; font-weight: 700; color: #1a1815; letter-spacing: -0.02em; } .brand p { color: #6b655d; font-size: 1rem; margin-top: 0.5rem; } #signup { background: #ffffff; border: 1px solid #e8e4dc; border-radius: 12px; padding: 2rem; } .field { margin-bottom: 1.25rem; } .field:last-of-type { margin-bottom: 1.5rem; } label { display: block; font-size: 0.875rem; font-weight: 500; color: #3d3a35; margin-bottom: 0.5rem; } input { width: 100%; padding: 0.75rem 1rem; font-size: 1rem; font-family: inherit; color: #1a1815; background: #faf9f6; border: 1px solid #d8d4cb; border-radius: 8px; transition: border-color 0.15s ease, box-shadow 0.15s ease, background-color 0.15s ease; } input:hover { border-color: #c4bfb5; } input:focus { outline: none; border-color: #2d7d46; background: #ffffff; box-shadow: 0 0 0 3px rgba(45, 125, 70, 0.15); } input::placeholder { color: #9a958b; } input[aria-invalid="true"] { border-color: #c0392b; background: #fdf7f7; } input[aria-invalid="true"]:focus { box-shadow: 0 0 0 3px rgba(192, 57, 43, 0.15); } button[type="submit"] { width: 100%; padding: 0.875rem 1.5rem; font-size: 1rem; font-weight: 600; font-family: inherit; color: #ffffff; background: #2d7d46; border: none; border-radius: 8px; cursor: pointer; transition: background-color 0.15s ease, transform 0.05s ease; } button[type="submit"]:hover { background: #256b3a; } button[type="submit"]:active { transform: scale(0.99); } button[type="submit"]:focus { outline: none; box-shadow: 0 0 0 3px rgba(45, 125, 70, 0.3); } #status { margin-top: 1rem; padding: 0.75rem 1rem; font-size: 0.875rem; line-height: 1.5; border-radius: 8px; min-height: 1.5em; } #status:empty { margin-top: 0; padding: 0; min-height: 0; } #status[aria-live="polite"] { background: #fdf7f7; border: 1px solid #f5c6c6; color: #c0392b; } @media (max-width: 480px) { body { padding: 1.5rem 1rem; } #signup { padding: 1.5rem; } .brand h1 { font-size: 1.75rem; } } </style> </head> <body> <div class="container"> <div class="brand"> <h1>Orchard Works</h1> <p>Create your account to get started</p> </div> <form id="signup" novalidate> <div class="field"> <label for="name">Full Name</label> <input type="text" id="name" name="name" placeholder="Enter your name" required autocomplete="name"> </div> <div class="field"> <label for="email">Email Address</label> <input type="email" id="email" name="email" placeholder="you@example.com" required autocomplete="email"> </div> <div class="field"> <label for="password">Password</label> <input type="password" id="password" name="password" placeholder="At least 8 characters" required minlength="8" autocomplete="new-password"> </div> <button type="submit">Create Account</button> <div id="status" role="status" aria-live="polite"></div> </form> </div> <script> (function() { const form = document.getElementById('signup'); const statusEl = document.getElementById('status'); const emailInput = document.getElementById('email'); const passwordInput = document.getElementById('password'); const nameInput = document.getElementById('name'); function showError(message, input) { statusEl.textContent = message; if (input) { input.setAttribute('aria-invalid', 'true'); input.focus(); } } function clearErrors() { statusEl.textContent = ''; [nameInput, emailInput, passwordInput].forEach(input => { input.removeAttribute('aria-invalid'); }); } function isValidEmail(email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); } form.addEventListener('submit', function(e) { e.preventDefault(); clearErrors(); const email = emailInput.value.trim(); const password = passwordInput.value; const name = nameInput.value.trim(); if (!name) { showError('Please enter your name.', nameInput); return; } if (!isValidEmail(email)) { showError('Please enter a valid email address.', emailInput); return; } if (password.length < 8) { showError('Password must be at least 8 characters long.', passwordInput); return; } // Form is valid - prevent real submission, leave status empty statusEl.textContent = ''; console.log('Form submitted:', { name, email }); // In a real app, you would send the data to your server here }); // Clear error on input [nameInput, emailInput, passwordInput].forEach(input => { input.addEventListener('input', function() { if (this.hasAttribute('aria-invalid')) { this.removeAttribute('aria-invalid'); if (statusEl.textContent) { statusEl.textContent = ''; } } }); }); })(); </script> </body> </html>A to-do app that remembersPassed
1,337 tokens: 188 read, 1,149 written · 24 s · 48.5 tok/s
Build a to-do list app called "Morning chores". Show its name in a heading. The app has an <input id="new-task">, a <button id="add"> and a <ul id="tasks">. Clicking add appends the text as an <li> with its own remove button. Save the list in localStorage under the key "todos" and load it again when the page opens. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.
Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Morning chores</title> <style> body { font-family: sans-serif; margin: 2rem; } h1 { margin-bottom: 1rem; } #new-task { padding: 0.5rem; width: 60%; max-width: 300px; } #add { padding: 0.5rem 1rem; margin-left: 0.5rem; cursor: pointer; } #tasks { list-style: none; padding: 0; margin-top: 1rem; } #tasks li { display: flex; justify-content: space-between; align-items: center; padding: 0.5rem; border-bottom: 1px solid #eee; } #tasks li:last-child { border-bottom: none; } .remove-btn { background: #ff4444; color: white; border: none; padding: 0.25rem 0.5rem; cursor: pointer; } </style> </head> <body> <h1>Morning chores</h1> <input type="text" id="new-task" placeholder="Enter a chore"> <button id="add">Add</button> <ul id="tasks"></ul> <script> const taskInput = document.getElementById('new-task'); const addButton = document.getElementById('add'); const taskList = document.getElementById('tasks'); const STORAGE_KEY = 'todos'; function loadTasks() { const data = localStorage.getItem(STORAGE_KEY); if (data) { try { const tasks = JSON.parse(data); tasks.forEach(text => createTaskElement(text)); } catch (e) { console.error('Failed to parse tasks', e); } } } function saveTasks() { const tasks = []; taskList.querySelectorAll('li').forEach(li => { // The text is the first child text node before the button const text = li.firstChild.textContent.trim(); tasks.push(text); }); localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks)); } function createTaskElement(text) { const li = document.createElement('li'); // Create a text node for the task text li.appendChild(document.createTextNode(text + ' ')); const removeBtn = document.createElement('button'); removeBtn.textContent = 'Remove'; removeBtn.className = 'remove-btn'; removeBtn.addEventListener('click', () => { li.remove(); saveTasks(); }); li.appendChild(removeBtn); taskList.appendChild(li); } addButton.addEventListener('click', () => { const text = taskInput.value.trim(); if (text) { createTaskElement(text); saveTasks(); taskInput.value = ''; } }); // Also allow pressing Enter in the input taskInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') { addButton.click(); } }); // Initial load loadTasks(); </script> </body> </html>A bar chart in SVGPassed
2,041 tokens: 241 read, 1,800 written · 25 s · 72.4 tok/s
Draw an inline SVG bar chart of scones sold, in this order: Tue 13, Wed 37, Thu 24, Fri 28 and Sat 32. 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.0"> <title>Scones Sold Bar Chart</title> <style> .bar { fill: #2c7be5; } .bar-label { font: 14px system-ui, sans-serif; fill: #333; text-anchor: middle; } .chart-title { font: bold 18px system-ui, sans-serif; fill: #333; text-anchor: middle; } .axis { stroke: #999; stroke-width: 1; } .grid-line { stroke: #eee; stroke-width: 1; } </style> </head> <body> <svg width="400" height="300" viewBox="0 0 400 300" aria-label="Bar chart of scones sold from Tuesday to Saturday. Tuesday 13, Wednesday 37, Thursday 24, Friday 28, Saturday 32."> <title>Scones Sold: Tue 13, Wed 37, Thu 24, Fri 28, Sat 32</title> <!-- Y-axis --> <line class="axis" x1="50" y1="50" x2="50" y2="250"/> <!-- X-axis --> <line class="axis" x1="50" y1="250" x2="380" y2="250"/> <!-- Grid lines and Y labels --> <line class="grid-line" x1="50" y1="50" x2="380" y2="50"/> <text x="40" y="55" font="12px system-ui, sans-serif" fill="#666" text-anchor="end">37</text> <line class="grid-line" x1="50" y1="100" x2="380" y2="100"/> <text x="40" y="105" font="12px system-ui, sans-serif" fill="#666" text-anchor="end">27.75</text> <line class="grid-line" x1="50" y1="150" x2="380" y2="150"/> <text x="40" y="155" font="12px system-ui, sans-serif" fill="#666" text-anchor="end">18.5</text> <line class="grid-line" x1="50" y1="200" x2="380" y2="200"/> <text x="40" y="205" font="12px system-ui, sans-serif" fill="#666" text-anchor="end">9.25</text> <text x="40" y="255" font="12px system-ui, sans-serif" fill="#666" text-anchor="end">0</text> <!-- Bars --> <!-- Tue: value 13, height = 13/37 * 200 = 70.27, y = 250 - 70.27 = 179.73 --> <rect class="bar" x="70" y="179.73" width="50" height="70.27"/> <text class="bar-label" x="95" y="270">Tue</text> <!-- Wed: value 37, height = 200, y = 50 --> <rect class="bar" x="140" y="50" width="50" height="200"/> <text class="bar-label" x="165" y="270">Wed</text> <!-- Thu: value 24, height = 24/37 * 200 = 129.73, y = 250 - 129.73 = 120.27 --> <rect class="bar" x="210" y="120.27" width="50" height="129.73"/> <text class="bar-label" x="235" y="270">Thu</text> <!-- Fri: value 28, height = 28/37 * 200 = 151.35, y = 250 - 151.35 = 98.65 --> <rect class="bar" x="280" y="98.65" width="50" height="151.35"/> <text class="bar-label" x="305" y="270">Fri</text> <!-- Sat: value 32, height = 32/37 * 200 = 172.97, y = 250 - 172.97 = 77.03 --> <rect class="bar" x="350" y="77.03" width="50" height="172.97"/> <text class="bar-label" x="375" y="270">Sat</text> <!-- Chart title --> <text class="chart-title" x="200" y="30">Scones Sold by Day</text> </svg> </body> </html>
Building games 1 of 4
Build 2048Failed
4,465 tokens: 454 read, 4,011 written · 1 min 10 s · 57.4 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. [2, 0, 0, 0] [0, 0, 2, 4] [4, 2, 0, 0] [4, 0, 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.0"> <title>2048</title> <style> * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: system-ui, sans-serif; background: #faf8ef; min-height: 100vh; display: flex; flex-direction: column; align-items: center; padding: 20px; } h1 { color: #776e65; margin-bottom: 10px; } .score-container { background: #bbada0; border-radius: 6px; padding: 10px 20px; color: white; font-weight: bold; margin-bottom: 20px; } .board { background: #bbada0; border-radius: 6px; padding: 10px; display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; width: 400px; height: 400px; } .cell { background: #cdc1b4; border-radius: 4px; position: relative; } .tile { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 32px; transition: transform 0.1s, background 0.1s; user-select: none; } .tile-2 { background: #eee4da; color: #776e65; } .tile-4 { background: #ede0c8; color: #776e65; } .tile-8 { background: #f2b179; color: #f9f6f2; } .tile-16 { background: #f59563; color: #f9f6f2; } .tile-32 { background: #f67c5f; color: #f9f6f2; } .tile-64 { background: #f65e3b; color: #f9f6f2; } .tile-128 { background: #edcf72; color: #f9f6f2; font-size: 28px; } .tile-256 { background: #edcc61; color: #f9f6f2; font-size: 28px; } .tile-512 { background: #edc850; color: #f9f6f2; font-size: 28px; } .tile-1024 { background: #edc53f; color: #f9f6f2; font-size: 24px; } .tile-2048 { background: #edc22e; color: #f9f6f2; font-size: 24px; } .tile-4096, .tile-8192, .tile-16384 { background: #3c3a32; color: #f9f6f2; font-size: 20px; } .overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(238, 228, 218, 0.73); display: none; flex-direction: column; align-items: center; justify-content: center; z-index: 10; } .overlay.visible { display: flex; } .overlay-content { background: white; padding: 40px; border-radius: 6px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.2); } .overlay h2 { color: #776e65; margin-bottom: 10px; } .overlay p { color: #776e65; margin-bottom: 20px; } button { background: #8f7a66; color: white; border: none; border-radius: 4px; padding: 10px 20px; font-size: 16px; cursor: pointer; } button:hover { background: #7d6a58; } @media (max-width: 440px) { .board { width: 90vw; height: 90vw; max-width: 400px; max-height: 400px; } .tile { font-size: 24px; } .tile-128, .tile-256, .tile-512 { font-size: 20px; } .tile-1024, .tile-2048 { font-size: 18px; } } </style> </head> <body> <h1>2048</h1> <div class="score-container">Score: <span id="score">0</span></div> <div class="board" id="board"></div> <div class="overlay" id="overlay"> <div class="overlay-content"> <h2>Game Over</h2> <p>Final Score: <span id="final-score">0</span></p> <button id="restart">Play Again</button> </div> </div> <script id="game"> function createGame() { const initialBoard = [ [2, 0, 0, 0], [0, 0, 2, 4], [4, 2, 0, 0], [4, 0, 0, 0] ]; let board = initialBoard.map(row => [...row]); let score = 0; let over = false; function addInitialTwos() { let count = 0; for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (board[r][c] === 0) { board[r][c] = 2; count++; if (count === 2) return; } } } } function cloneBoard(b) { return b.map(row => [...row]); } function boardsEqual(a, b) { for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (a[r][c] !== b[r][c]) return false; } } return true; } function processLine(line) { const result = []; let mergeScore = 0; const filtered = line.filter(v => v !== 0); for (let i = 0; i < filtered.length; i++) { if (i + 1 < filtered.length && filtered[i] === filtered[i + 1]) { const merged = filtered[i] * 2; result.push(merged); mergeScore += merged; i++; } else { result.push(filtered[i]); } } while (result.length < 4) result.push(0); return { line: result, score: mergeScore }; } function moveLeft(b) { const newBoard = cloneBoard(b); let totalScore = 0; let changed = false; for (let r = 0; r < 4; r++) { const { line, score: lineScore } = processLine(newBoard[r]); totalScore += lineScore; if (!boardsEqual([newBoard[r]], [line])) changed = true; newBoard[r] = line; } return { board: newBoard, score: totalScore, changed }; } function moveRight(b) { const newBoard = b.map(row => [...row].reverse()); const { board, score, changed } = moveLeft(newBoard); return { board: board.map(row => [...row].reverse()), score, changed }; } function moveUp(b) { const newBoard = cloneBoard(b); let totalScore = 0; let changed = false; for (let c = 0; c < 4; c++) { const col = [newBoard[0][c], newBoard[1][c], newBoard[2][c], newBoard[3][c]]; const { line, score: lineScore } = processLine(col); totalScore += lineScore; const oldCol = [newBoard[0][c], newBoard[1][c], newBoard[2][c], newBoard[3][c]]; if (!boardsEqual([oldCol], [line])) changed = true; for (let r = 0; r < 4; r++) newBoard[r][c] = line[r]; } return { board: newBoard, score: totalScore, changed }; } function moveDown(b) { const newBoard = cloneBoard(b); let totalScore = 0; let changed = false; for (let c = 0; c < 4; c++) { const col = [newBoard[3][c], newBoard[2][c], newBoard[1][c], newBoard[0][c]]; const { line, score: lineScore } = processLine(col); totalScore += lineScore; const oldCol = [newBoard[3][c], newBoard[2][c], newBoard[1][c], newBoard[0][c]]; if (!boardsEqual([oldCol], [line])) changed = true; for (let r = 0; r < 4; r++) newBoard[3-r][c] = line[r]; } return { board: newBoard, score: totalScore, changed }; } function addRandomTwo(b) { for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (b[r][c] === 0) { b[r][c] = 2; return true; } } } return false; } function checkGameOver(b) { const dirs = ['up', 'down', 'left', 'right']; for (const dir of dirs) { let result; if (dir === 'left') result = moveLeft(b); else if (dir === 'right') result = moveRight(b); else if (dir === 'up') result = moveUp(b); else result = moveDown(b); if (result.changed) return false; } return true; } addInitialTwos(); return { move(dir) { if (over) return; let result; if (dir === 'left') result = moveLeft(board); else if (dir === 'right') result = moveRight(board); else if (dir === 'up') result = moveUp(board); else if (dir === 'down') result = moveDown(board); else return; if (result.changed) { board = result.board; score += result.score; addRandomTwo(board); over = checkGameOver(board); } }, state() { return { board: cloneBoard(board), score, over }; } }; } </script> <script> const game = createGame(); const boardEl = document.getElementById('board'); const scoreEl = document.getElementById('score'); const overlay = document.getElementById('overlay'); const finalScoreEl = document.getElementById('final-score'); const restartBtn = document.getElementById('restart'); function render() { const { board, score, over } = game.state(); scoreEl.textContent = score; boardEl.innerHTML = ''; for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { const cell = document.createElement('div'); cell.className = 'cell'; const val = board[r][c]; if (val !== 0) { const tile = document.createElement('div'); tile.className = `tile tile-${val}`; tile.textContent = val; cell.appendChild(tile); } boardEl.appendChild(cell); } } if (over) { finalScoreEl.textContent = score; overlay.classList.add('visible'); } else { overlay.classList.remove('visible'); } } function handleKey(e) { const dirMap = { 'ArrowUp': 'up', 'ArrowDown': 'down', 'ArrowLeft': 'left', 'ArrowRight': 'right' }; const dir = dirMap[e.key]; if (dir) { e.preventDefault(); game.move(dir); render(); } } restartBtn.addEventListener('click', () => { location.reload(); }); document.addEventListener('keydown', handleKey); render(); </script> </body> </html>Build SnakeFailed
3,026 tokens: 458 read, 2,568 written · 44 s · 57.8 tok/s
Build Snake as one web page on a 10 by 10 grid, playable with the arrow keys (one key press, one step), with the grid drawn on the page. In <script id="game">, define createGame() returning an object with step(dir) and state(). dir is "up", "down", "left" or "right". state() returns {snake, food, score, over}: snake is a list of [x, y] cells, head first; food is [x, y]; score is a number; over is a boolean. x is the column (0 to 9, left to right), y the row (0 to 9, top to bottom); up is y - 1. The rules, exactly: 1. The game starts with snake [[6, 3], [5, 3], [4, 3]], moving right, food at [6, 0], score 0. 2. step(dir): if dir is the opposite of the current direction it is ignored and the snake keeps going; otherwise dir becomes the current direction. The head moves one cell that way. 3. If the new head cell holds the food, the snake grows: its tail stays. Otherwise the tail cell is freed first. 4. If the new head is off the grid or on a cell of the snake (after rule 3), the game is over: over becomes true and nothing else changes. Once over, step does nothing. 5. Eating adds 1 to the score, and the next food goes to the first empty cell in reading order (row by row from the top, left to right) after the new head's cell, wrapping from [9, 9] to [0, 0]. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Snake</title> <style> * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: monospace; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; background: #1a1a2e; color: #eee; gap: 16px; } h1 { font-size: 1.5rem; letter-spacing: 2px; } .score { font-size: 1.2rem; } .grid { display: grid; grid-template-columns: repeat(10, 32px); grid-template-rows: repeat(10, 32px); gap: 1px; background: #16213e; border: 2px solid #0f3460; } .cell { width: 32px; height: 32px; background: #0f3460; } .cell.snake { background: #e94560; } .cell.snake.head { background: #ff6b6b; } .cell.food { background: #4ecca3; animation: pulse 1s infinite; } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } } .controls { font-size: 0.85rem; color: #888; text-align: center; } .game-over { position: fixed; inset: 0; background: rgba(0,0,0,0.85); display: none; flex-direction: column; align-items: center; justify-content: center; gap: 16px; z-index: 10; } .game-over.visible { display: flex; } .game-over h2 { font-size: 2rem; color: #e94560; } .game-over p { font-size: 1.2rem; } .game-over button { padding: 10px 24px; font-size: 1rem; background: #e94560; color: white; border: none; border-radius: 4px; cursor: pointer; } .game-over button:hover { background: #ff6b6b; } </style> </head> <body> <h1>SNAKE</h1> <div class="score">Score: <span id="score">0</span></div> <div class="grid" id="grid"></div> <div class="controls">Arrow keys to move — one press, one step</div> <div class="game-over" id="gameOver"> <h2>GAME OVER</h2> <p>Final Score: <span id="finalScore">0</span></p> <button id="restartBtn">Play Again</button> </div> <script id="game"> function createGame() { const GRID_SIZE = 10; let snake = [[6, 3], [5, 3], [4, 3]]; let direction = "right"; let food = [6, 0]; let score = 0; let over = false; const opposite = { up: "down", down: "up", left: "right", right: "left" }; function nextHead(head, dir) { const [x, y] = head; switch (dir) { case "up": return [x, y - 1]; case "down": return [x, y + 1]; case "left": return [x - 1, y]; case "right": return [x + 1, y]; } } function isOnSnake(cell, snakeArr) { return snakeArr.some(([sx, sy]) => sx === cell[0] && sy === cell[1]); } function findNextFood(startX, startY, snakeArr) { const startIndex = startY * GRID_SIZE + startX; for (let offset = 1; offset <= GRID_SIZE * GRID_SIZE; offset++) { const idx = (startIndex + offset) % (GRID_SIZE * GRID_SIZE); const x = idx % GRID_SIZE; const y = Math.floor(idx / GRID_SIZE); if (!isOnSnake([x, y], snakeArr)) { return [x, y]; } } return null; } function step(dir) { if (over) return; if (opposite[dir] === direction) { dir = direction; } else { direction = dir; } const head = snake[0]; const newHead = nextHead(head, direction); const [nx, ny] = newHead; if (nx < 0 || nx >= GRID_SIZE || ny < 0 || ny >= GRID_SIZE) { over = true; return; } const eating = nx === food[0] && ny === food[1]; if (eating) { snake.unshift(newHead); score += 1; food = findNextFood(nx, ny, snake); } else { snake.unshift(newHead); snake.pop(); if (isOnSnake(newHead, snake)) { over = true; return; } } } function state() { return { snake: snake.map(([x, y]) => [x, y]), food: [...food], score, over }; } return { step, state }; } </script> <script> const game = createGame(); const gridEl = document.getElementById("grid"); const scoreEl = document.getElementById("score"); const finalScoreEl = document.getElementById("finalScore"); const gameOverEl = document.getElementById("gameOver"); const restartBtn = document.getElementById("restartBtn"); const cells = []; for (let y = 0; y < 10; y++) { for (let x = 0; x < 10; x++) { const cell = document.createElement("div"); cell.className = "cell"; cell.dataset.x = x; cell.dataset.y = y; gridEl.appendChild(cell); cells.push(cell); } } function getCell(x, y) { return cells[y * 10 + x]; } function render() { const { snake, food, score, over } = game.state(); cells.forEach(c => c.className = "cell"); snake.forEach(([x, y], i) => { const cell = getCell(x, y); cell.classList.add("snake"); if (i === 0) cell.classList.add("head"); }); const [fx, fy] = food; getCell(fx, fy).classList.add("food"); scoreEl.textContent = score; if (over) { finalScoreEl.textContent = score; gameOverEl.classList.add("visible"); } } function handleKey(e) { const map = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right" }; const dir = map[e.key]; if (!dir) return; e.preventDefault(); game.step(dir); render(); } function restart() { // Re-run the game script to get a fresh createGame // Since createGame is a function, we can just call it again // But the script only defines it once. We'll recreate by re-evaluating? // Simpler: the game logic is pure, so we can just create a new instance. // However, the script tag only runs once. We'll store the factory. // Actually, createGame is already defined globally from the script. // We can just call it again. window.game = createGame(); gameOverEl.classList.remove("visible"); render(); } // Make createGame accessible globally for restart // The script#game defines createGame in global scope window.createGame = createGame; window.game = game; document.addEventListener("keydown", handleKey); restartBtn.addEventListener("click", restart); render(); </script> </body> </html>Box-pushing puzzlePassed
5,855 tokens: 1,123 read, 4,732 written · 2 min 10 s · 36.5 tok/s
Build a box-pushing puzzle as one web page on an 8 by 7 grid, playable with the arrow keys, with the level drawn on the page. Give the page and its heading the title Box-pushing puzzle. In <script id="game">, define createGame() returning an object with walk(dir) and state(). dir is "up", "down", "left" or "right". state() returns {player, boxes, pushes, steps, solved}: player is [x, y]; boxes is a list of [x, y] sorted by row, then column; pushes and steps are numbers; solved is a boolean. x is the column (0 to 7, left to right), y the row (0 to 6, top to bottom); up is y - 1. The level, row 0 first, 8 characters to a row (a space is empty floor; the outer ring is all wall): ``` ######## # +## # #*$ # # # # ## $ . # # # ######## ``` # wall, space floor, . goal, $ box, * box on a goal, @ player, + player on a goal. The rules, exactly: 1. The game starts with this level, steps 0, pushes 0 and solved false. Walls and goals never change. 2. walk(dir) moves the player one cell in dir. If that cell is a wall, nothing changes and nothing is counted. A goal is floor, so the player can stand on one. 3. If that cell holds a box, the box moves one cell further in dir and the player takes the box's old cell. This push happens only if the cell beyond the box is empty floor or a goal: not a wall and not another box. Otherwise nothing changes and nothing is counted. 4. A walk that moves the player adds 1 to steps. A push is a walk too, so it adds 1 to pushes as well. 5. solved is true when every box is on a goal. Once solved, walk does nothing. The page: the arrow keys do the same walks as walk(dir), one walk for each key press (a key that repeats while held walks once). Four buttons with data-dir="up", data-dir="down", data-dir="left" and data-dir="right" do the same walks. Label them Up, Down, Left and Right, laid out like the arrow keys: Up above Down, with Left, Down and Right in one row. A button with id="restart", labelled Restart, starts the level over, with steps and pushes back at 0. The board is an element with id="board". It holds one element per cell, 56 in all, row by row from the top, 8 to a row, and nothing else. Each cell has role="img" and an aria-label that names what it holds: wall, empty floor, empty goal, box, box on a goal, you or you on a goal. Every cell except empty floor also shows a visible character as its text, so that a wall, a goal, a box and you can each be seen (the character is yours to choose). Show the steps in an element with id="steps" and the pushes in one with id="pushes", each as a plain number. The status line is an element with id="status". Until the level is solved, it must not say that it is solved (a line such as Not solved yet is fine). Once it is, it says solved, with the number of steps next to the word steps and the number of pushes next to the word pushes, for example: Solved in 12 steps with 3 pushes. A tenth of a second after each key press, button press or Restart, the board, the steps, the pushes and the status line show what state() says. A page may draw on the next animation frame or after a timer. The page must not use eval or Function, must not give a timer a string of text (a timer takes a function), must not add a script element to the page, must not set an event attribute such as onclick from text, and must not make network requests or load anything from another site: no fetch, XMLHttpRequest, WebSocket, EventSource, sendBeacon or importScripts, and no image or file from another site. The whole page must be under 65,536 characters, and the script with id="game" under 20,000 characters. Light background; walls dark, goals ringed, boxes and the player easy to tell apart. Tell a box on a goal from one off a goal by a mark or shape, not by colour alone. The two scripts share one global scope, so give the page's copy of the map another name than the logic's (a const MAP in both stops the second script with an error), or wrap the page's script in a function. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Box-pushing puzzle</title> <style> body {font-family:sans-serif;background:#f0f0f0;margin:1rem} h1 {text-align:center} #board {display:grid;grid-template-columns:repeat(8,2.5rem);grid-template-rows:repeat(7,2.5rem);gap:2px;margin:1rem auto;max-width:22rem} .cell {width:2.5rem;height:2.5rem;display:flex;align-items:center;justify-content:center;font-size:1.5rem;border:1px solid #ccc;background:#fff;box-sizing:border-box} .wall {background:#222;color:#fff} .goal {background:repeating-conic-gradient(#888 0 25%,transparent 25% 50%) 50%/80% 80%;border:2px solid #888} .box {color:#006} .box-on-goal {color:#c60} .player {color:#060} .player-on-goal {color:#090} .controls {display:grid;grid-template-areas:"... up ..." "left down right" "... restart ...";gap:4px;justify-content:center;margin:1rem} button {padding:.5rem 1rem;font-size:1rem;cursor:pointer} [data-dir="up"] {grid-area:up} [data-dir="down"] {grid-area:down} [data-dir="left"] {grid-area:left} [data-dir="right"] {grid-area:right} #restart {grid-area:restart} #info {display:flex;gap:2rem;justify-content:center;margin:.5rem} #status {margin-top:.5rem;text-align:center;font-weight:bold} </style> </head> <body> <h1>Box-pushing puzzle</h1> <div id="board"></div> <div class="controls"> <button data-dir="up">Up</button> <button data-dir="left">Left</button> <button data-dir="down">Down</button> <button data-dir="right">Right</button> <button id="restart">Restart</button> </div> <div id="info"> <div>Steps: <span id="steps">0</span></div> <div>Pushes: <span id="pushes">0</span></div> </div> <div id="status">Not solved yet</div> <script id="game"> const LEVEL = [ "########", "# +##", "# #*$ #", "# # #", "## $ . #", "# #", "########" ]; function createGame() { const H = LEVEL.length, W = LEVEL[0].length; const walls = new Set(), goals = new Set(); let player = [0,0], boxes = []; for (let y=0; y<H; y++) for (let x=0; x<W; x++) { const ch = LEVEL[y][x]; if (ch==='#') walls.add(x+','+y); else if (ch==='.') goals.add(x+','+y); else if (ch==='@') player = [x,y]; else if (ch==='+') {player=[x,y]; goals.add(x+','+y);} else if (ch==='$') boxes.push([x,y]); else if (ch==='*') {boxes.push([x,y]); goals.add(x+','+y);} } let steps=0, pushes=0, solved=false; const dirs = {up:[0,-1], down:[0,1], left:[-1,0], right:[1,0]}; function key(x,y){return x+','+y} function hasBox(x,y){return boxes.some(b=>b[0]===x&&b[1]===y)} function moveBox(bx,by,dx,dy){ const nx=bx+dx, ny=by+dy; if (walls.has(key(nx,ny)) || hasBox(nx,ny)) return false; boxes = boxes.map(b=>b[0]===bx&&b[1]===by?[nx,ny]:b); return true; } function checkSolved(){ return boxes.every(b=>goals.has(key(b[0],b[1]))); } return { walk(dir){ if (solved) return; const [dx,dy] = dirs[dir]; const [px,py] = player; const nx=px+dx, ny=py+dy; if (walls.has(key(nx,ny))) return; if (hasBox(nx,ny)){ if (!moveBox(nx,ny,dx,dy)) return; player = [nx,ny]; steps++; pushes++; }else{ player = [nx,ny]; steps++; } solved = checkSolved(); }, state(){ return { player: [...player], boxes: [...boxes].sort((a,b)=>a[1]-b[1]||a[0]-b[0]), pushes, steps, solved }; } }; } </script> <script> (() => { const game = createGame(); const board = document.getElementById('board'); const stepsEl = document.getElementById('steps'); const pushesEl = document.getElementById('pushes'); const statusEl = document.getElementById('status'); const cells = []; // Build board cells from static LEVEL (from game script) const H = LEVEL.length, W = LEVEL[0].length; for (let y=0; y<H; y++) for (let x=0; x<W; x++) { const cell = document.createElement('div'); cell.className = 'cell'; cell.setAttribute('role','img'); board.appendChild(cell); cells.push(cell); } function render(state){ const {player, boxes, pushes, steps, solved} = state; const boxSet = new Set(boxes.map(([x,y])=>x+','+y)); const goalSet = new Set(); for (let y=0; y<H; y++) for (let x=0; x<W; x++) { const ch = LEVEL[y][x]; if (ch==='.' || ch==='+' || ch==='*') goalSet.add(x+','+y); } for (let y=0; y<H; y++) for (let x=0; x<W; x++) { const idx = y*W+x; const cell = cells[idx]; const k = x+','+y; let cls = '', txt = '', label = ''; if (LEVEL[y][x]==='#') {cls='wall'; txt='█'; label='wall';} else if (goalSet.has(k)) { cls='goal'; if (boxSet.has(k)) {cls+=' box-on-goal'; txt='▣'; label='box on a goal';} else if (player[0]===x && player[1]===y) {cls+=' player-on-goal'; txt='☺'; label='you on a goal';} else {txt='○'; label='empty goal';} } else { if (boxSet.has(k)) {cls='box'; txt='□'; label='box';} else if (player[0]===x && player[1]===y) {cls='player'; txt='☺'; label='you';} else {label='empty floor';} } cell.className = 'cell ' + cls; cell.textContent = txt; cell.setAttribute('aria-label', label); } stepsEl.textContent = steps; pushesEl.textContent = pushes; if (solved) statusEl.textContent = `Solved in ${steps} steps with ${pushes} pushes`; else statusEl.textContent = 'Not solved yet'; } function doWalk(dir){ game.walk(dir); setTimeout(() => render(game.state()), 100); } document.addEventListener('keydown', e => { const map = {ArrowUp:'up', ArrowDown:'down', ArrowLeft:'left', ArrowRight:'right'}; if (map[e.key]) {e.preventDefault(); doWalk(map[e.key]);} }); document.querySelectorAll('[data-dir]').forEach(btn => { btn.addEventListener('click', () => doWalk(btn.dataset.dir)); }); document.getElementById('restart').addEventListener('click', () => { // recreate game Object.assign(game, createGame()); setTimeout(() => render(game.state()), 100); }); render(game.state()); })(); </script> </body> </html>MinesweeperFailed
4,658 tokens: 1,437 read, 3,221 written · 1 min 3 s · 51.1 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; } body { margin: 0; min-height: 100vh; background: #fdf6e3; font-family: system-ui, sans-serif; color: #333; display: flex; flex-direction: column; align-items: center; padding: 16px; } h1 { margin: 0 0 8px; font-size: 1.5rem; } .rules { max-width: 360px; margin: 0 0 16px; font-size: 0.9rem; line-height: 1.5; color: #555; } .panel { background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); padding: 16px; width: 100%; max-width: 360px; } .status-line { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; font-size: 0.95rem; } .status-line .mines { font-weight: 600; } .status-line .state { font-weight: 600; } .state.playing { color: #333; } .state.won { color: #2e7d32; } .state.lost { color: #c62828; } #flag-mode { background: #fff; border: 2px solid #ccc; border-radius: 6px; padding: 8px 12px; font-size: 0.85rem; cursor: pointer; transition: all 0.15s; } #flag-mode[aria-pressed="true"] { background: #fce4ec; border-color: #ec407a; color: #c2185b; } #flag-mode:focus { outline: 2px solid #1976d2; outline-offset: 2px; } #board { display: block; width: 324px; height: 324px; background: #eee; border: 1px solid #ddd; border-radius: 4px; touch-action: none; } @media (max-width: 360px) { .panel { padding: 12px; } #board { width: 100%; height: auto; aspect-ratio: 1/1; } } </style> </head> <body> <h1>Minesweeper</h1> <p class="rules">Open cells by clicking. Numbers show how many mines touch that cell. Open a cell with no adjacent mines and it spreads automatically. Right-click or use Flag mode to place flags. Win by opening all safe cells. Lose by opening a mine.</p> <div class="panel" role="region" aria-label="Game board"> <div class="status-line" role="status" aria-live="polite" id="status"> <span class="mines">Mines left: <span id="mines-left">10</span></span> <span class="state playing" id="game-state">Playing</span> </div> <button id="flag-mode" aria-pressed="false">Flag mode: off</button> <canvas id="board" width="324" height="324" aria-label="Minesweeper board" tabindex="0"></canvas> </div> <script id="game"> const MINE_LAYOUT = [ "*........", ".........", "*...*..*.", "....*....", "**.......", ".........", "...*.**..", ".........", "........." ]; function createGame() { const mines = new Set(); for (let r = 0; r < 9; r++) { for (let c = 0; c < 9; c++) { if (MINE_LAYOUT[r][c] === '*') mines.add(r * 9 + c); } } const opened = new Array(81).fill(false); const flagged = new Array(81).fill(false); let status = "playing"; function idx(r, c) { return r * 9 + c; } function inBounds(r, c) { return r >= 0 && r < 9 && c >= 0 && c < 9; } function countAdjacentMines(r, c) { let n = 0; for (let dr = -1; dr <= 1; dr++) { for (let dc = -1; dc <= 1; dc++) { if (dr === 0 && dc === 0) continue; const nr = r + dr, nc = c + dc; if (inBounds(nr, nc) && mines.has(idx(nr, nc))) n++; } } return n; } function floodOpen(r, c) { const queue = [[r, c]]; while (queue.length) { const [cr, cc] = queue.shift(); const i = idx(cr, cc); if (opened[i] || flagged[i]) continue; opened[i] = true; const adj = countAdjacentMines(cr, cc); if (adj === 0) { for (let dr = -1; dr <= 1; dr++) { for (let dc = -1; dc <= 1; dc++) { if (dr === 0 && dc === 0) continue; const nr = cr + dr, nc = cc + dc; if (inBounds(nr, nc) && !opened[idx(nr, nc)] && !flagged[idx(nr, nc)]) { queue.push([nr, nc]); } } } } } } function checkWin() { for (let i = 0; i < 81; i++) { if (!mines.has(i) && !opened[i]) return false; } return true; } function press(move) { if (status !== "playing") return; const [kind, r, c] = move; const i = idx(r, c); if (kind === "open") { if (flagged[i] || opened[i]) return; if (mines.has(i)) { status = "lost"; return; } const adj = countAdjacentMines(r, c); if (adj === 0) { floodOpen(r, c); } else { opened[i] = true; } if (checkWin()) status = "won"; } else if (kind === "flag") { if (opened[i]) return; flagged[i] = !flagged[i]; } } function state() { const cells = []; let flaggedCount = 0; for (let r = 0; r < 9; r++) { let rowStr = ""; for (let c = 0; c < 9; c++) { const i = idx(r, c); const isMine = mines.has(i); if (status === "won" && isMine) { rowStr += "F"; flaggedCount++; } else if (status === "lost" && isMine) { rowStr += "*"; if (flagged[i]) flaggedCount++; } else if (flagged[i]) { rowStr += "F"; flaggedCount++; } else if (opened[i]) { const adj = countAdjacentMines(r, c); rowStr += adj === 0 ? "." : String(adj); } else { rowStr += "#"; } } cells.push(rowStr); } const minesLeft = 10 - flaggedCount; return { cells, status, mines_left: minesLeft }; } return { press, state }; } </script> <script> const game = createGame(); const canvas = document.getElementById("board"); const ctx = canvas.getContext("2d"); const minesLeftEl = document.getElementById("mines-left"); const gameStateEl = document.getElementById("game-state"); const flagModeBtn = document.getElementById("flag-mode"); let flagMode = false; const CELL_SIZE = 36; const BOARD_SIZE = 324; function draw() { const { cells, status, mines_left } = game.state(); ctx.clearRect(0, 0, BOARD_SIZE, BOARD_SIZE); // Draw grid ctx.strokeStyle = "#ccc"; ctx.lineWidth = 1; for (let i = 0; i <= 9; i++) { const pos = i * CELL_SIZE; ctx.beginPath(); ctx.moveTo(pos, 0); ctx.lineTo(pos, BOARD_SIZE); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, pos); ctx.lineTo(BOARD_SIZE, pos); ctx.stroke(); } // Draw cell contents ctx.font = "bold 20px system-ui, sans-serif"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; for (let r = 0; r < 9; r++) { const row = cells[r]; for (let c = 0; c < 9; c++) { const ch = row[c]; const x = c * CELL_SIZE + CELL_SIZE / 2; const y = r * CELL_SIZE + CELL_SIZE / 2; if (ch === "#" || ch === ".") continue; if (ch >= "1" && ch <= "8") { const colors = ["", "#1976d2", "#388e3c", "#d32f2f", "#7b1fa2", "#f57c00", "#0097a7", "#5d4037", "#616161"]; ctx.fillStyle = colors[parseInt(ch)]; ctx.fillText(ch, x, y + 1); } else if (ch === "F") { ctx.fillStyle = "#ec407a"; ctx.fillText("🚩", x, y + 1); } else if (ch === "*") { ctx.fillStyle = "#c62828"; ctx.fillText("💣", x, y + 1); } } } // Update status minesLeftEl.textContent = mines_left; gameStateEl.textContent = status.charAt(0).toUpperCase() + status.slice(1); gameStateEl.className = "state " + status; } function getCellFromEvent(e) { const rect = canvas.getBoundingClientRect(); const scaleX = canvas.width / rect.width; const scaleY = canvas.height / rect.height; const clientX = e.touches ? e.touches[0].clientX : e.clientX; const clientY = e.touches ? e.touches[0].clientY : e.clientY; const x = (clientX - rect.left) * scaleX; const y = (clientY - rect.top) * scaleY; const col = Math.floor(x / CELL_SIZE); const row = Math.floor(y / CELL_SIZE); if (row >= 0 && row < 9 && col >= 0 && col < 9) { return [row, col]; } return null; } function handlePress(row, col, kind) { game.press([kind, row, col]); draw(); } canvas.addEventListener("click", (e) => { const cell = getCellFromEvent(e); if (!cell) return; const [row, col] = cell; handlePress(row, col, flagMode ? "flag" : "open"); }); canvas.addEventListener("contextmenu", (e) => { e.preventDefault(); const cell = getCellFromEvent(e); if (!cell) return; const [row, col] = cell; handlePress(row, col, "flag"); }); flagModeBtn.addEventListener("click", () => { flagMode = !flagMode; flagModeBtn.textContent = "Flag mode: " + (flagMode ? "on" : "off"); flagModeBtn.setAttribute("aria-pressed", flagMode); }); canvas.addEventListener("keydown", (e) => { // Simple keyboard support: arrow keys to navigate would be complex // Just handle F for flag on focused cell? But canvas is single focusable. // For simplicity, we'll skip full keyboard nav as it's "welcome but not checked" if (e.key === "f" || e.key === "F") { // Could implement but not required } }); draw(); </script> </body> </html>
Building apps 2 of 4
Step sequencerFailed
4,849 tokens: 1,322 read, 3,527 written · 1 min 19 s · 44.5 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 1001000010001010 snare 0000100100101000 hat 1011101010111010 The rules, exactly: 1. At the start, playing is false, playhead is 0 and hits is []. 2. press([track, step]) toggles one cell: track 0 is kick, 1 snare, 2 hat; step is 0 to 15, where 0 is the first step. Toggling changes the pattern and nothing else. 3. press('play') does nothing when playing is already true. Otherwise it sets playing to true, and hits becomes the list of track numbers (0 kick, 1 snare, 2 hat) whose cell at the playhead is 1, in ascending order ([] when there are none). So the step under the playhead sounds as play starts. 4. press('stop') sets playing to false, playhead to 0 and hits to []. 5. press('tick') does nothing unless playing is true. When it is, playhead goes on by one, and after 15 it goes back to 0. hits becomes the list of track numbers whose cell at the new playhead is 1, in ascending order ([] when there are none). 6. Any other cmd does nothing: a list that is not exactly two whole numbers (such as [0, 1, 2], [1], [] or [true, 0]), null, a number, true or false, a word other than play, stop or tick, and a track or step outside the ranges above. Track and step are whole numbers. state() returns {playing, playhead, hits, pattern}: playing is true or false; playhead is 0 to 15; hits lists the track numbers set by the last tick or by the play that started playback, in ascending order ([] at the start and after stop); pattern is three strings of 16 characters, kick first, each character 1 or 0. The page: - Each step button is a real button with the attributes data-track (0, 1 or 2) and data-step (0 to 15), and aria-pressed set to true or false to match its state. A click calls press([track, step]), and after every press, the page draws from state(). - A step that is on has the class on, and the stylesheet fills it dark; a step that is off has no class on. - Play has the id play and Stop the id stop. Play calls press('play') and starts one timer that calls press('tick') every 125 ms: 120 quarter-note beats a minute, four steps to a beat. Stop calls press('stop') and clears the timer. Each play and each tick sounds the hits that state() then reports, and nothing else sounds. - Play has the disabled attribute while playing, and Stop has it while stopped. - A status line with the id status reads "Stopped", or "Playing, step N of 16" with N the playhead plus 1. Give it a fixed height, so the grid does not move when its text changes. - A span with the id announce, set to aria-live polite, is empty until playback starts for the first time. From then on it says "Playing" when playback starts and "Stopped" when it stops, and changes at no other time. - The cells in the playhead column have the class playhead while playing, and no cell has it while stopped. - The numbers 1 to 16, as text, sit above the grid, and the playhead's number is pink. Under 720 px each step shows its number. - When the page becomes hidden, it presses Stop, so nothing sounds in a background tab. - Each track in hits plays its drum: kick is a falling sine tone, snare a short noise burst with a low body tone, hat a short high noise burst. Tones use oscillators; noise bursts use buffer sources playing a buffer of random samples: the kick is one oscillator, the snare one buffer source and one oscillator, the hat one buffer source. Hits that land together must not clip, so put a gain or a limiter before the output. Create the AudioContext inside the first click (browsers need a click before they make sound), and resume it if it is suspended. - Flat and plain: a light background, dark ink, no shadows or gradients, Play the one pink button (#b31f57), and the playhead cell outlined in pink where you are. At 1280 px the 16 steps sit in one row; under 720 px they form two bars of 8. The page never scrolls sideways. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and drives the sequencer through createGame(). Wire the page in another <script>.Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Step sequencer</title> <style> :root { --pink:#b31f57; --ink:#111; --bg:#fafafa; --cell:60px; --gap:4px; } *{box-sizing:border-box;margin:0;padding:0} body{font-family:system-ui,sans-serif;background:var(--bg);color:var(--ink);min-height:100vh;display:flex;flex-direction:column;align-items:center;padding:24px 12px} h1{font-size:1.5rem;margin-bottom:16px;font-weight:600} .seq{display:flex;flex-direction:column;align-items:center;gap:12px;width:100%;max-width:1200px} .track{display:flex;align-items:center;gap:var(--gap);flex-wrap:wrap;justify-content:center} .track-label{width:4.5ch;text-align:right;font-size:.85rem;font-variant-numeric:tabular-nums;color:#555;user-select:none} .step{width:var(--cell);height:var(--cell);border:2px solid #ccc;background:#fff;border-radius:4px;cursor:pointer;transition:background .1s,border-color .1s;display:flex;align-items:center;justify-content:center;font-size:.75rem;color:#666;position:relative} .step:focus-visible{outline:2px solid var(--pink);outline-offset:2px} .step.on{background:var(--ink);border-color:var(--ink);color:#fff} .step.playhead{box-shadow:0 0 0 3px var(--pink);z-index:1} .step.playhead::after{content:"";position:absolute;inset:-5px;border:2px solid var(--pink);border-radius:6px;pointer-events:none} .controls{display:flex;gap:12px;margin-top:8px} button{padding:10px 28px;font-size:1rem;border:none;border-radius:4px;cursor:pointer;transition:opacity .15s} button:disabled{opacity:.45;cursor:not-allowed} #play{background:var(--pink);color:#fff} #stop{background:#eee;color:var(--ink);border:1px solid #ccc} #status{height:1.5em;font-size:.9rem;color:#555;text-align:center;width:100%;max-width:1200px} #announce{position:absolute;left:-9999px} .step-numbers{display:flex;gap:var(--gap);justify-content:center;flex-wrap:wrap;width:100%;max-width:calc(16*var(--cell)+15*var(--gap));padding-left:calc(4.5ch+var(--gap));margin-bottom:4px} .step-num{width:var(--cell);height:24px;display:flex;align-items:center;justify-content:center;font-size:.75rem;color:#888;font-variant-numeric:tabular-nums} .step-num.playhead{color:var(--pink);font-weight:700} @media (max-width:1280px){ :root{--cell:52px} } @media (max-width:720px){ :root{--cell:44px} .track{flex-wrap:wrap} .step-numbers{display:none} .step::before{content:attr(data-step-num);position:absolute;top:-16px;left:50%;transform:translateX(-50%);font-size:.65rem;color:#888;white-space:nowrap} .step.playhead::before{color:var(--pink);font-weight:700} } @media (max-width:480px){ :root{--cell:38px} button{padding:10px 16px;font-size:.9rem} .track-label{width:4ch;font-size:.75rem} } </style> </head> <body> <h1>Step sequencer</h1> <div class="seq"> <div class="step-numbers" id="stepNumbers"></div> <div class="track" id="track0"><span class="track-label">Kick</span></div> <div class="track" id="track1"><span class="track-label">Snare</span></div> <div class="track" id="track2"><span class="track-label">Hat</span></div> <div class="controls"> <button id="play" disabled>Play</button> <button id="stop" disabled>Stop</button> </div> <div id="status">Stopped</div> <span id="announce" aria-live="polite"></span> </div> <script id="game"> function createGame(){ const pattern = [ "1001000010001010".split("").map(Number), "0000100100101000".split("").map(Number), "1011101010111010".split("").map(Number) ]; let playing = false; let playhead = 0; let hits = []; function press(cmd){ if(Array.isArray(cmd) && cmd.length===2 && Number.isInteger(cmd[0]) && Number.isInteger(cmd[1])){ const [track, step] = cmd; if(track>=0 && track<=2 && step>=0 && step<=15){ pattern[track][step] ^= 1; } return; } if(cmd==="play"){ if(playing) return; playing = true; hits = []; for(let t=0;t<3;t++) if(pattern[t][playhead]) hits.push(t); return; } if(cmd==="stop"){ playing = false; playhead = 0; hits = []; return; } if(cmd==="tick"){ if(!playing) return; playhead = (playhead+1)%16; hits = []; for(let t=0;t<3;t++) if(pattern[t][playhead]) hits.push(t); return; } } function state(){ return { playing, playhead, hits: [...hits], pattern: pattern.map(row=>row.join("")) }; } return {press, state}; } </script> <script> const game = createGame(); let audioCtx = null; let tickTimer = null; let hasStarted = false; const trackEls = [document.getElementById("track0"), document.getElementById("track1"), document.getElementById("track2")]; const playBtn = document.getElementById("play"); const stopBtn = document.getElementById("stop"); const statusEl = document.getElementById("status"); const announceEl = document.getElementById("announce"); const stepNumbersEl = document.getElementById("stepNumbers"); function initAudio(){ if(audioCtx) return; audioCtx = new (window.AudioContext||window.webkitAudioContext)(); const masterGain = audioCtx.createGain(); masterGain.gain.value = 0.5; masterGain.connect(audioCtx.destination); audioCtx.masterGain = masterGain; } function resumeAudio(){ if(audioCtx && audioCtx.state==="suspended") audioCtx.resume(); } function playKick(time){ const osc = audioCtx.createOscillator(); const gain = audioCtx.createGain(); osc.type = "sine"; osc.frequency.setValueAtTime(150, time); osc.frequency.exponentialRampToValueAtTime(40, time+0.5); gain.gain.setValueAtTime(1, time); gain.gain.exponentialRampToValueAtTime(0.001, time+0.5); osc.connect(gain).connect(audioCtx.masterGain); osc.start(time); osc.stop(time+0.55); } function playSnare(time){ const bufferSize = audioCtx.sampleRate * 0.2; const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate); const data = buffer.getChannelData(0); for(let i=0;i<bufferSize;i++) data[i] = (Math.random()*2-1) * Math.exp(-i/bufferSize*8); const noise = audioCtx.createBufferSource(); noise.buffer = buffer; const noiseGain = audioCtx.createGain(); noiseGain.gain.setValueAtTime(0.6, time); noiseGain.gain.exponentialRampToValueAtTime(0.001, time+0.2); noise.connect(noiseGain).connect(audioCtx.masterGain); noise.start(time); noise.stop(time+0.22); const osc = audioCtx.createOscillator(); const oscGain = audioCtx.createGain(); osc.type = "sine"; osc.frequency.setValueAtTime(180, time); osc.frequency.exponentialRampToValueAtTime(80, time+0.15); oscGain.gain.setValueAtTime(0.4, time); oscGain.gain.exponentialRampToValueAtTime(0.001, time+0.15); osc.connect(oscGain).connect(audioCtx.masterGain); osc.start(time); osc.stop(time+0.17); } function playHat(time){ const bufferSize = audioCtx.sampleRate * 0.06; const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate); const data = buffer.getChannelData(0); for(let i=0;i<bufferSize;i++) data[i] = (Math.random()*2-1) * Math.exp(-i/bufferSize*20); const noise = audioCtx.createBufferSource(); noise.buffer = buffer; const gain = audioCtx.createGain(); gain.gain.setValueAtTime(0.35, time); gain.gain.exponentialRampToValueAtTime(0.001, time+0.06); noise.connect(gain).connect(audioCtx.masterGain); noise.start(time); noise.stop(time+0.07); } function playHits(hits, time){ if(hits.includes(0)) playKick(time); if(hits.includes(1)) playSnare(time); if(hits.includes(2)) playHat(time); } function render(){ const s = game.state(); for(let t=0;t<3;t++){ const steps = trackEls[t].querySelectorAll(".step"); steps.forEach((btn, i)=>{ const on = s.pattern[t][i]==="1"; btn.classList.toggle("on", on); btn.setAttribute("aria-pressed", on); btn.classList.toggle("playhead", s.playing && i===s.playhead); }); } playBtn.disabled = s.playing; stopBtn.disabled = !s.playing; statusEl.textContent = s.playing ? `Playing, step ${s.playhead+1} of 16` : "Stopped"; const nums = stepNumbersEl.querySelectorAll(".step-num"); nums.forEach((el, i)=> el.classList.toggle("playhead", s.playing && i===s.playhead)); } function buildUI(){ for(let t=0;t<3;t++){ const track = trackEls[t]; for(let i=0;i<16;i++){ const btn = document.createElement("button"); btn.type="button"; btn.className="step"; btn.dataset.track = t; btn.dataset.step = i; btn.dataset.stepNum = i+1; btn.setAttribute("aria-pressed","false"); btn.textContent = ""; btn.addEventListener("click",()=>{ initAudio(); resumeAudio(); game.press([t,i]); render(); }); track.appendChild(btn); } } for(let i=1;i<=16;i++){ const span = document.createElement("span"); span.className="step-num"; span.textContent = i; stepNumbersEl.appendChild(span); } playBtn.addEventListener("click",()=>{ initAudio(); resumeAudio(); if(!hasStarted){ hasStarted=true; announceEl.textContent="Playing"; } game.press("play"); const st = game.state(); playHits(st.hits, audioCtx.currentTime); render(); if(tickTimer) clearInterval(tickTimer); tickTimer = setInterval(()=>{ game.press("tick"); const s = game.state(); playHits(s.hits, audioCtx.currentTime); render(); },125); }); stopBtn.addEventListener("click",()=>{ if(tickTimer){ clearInterval(tickTimer); tickTimer=null; } game.press("stop"); render(); if(hasStarted) announceEl.textContent="Stopped"; }); document.addEventListener("visibilitychange",()=>{ if(document.hidden){ if(tickTimer){ clearInterval(tickTimer); tickTimer=null; } game.press("stop"); render(); if(hasStarted) announceEl.textContent="Stopped"; } }); render(); } buildUI(); </script> </body> </html>Grow a branching plantFailed
1,273 tokens: 1,253 read, 20 written · 5 s · 3.9 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.Falling sandPassed
11,667 tokens: 1,167 read, 10,500 written · 2 min 53 s · 60.7 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 20, columns 16 to 22; row 21, columns 2 to 9; row 20, columns 25 to 30. 3. Sand: column 16, row 2; row 3, columns 12 to 20; row 4, columns 10 to 22; row 5, columns 10 to 22; row 6, columns 9 to 23; row 7, columns 10 to 22; row 8, columns 10 to 22; row 9, columns 12 to 20; column 16, row 10. 4. Every other cell is empty. The rules, exactly: 1. A pour [x, y] puts one grain in that cell if it is empty; a cell holding sand or wall, or outside the grid, is not empty, so the pour does nothing. 2. A step runs one frame, using frame as it is before the step, then frame goes up by 1. A frame scans the rows from row 28 up to row 0. Within a row it scans the columns from left to right when frame is even, and from right to left when frame is odd. 3. Each sand cell the scan reaches moves at most once: to (x, y+1) if that cell is empty; otherwise to (x-1, y+1) if that is empty; otherwise to (x+1, y+1) if that is empty; otherwise it stays. Anything outside the grid counts as wall. 4. Each check reads the cells as they are at that moment: a grain that has moved leaves its cell empty, and a cell an earlier grain filled in this frame is not empty. The site plays a list of moves through play() and checks state() after each one. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>. Do not run a string as code: no eval, no Function (not even as a function's constructor property), no timer given a string, no javascript: address, and no script element made from text. Network requests are refused, and the game script is at most 20,000 characters. The page: a canvas with the id board and the width and height attributes 640 and 480. The board may be shown at any size and place on the page: a press or drag finds its cell from where the board is on screen not from its 640 by 480 pixels. A press on the board pours one grain into the cell under the pointer. A drag pours into every cell on the straight line from the cell the pointer left to the cell it reached, both ends included (Bresenham's line algorithm). Buttons with the ids play, step and reset. play runs one frame about every 50 ms, and its label reads Pause while it runs; pressing it again pauses, and the label reads Play. step runs one frame. reset calls createGame() again, back to the start, and stops Play if it is running. After each pour, after each frame that Play or Step runs, and after Reset, the board is cleared or filled once, then each grain of sand is drawn with fillRect in its own cell; empty cells are not drawn one by one. One line under the board, with the id status, reads "Frame N, M grains of sand" ("1 grain of sand" for one), N is the frame and M the grains. Not checked, but wanted: keyboard pouring (arrow keys move a pour cursor when the board has focus; Space or Enter pours at it); a live region with the id say that announces Play, Pause, Step and Reset; reduced motion (prefers-reduced-motion: reduce): a press of Play runs one frame; off screen, Play pauses for real (no frame runs, the label reads Play) and resumes on return only if it was playing, and a press of Play then does nothing, while Step still runs one frame.Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Falling Sand</title> <style> body { font-family: sans-serif; margin: 1rem; } #board { border: 1px solid #333; background: #111; display: block; touch-action: none; } button { margin: 0.25rem; padding: 0.5rem 1rem; font-size: 1rem; cursor: pointer; } #status { margin-top: 0.5rem; font-family: monospace; } #say { position: absolute; left: -9999px; } canvas:focus { outline: 2px solid #0af; outline-offset: -2px; } </style> </head> <body> <canvas id="board" width="640" height="480" tabindex="0"></canvas> <div> <button id="play">Play</button> <button id="step">Step</button> <button id="reset">Reset</button> </div> <div id="status">Frame 0, 0 grains of sand</div> <div id="say" aria-live="polite"></div> <script id="game"> function createGame() { const COLS = 40, ROWS = 30; let frame = 0; let grid = Array.from({length: ROWS}, () => Array(COLS).fill(0)); // Row 29 all wall for (let x = 0; x < COLS; x++) grid[29][x] = 2; // Walls for (let x = 16; x <= 22; x++) grid[20][x] = 2; for (let x = 2; x <= 9; x++) grid[21][x] = 2; for (let x = 25; x <= 30; x++) grid[20][x] = 2; // Sand grid[2][16] = 1; for (let x = 12; x <= 20; x++) grid[3][x] = 1; for (let x = 10; x <= 22; x++) grid[4][x] = 1; for (let x = 10; x <= 22; x++) grid[5][x] = 1; for (let x = 9; x <= 23; x++) grid[6][x] = 1; for (let x = 10; x <= 22; x++) grid[7][x] = 1; for (let x = 10; x <= 22; x++) grid[8][x] = 1; for (let x = 12; x <= 20; x++) grid[9][x] = 1; grid[10][16] = 1; function pour(x, y) { if (x >= 0 && x < COLS && y >= 0 && y < ROWS && grid[y][x] === 0) { grid[y][x] = 1; } } function step() { const currentFrame = frame; const leftToRight = currentFrame % 2 === 0; for (let y = 28; y >= 0; y--) { const cols = leftToRight ? Array.from({length: COLS}, (_, i) => i) : Array.from({length: COLS}, (_, i) => COLS - 1 - i); for (let x of cols) { if (grid[y][x] === 1) { if (y + 1 < ROWS && grid[y + 1][x] === 0) { grid[y][x] = 0; grid[y + 1][x] = 1; } else if (x - 1 >= 0 && y + 1 < ROWS && grid[y + 1][x - 1] === 0) { grid[y][x] = 0; grid[y + 1][x - 1] = 1; } else if (x + 1 < COLS && y + 1 < ROWS && grid[y + 1][x + 1] === 0) { grid[y][x] = 0; grid[y + 1][x + 1] = 1; } } } } frame++; } return { play(move) { if (move === "step") step(); else if (Array.isArray(move) && move.length === 2) pour(move[0], move[1]); }, state() { return {frame, cells: grid.map(row => [...row])}; } }; } </script> <script> const COLS = 40, ROWS = 30, CELL = 16; const canvas = document.getElementById('board'); const ctx = canvas.getContext('2d'); const playBtn = document.getElementById('play'); const stepBtn = document.getElementById('step'); const resetBtn = document.getElementById('reset'); const statusEl = document.getElementById('status'); const sayEl = document.getElementById('say'); let game = createGame(); let playing = false; let intervalId = null; let cursorX = 20, cursorY = 15; let isMouseDown = false; let lastCell = null; const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; let wasPlayingBeforeHidden = false; function announce(msg) { sayEl.textContent = msg; } function getCellFromClient(clientX, clientY) { const rect = canvas.getBoundingClientRect(); const x = Math.floor((clientX - rect.left) / rect.width * COLS); const y = Math.floor((clientY - rect.top) / rect.height * ROWS); return [Math.max(0, Math.min(COLS - 1, x)), Math.max(0, Math.min(ROWS - 1, y))]; } function bresenham(x0, y0, x1, y1) { const pts = []; const dx = Math.abs(x1 - x0), dy = Math.abs(y1 - y0); const sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1; let err = dx - dy; while (true) { pts.push([x0, y0]); if (x0 === x1 && y0 === y1) break; const e2 = 2 * err; if (e2 > -dy) { err -= dy; x0 += sx; } if (e2 < dx) { err += dx; y0 += sy; } } return pts; } function pourAt(x, y) { game.play([x, y]); updateUI(); } function updateUI() { const state = game.state(); draw(state.cells); const sand = state.cells.flat().filter(v => v === 1).length; statusEl.textContent = `Frame ${state.frame}, ${sand} grain${sand === 1 ? '' : 's'} of sand`; } function draw(grid) { ctx.clearRect(0, 0, canvas.width, canvas.height); // walls ctx.fillStyle = '#888'; for (let y = 0; y < ROWS; y++) { for (let x = 0; x < COLS; x++) { if (grid[y][x] === 2) ctx.fillRect(x * CELL, y * CELL, CELL, CELL); } } // sand ctx.fillStyle = '#E8C87A'; for (let y = 0; y < ROWS; y++) { for (let x = 0; x < COLS; x++) { if (grid[y][x] === 1) ctx.fillRect(x * CELL, y * CELL, CELL, CELL); } } // cursor highlight if (document.activeElement === canvas) { ctx.fillStyle = 'rgba(255,255,255,0.3)'; ctx.fillRect(cursorX * CELL, cursorY * CELL, CELL, CELL); ctx.strokeStyle = '#fff'; ctx.strokeRect(cursorX * CELL, cursorY * CELL, CELL, CELL); } } // Pointer events canvas.addEventListener('mousedown', e => { isMouseDown = true; const cell = getCellFromClient(e.clientX, e.clientY); pourAt(...cell); lastCell = cell; }); window.addEventListener('mousemove', e => { if (!isMouseDown) return; const cell = getCellFromClient(e.clientX, e.clientY); if (lastCell) { const line = bresenham(lastCell[0], lastCell[1], cell[0], cell[1]); for (const [x, y] of line) pourAt(x, y); } lastCell = cell; }); window.addEventListener('mouseup', () => { isMouseDown = false; lastCell = null; }); // Touch events canvas.addEventListener('touchstart', e => { e.preventDefault(); const touch = e.touches[0]; isMouseDown = true; const cell = getCellFromClient(touch.clientX, touch.clientY); pourAt(...cell); lastCell = cell; }, {passive: false}); canvas.addEventListener('touchmove', e => { e.preventDefault(); if (!isMouseDown) return; const touch = e.touches[0]; const cell = getCellFromClient(touch.clientX, touch.clientY); if (lastCell) { const line = bresenham(lastCell[0], lastCell[1], cell[0], cell[1]); for (const [x, y] of line) pourAt(x, y); } lastCell = cell; }, {passive: false}); canvas.addEventListener('touchend', () => { isMouseDown = false; lastCell = null; }); // Keyboard canvas.addEventListener('keydown', e => { switch (e.key) { case 'ArrowUp': cursorY = Math.max(0, cursorY - 1); break; case 'ArrowDown': cursorY = Math.min(ROWS - 1, cursorY + 1); break; case 'ArrowLeft': cursorX = Math.max(0, cursorX - 1); break; case 'ArrowRight': cursorX = Math.min(COLS - 1, cursorX + 1); break; case ' ': case 'Enter': pourAt(cursorX, cursorY); break; default: return; } e.preventDefault(); updateUI(); }); // Buttons playBtn.addEventListener('click', () => { if (reducedMotion) { game.play("step"); updateUI(); announce("Play"); return; } if (playing) { clearInterval(intervalId); playing = false; playBtn.textContent = "Play"; announce("Pause"); } else { if (document.hidden) return; playing = true; playBtn.textContent = "Pause"; announce("Play"); intervalId = setInterval(() => { game.play("step"); updateUI(); }, 50); } }); stepBtn.addEventListener('click', () => { game.play("step"); updateUI(); announce("Step"); }); resetBtn.addEventListener('click', () => { if (playing) { clearInterval(intervalId); playing = false; playBtn.textContent = "Play"; } game = createGame(); cursorX = 20; cursorY = 15; updateUI(); announce("Reset"); }); // Visibility document.addEventListener('visibilitychange', () => { if (document.hidden) { if (playing) { wasPlayingBeforeHidden = true; clearInterval(intervalId); playing = false; playBtn.textContent = "Play"; } } else { if (wasPlayingBeforeHidden && !reducedMotion) { playing = true; playBtn.textContent = "Pause"; intervalId = setInterval(() => { game.play("step"); updateUI(); }, 50); } wasPlayingBeforeHidden = false; } }); // Initial draw updateUI(); </script> </body> </html>Focus timerPassed
12,132 tokens: 1,110 read, 11,022 written · 3 min 57 s · 46.5 tok/s
Build a focus timer as one web page. Work periods alternate with breaks, and after every few finished work periods the break is long. The page shows the name of the period, the time left, an SVG ring that empties as the time runs down, and how many work periods are done. In <script id="game">, define createGame(). It returns an object with two methods, tick(cmd) and state(). The page's own timer calls tick() once a second, and its buttons call tick('start'), tick('pause'), tick('skip') and tick('reset'). Those four exact lowercase words are commands: they change the timer and pass no time. Any other value passes one second, and only while the timer is running: no argument, null, undefined, a number, true, false, an empty text, any other text such as 'Start' or 'tick', or an object. state() returns {phase, left, running, done}: phase is 'work', 'short' or 'long'; left is the whole number of seconds left in this period; running is true or false; done is a number. The script in <script id="game"> is at most 20,000 characters. This run's lengths: work 1500 seconds (25 minutes), short break 300 seconds (5 minutes), long break 600 seconds (10 minutes). A long break follows every 3rd finished work period. The rules, exactly: 1. The timer starts in work, with left 1500, running false and done 0. 2. 'start' sets running to true, and 'pause' sets it to false. Neither changes anything else. 3. While running, each passed second lowers left by 1. While paused, passed seconds change nothing. 4. When left reaches 0, the period is over at once, so state() never shows 0. The next period starts with its full length and paused (running false). Seconds passed after that change nothing until 'start'. 5. A work period that ends this way adds 1 to done. Then a long break comes when done is a multiple of 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 25:00. - An SVG ring around the time: a circle with pathLength="100" and stroke-dasharray="100". Set its stroke-dashoffset attribute to 100 times (1 minus left divided by the full length of the current period) on every redraw. The arc is full, with an offset of 0, at the start of a period, and it is empty, with an offset of 100, when the time is up. A track circle without a stroke-dashoffset may sit under it. - Four buttons in one row, with the ids start, pause, skip and reset, labelled Start, Pause, Skip and Reset. Each calls tick() with its command. Start is disabled while the timer runs, and Pause is disabled while it is paused. Skip and Reset are always enabled. Below 390 px they may wrap into two rows of two. - The count in an element with the id count, in words: "Focus periods done: 3". - The page's own timer calls tick() once a second, with no argument. After every call, the page redraws from state(). When a period ends, the page may play a short chime with the Web Audio API. - Look: a light, warm off-white page with one white card, dark ink text and muted grey for the small labels. One accent colour, used for the Start button only. Flat fills, no gradients or shadows, no outside fonts or images: use the system font. It must look tidy at 390 px and at 1280 px wide, with no sideways scrolling. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the timer's logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and drives the timer through createGame(). Do not use eval, Function or any other way of running text as code: no string given to a timer, and no script element or event-handler attribute made from text while the page runs. Put the wiring in another <script>.Open the page on its own. It runs in a sandbox: no network, no access to this site.
Page source
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Focus timer</title> <style> :root { --bg: #faf9f6; --card: #ffffff; --ink: #2d2d2d; --muted: #999999; --accent: #d47a00; --track: #dddddd; } * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: var(--bg); color: var(--ink); min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 1rem; } .card { background: var(--card); border-radius: 8px; padding: 2rem; width: 100%; max-width: 400px; text-align: center; } h1 { font-size: 1.5rem; font-weight: 600; margin-bottom: 1rem; } #phase { font-size: 1.2rem; color: var(--muted); margin-bottom: 0.5rem; } .timer-ring { position: relative; width: 200px; height: 200px; margin: 0 auto 1rem; } .ring-svg { width: 100%; height: 100%; display: block; } #time { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 3rem; font-weight: 700; line-height: 1; pointer-events: none; } #count { font-size: 0.9rem; color: var(--muted); margin-bottom: 1.5rem; } .button-row { display: flex; flex-wrap: wrap; gap: 0.5rem; justify-content: center; } .button-row button { flex: 1 1 45%; min-width: 120px; max-width: 200px; padding: 0.75rem 1rem; border: 1px solid var(--track); border-radius: 4px; font-size: 1rem; font-family: inherit; cursor: pointer; background: var(--card); color: var(--ink); transition: background 0.1s, color 0.1s; } .button-row button:hover:not(:disabled) { background: #f0f0f0; } .button-row button:disabled { opacity: 0.5; cursor: not-allowed; } .button-row button#start { background: var(--accent); border-color: var(--accent); color: white; } .button-row button#start:hover:not(:disabled) { background: #b86a00; border-color: #b86a00; } @media (min-width: 390px) { .button-row button { flex: 1 1 auto; max-width: none; } } </style> </head> <body> <div class="card"> <h1>Focus timer</h1> <div id="phase">Focus</div> <div class="timer-ring"> <svg class="ring-svg" viewBox="0 0 100 100"> <circle class="track" cx="50" cy="50" r="45" fill="none" stroke="#ddd" stroke-width="8"></circle> <circle class="progress" id="progress-ring" cx="50" cy="50" r="45" fill="none" stroke="#d47a00" stroke-width="8" stroke-dasharray="100" stroke-dashoffset="0" pathLength="100" transform="rotate(-90 50 50)"></circle> </svg> <div id="time">25:00</div> </div> <div id="count">Focus periods done: 0</div> <div class="button-row"> <button id="start">Start</button> <button id="pause">Pause</button> <button id="skip">Skip</button> <button id="reset">Reset</button> </div> </div> <script id="game"> function createGame() { const WORK = 1500; const SHORT = 300; const LONG = 600; const LONG_EVERY = 3; let phase = 'work'; let left = WORK; let running = false; let done = 0; function fullLength(p) { if (p === 'work') return WORK; if (p === 'short') return SHORT; return LONG; } function nextPhaseAfterWork() { return (done % LONG_EVERY === 0) ? 'long' : 'short'; } function handlePeriodEnd() { if (phase === 'work') { done += 1; phase = nextPhaseAfterWork(); } else { phase = 'work'; } left = fullLength(phase); running = false; } function handleSkip() { if (phase === 'work') { phase = 'short'; } else { phase = 'work'; } left = fullLength(phase); running = false; } 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') { handleSkip(); return; } if (running) { left -= 1; if (left <= 0) { handlePeriodEnd(); } } } function state() { return { phase, left, running, done }; } return { tick, state }; } </script> <script> const game = createGame(); let prevState = game.state(); function formatTime(sec) { const m = Math.floor(sec / 60).toString().padStart(2, '0'); const s = (sec % 60).toString().padStart(2, '0'); return `${m}:${s}`; } function phaseName(phase) { if (phase === 'work') return 'Focus'; if (phase === 'short') return 'Short break'; return 'Long break'; } function fullLengthForPhase(phase) { if (phase === 'work') return 1500; if (phase === 'short') return 300; return 600; } function render() { const state = game.state(); document.getElementById('phase').textContent = phaseName(state.phase); document.getElementById('time').textContent = formatTime(state.left); document.getElementById('count').textContent = `Focus periods done: ${state.done}`; document.getElementById('start').disabled = state.running; document.getElementById('pause').disabled = !state.running; const full = fullLengthForPhase(state.phase); const progress = state.left / full; const offset = 100 * (1 - progress); document.getElementById('progress-ring').setAttribute('stroke-dashoffset', offset); if (state.phase !== prevState.phase) { playChime(); } prevState = state; } let audioCtx = null; function playChime() { if (!audioCtx) { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); } const now = audioCtx.currentTime; const osc = audioCtx.createOscillator(); const gain = audioCtx.createGain(); osc.type = 'sine'; osc.frequency.value = 880; gain.gain.setValueAtTime(0.1, now); gain.gain.exponentialRampToValueAtTime(0.001, now + 0.5); osc.connect(gain).connect(audioCtx.destination); osc.start(now); osc.stop(now + 0.5); } document.getElementById('start').addEventListener('click', () => { game.tick('start'); render(); }); document.getElementById('pause').addEventListener('click', () => { game.tick('pause'); render(); }); document.getElementById('skip').addEventListener('click', () => { game.tick('skip'); render(); }); document.getElementById('reset').addEventListener('click', () => { game.tick('reset'); render(); }); setInterval(() => { game.tick(); render(); }, 1000); render(); </script> </body> </html>
Writing code 3 of 3
Merge intervalsPassed
684 tokens: 168 read, 516 written · 8 s · 67.3 tok/s
Write a JavaScript function mergeIntervals(intervals). intervals is an array of [start, end] pairs of integers with start <= end, in any order, possibly empty. Return a new array of the merged intervals sorted by start: intervals that overlap or touch (one ends where the next starts) become one. Do not change the input array or its pairs. mergeIntervals([[8, 10], [1, 3], [2, 6], [6, 7]]) returns [[1, 7], [8, 10]]. Reply with one ```js code block holding plain JavaScript (no imports, no exports, no DOM, no timers). The site runs it with hidden tests.
```js function mergeIntervals(intervals) { if (!intervals || intervals.length === 0) return []; // Create a sorted copy without mutating the original const sorted = [...intervals].sort((a, b) => a[0] - b[0]); const result = []; let [curStart, curEnd] = sorted[0]; for (let i = 1; i < sorted.length; i++) { const [start, end] = sorted[i]; if (start <= curEnd) { // Overlaps or touches: merge if (end > curEnd) curEnd = end; } else { // No overlap: push current and start new result.push([curStart, curEnd]); curStart = start; curEnd = end; } } // Push the last interval result.push([curStart, curEnd]); return result; } ```An LRU cachePassed
835 tokens: 173 read, 662 written · 18 s · 35.9 tok/s
Write a JavaScript class LRUCache: a least-recently-used cache of integer keys and values. - new LRUCache(capacity): capacity is an integer of at least 1. - get(key) returns the value stored for key, or -1 if there is none. A get that finds the key makes it the most recently used. - put(key, value) stores the value (replacing any value already there) and makes key the most recently used. If that leaves more than capacity keys, the least recently used key is removed. get and put should take constant time on average. Reply with one ```js code block holding plain JavaScript (no imports, no exports, no DOM, no timers). The site runs it with hidden tests.
```js class LRUCache { constructor(capacity) { this.capacity = capacity; this.cache = new Map(); // Dummy head and tail to simplify edge cases this.head = { key: 0, value: 0, prev: null, next: null }; this.tail = { key: 0, value: 0, prev: null, next: null }; this.head.next = this.tail; this.tail.prev = this.head; } // Add node right after head (most recently used position) _addNode(node) { node.prev = this.head; node.next = this.head.next; this.head.next.prev = node; this.head.next = node; } // Remove an existing node from the linked list _removeNode(node) { const prev = node.prev; const next = node.next; prev.next = next; next.prev = prev; } // Move node to head (mark as recently used) _moveToHead(node) { this._removeNode(node); this._addNode(node); } // Pop the tail's previous node (least recently used) _popTail() { const res = this.tail.prev; this._removeNode(res); return res; } get(key) { const node = this.cache.get(key); if (!node) return -1; // Move the accessed node to the head this._moveToHead(node); return node.value; } put(key, value) { const node = this.cache.get(key); if (!node) { // Create new node const newNode = { key, value, prev: null, next: null }; this.cache.set(key, newNode); this._addNode(newNode); if (this.cache.size > this.capacity) { // Evict LRU const tail = this._popTail(); this.cache.delete(tail.key); } } else { // Update value and move to head node.value = value; this._moveToHead(node); } } } ```Evaluate arithmeticPassed
3,206 tokens: 204 read, 3,002 written · 1 min 5 s · 45.9 tok/s
Write a JavaScript function evaluate(expr) that returns the value of an arithmetic expression given as a string. The expression has non-negative integers, the operators + - * /, parentheses, unary minus (as in -3, - -3, 2 * -3 or -(1 + 2)) and spaces anywhere between tokens. * and / bind tighter than + and -, and operators of the same kind group from the left. / is integer division that truncates toward zero: 7 / 2 is 3 and -7 / 2 is -3. Dividing by zero must throw an Error. Do not use eval or Function. evaluate("2 + 3 * (4 - 6) / 4") returns 1. Reply with one ```js code block holding plain JavaScript (no imports, no exports, no DOM, no timers). The site runs it with hidden tests.```js function evaluate(expr) { let i = 0; const n = expr.length; function skipSpaces() { while (i < n && expr[i] === ' ') i++; } function parseNumber() { skipSpaces(); const start = i; while (i < n && expr[i] >= '0' && expr[i] <= '9') i++; if (start === i) throw new Error("Expected number"); return parseInt(expr.slice(start, i), 10); } function parsePrimary() { skipSpaces(); if (i < n && expr[i] === '(') { i++; const val = parseExpression(); skipSpaces(); if (i >= n || expr[i] !== ')') throw new Error("Expected )"); i++; return val; } return parseNumber(); } function parseFactor() { skipSpaces(); if (i < n && expr[i] === '-') { i++; return -parseFactor(); } return parsePrimary(); } function parseTerm() { let val = parseFactor(); while (true) { skipSpaces(); if (i < n && (expr[i] === '*' || expr[i] === '/')) { const op = expr[i]; i++; const right = parseFactor(); if (op === '*') { val = val * right; } else { if (right === 0) throw new Error("Division by zero"); val = Math.trunc(val / right); } } else { break; } } return val; } function parseExpression() { let val = parseTerm(); while (true) { skipSpaces(); if (i < n && (expr[i] === '+' || expr[i] === '-')) { const op = expr[i]; i++; const right = parseTerm(); if (op === '+') val = val + right; else val = val - right; } else { break; } } return val; } const result = parseExpression(); skipSpaces(); if (i !== n) throw new Error("Unexpected characters"); return result; } ```
Fixing code 2 of 2
Fix the bookings modulePassed
1,731 tokens: 633 read, 1,098 written · 23 s · 48.5 tok/s
This JavaScript module has one bug. The occupancy report sometimes counts one booked night more than there is in the range it was asked about. Find it and fix it without changing anything else. ```js // Bookings for one holiday flat. A booking is { guest, checkIn, checkOut } with dates as "YYYY-MM-DD". // A guest sleeps the nights from checkIn up to, but not including, checkOut: checkOut is the day they leave, // and another guest may check in that same day. function dayNumber(date) { const [y, m, d] = date.split('-').map(Number); return Date.UTC(y, m - 1, d) / 86400000; } function toDate(day) { return new Date(day * 86400000).toISOString().slice(0, 10); } function nights(booking) { return dayNumber(booking.checkOut) - dayNumber(booking.checkIn); } function overlaps(a, b) { return dayNumber(a.checkIn) < dayNumber(b.checkOut) && dayNumber(b.checkIn) < dayNumber(a.checkOut); } function canBook(bookings, request) { if (nights(request) < 1) return false; for (const booking of bookings) { if (overlaps(booking, request)) return false; } return true; } function isBooked(bookings, day) { return bookings.some((b) => dayNumber(b.checkIn) <= day && day < dayNumber(b.checkOut)); } // The nights from `from` up to, but not including, `to` that someone has booked. function bookedNights(bookings, from, to) { let count = 0; for (let day = dayNumber(from); day <= dayNumber(to); day++) { if (isBooked(bookings, day)) count++; } return count; } // The first night on or after `from` that nobody has booked, as "YYYY-MM-DD". function firstFreeNight(bookings, from) { let day = dayNumber(from); while (isBooked(bookings, day)) day++; return toDate(day); } // The price in cents: Friday and Saturday nights at rates.weekend, every other night at rates.weekday. function price(booking, rates) { let total = 0; for (let day = dayNumber(booking.checkIn); day < dayNumber(booking.checkOut); day++) { const weekday = new Date(day * 86400000).getUTCDay(); total += weekday === 5 || weekday === 6 ? rates.weekend : rates.weekday; } return total; } ``` Reply with the whole corrected module in one ```js code block, with the same function names.```js // Bookings for one holiday flat. A booking is { guest, checkIn, checkOut } with dates as "YYYY-MM-DD". // A guest sleeps the nights from checkIn up to, but not including, checkOut: checkOut is the day they leave, // and another guest may check in that same day. function dayNumber(date) { const [y, m, d] = date.split('-').map(Number); return Date.UTC(y, m - 1, d) / 86400000; } function toDate(day) { return new Date(day * 86400000).toISOString().slice(0, 10); } function nights(booking) { return dayNumber(booking.checkOut) - dayNumber(booking.checkIn); } function overlaps(a, b) { return dayNumber(a.checkIn) < dayNumber(b.checkOut) && dayNumber(b.checkIn) < dayNumber(a.checkOut); } function canBook(bookings, request) { if (nights(request) < 1) return false; for (const booking of bookings) { if (overlaps(booking, request)) return false; } return true; } function isBooked(bookings, day) { return bookings.some((b) => dayNumber(b.checkIn) <= day && day < dayNumber(b.checkOut)); } // The nights from `from` up to, but not including, `to` that someone has booked. function bookedNights(bookings, from, to) { let count = 0; for (let day = dayNumber(from); day < dayNumber(to); day++) { if (isBooked(bookings, day)) count++; } return count; } // The first night on or after `from` that nobody has booked, as "YYYY-MM-DD". function firstFreeNight(bookings, from) { let day = dayNumber(from); while (isBooked(bookings, day)) day++; return toDate(day); } // The price in cents: Friday and Saturday nights at rates.weekend, every other night at rates.weekday. function price(booking, rates) { let total = 0; for (let day = dayNumber(booking.checkIn); day < dayNumber(booking.checkOut); day++) { const weekday = new Date(day * 86400000).getUTCDay(); total += weekday === 5 || weekday === 6 ? rates.weekend : rates.weekday; } return total; } ```Fix the CSV readerPassed
2,988 tokens: 474 read, 2,514 written · 1 min 55 s · 21.8 tok/s
This JavaScript module has one bug. A quoted field with a comma in it, such as "Smith, Jane", is split in two. Find it and fix it without changing anything else. ```js // Reads CSV the way spreadsheets write it: fields are separated by commas, a field may be wrapped in // double quotes so it can hold commas, and "" inside a quoted field stands for one double quote. // Fields are not trimmed. Empty lines are skipped. function parseLine(line) { const fields = []; let field = ''; let quoted = false; for (let i = 0; i < line.length; i++) { const ch = line[i]; if (quoted && ch !== ',') { if (ch === '"') { if (line[i + 1] === '"') { field += '"'; i++; } else { quoted = false; } } else { field += ch; } } else if (ch === '"') { quoted = true; } else if (ch === ',') { fields.push(field); field = ''; } else { field += ch; } } fields.push(field); return fields; } function parseCSV(text) { return text.split(/\r?\n/).filter((line) => line !== '').map(parseLine); } // Each row after the header as an object keyed by the header's names; a missing field is ''. function toObjects(text) { const [header, ...rows] = parseCSV(text); return rows.map((row) => { const record = {}; header.forEach((name, i) => { record[name] = i < row.length ? row[i] : ''; }); return record; }); } // The sum of a column's numbers; fields that are not numbers count as 0. function sumColumn(text, name) { return toObjects(text).reduce((total, record) => total + (Number(record[name]) || 0), 0); } ``` Reply with the whole corrected module in one ```js code block, with the same function names.```js // Reads CSV the way spreadsheets write it: fields are separated by commas, a field may be wrapped in // double quotes so it can hold commas, and "" inside a quoted field stands for one double quote. // Fields are not trimmed. Empty lines are skipped. function parseLine(line) { const fields = []; let field = ''; let quoted = false; for (let i = 0; i < line.length; i++) { const ch = line[i]; if (quoted) { if (ch === '"') { if (line[i + 1] === '"') { field += '"'; i++; } else { quoted = false; } } else { field += ch; } } else if (ch === '"') { quoted = true; } else if (ch === ',') { fields.push(field); field = ''; } else { field += ch; } } fields.push(field); return fields; } function parseCSV(text) { return text.split(/\r?\n/).filter((line) => line !== '').map(parseLine); } // Each row after the header as an object keyed by the header's names; a missing field is ''. function toObjects(text) { const [header, ...rows] = parseCSV(text); return rows.map((row) => { const record = {}; header.forEach((name, i) => { record[name] = i < row.length ? row[i] : ''; }); return record; }); } // The sum of a column's numbers; fields that are not numbers count as 0. function sumColumn(text, name) { return toObjects(text).reduce((total, record) => total + (Number(record[name]) || 0), 0); } ```
Planning and data 3 of 3
A query over hidden dataPassed
1,106 tokens: 233 read, 873 written · 26 s · 33 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.SELECT c.name, COUNT(o.id) AS orders FROM customers c LEFT JOIN orders o ON c.id = o.customer_id WHERE NOT EXISTS ( SELECT 1 FROM orders o2 WHERE o2.customer_id = c.id AND o2.status = 'delivered' ) GROUP BY c.id, c.name;Schedule five meetingsPassed
4,570 tokens: 297 read, 4,273 written · 1 min 40 s · 42.8 tok/s
Five people each have one meeting today: Eli, Fay, Hal, Lea, Max. The five meetings are at different times, 09:00, 10:00, 11:00, 13:00, 14:00 (in that order: 10:00 is right after 09:00, 13:00 right after 11:00), and in different rooms. The list of rooms, in order: Birch, Maple, Pine, Rowan, Willow. 1. Lea meets before lunch (before 13:00). 2. Lea's meeting is in the slot right after Eli's. 3. Fay's and Max's rooms are next to each other on the list of rooms. 4. Eli's and Fay's rooms are not next to each other on the list of rooms. 5. Whoever is in Pine meets earlier than Eli. 6. Eli's and Max's rooms are not next to each other on the list of rooms. 7. Whoever is in Willow meets earlier than Hal. 8. Whoever is in Maple meets earlier than Fay. 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
Eli: 10:00, Birch Fay: 14:00, Rowan Hal: 13:00, Maple Lea: 11:00, Willow Max: 09:00, Pine
A replacement in ten calls or fewerPassed
15,321 tokens: 13,994 read, 1,327 written · 35 s · 38.1 tok/s
Hi, it's dee.holm@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 dee.holm@example.com. My kettle arrived with a cracked lid. Can you sort it out?
- assistant
lookup_account({"email":"dee.holm@example.com"}) - tool
{"account_id": "AC-630", "name": "Dee Holm"} - assistant
list_orders({"account_id":"AC-630"}) - tool
{"orders": [{"order_id": "R-5529", "placed": "2026-10-18", "status": "delivered"}, {"order_id": "R-5176", "placed": "2026-10-03", "status": "delivered"}, {"order_id": "R-5767", "placed": "2026-10-22", "status": "in transit"}]} - assistant
get_order({"order_id":"R-5529"}) - tool
{"items": [{"name": "Oak table lamp", "quantity": 1, "sku": "lamp-oak"}], "order_id": "R-5529"} - assistant
get_order({"order_id":"R-5176"}) - tool
{"items": [{"name": "Steel kettle", "quantity": 1, "sku": "kettle-steel"}, {"name": "Grey mug", "quantity": 2, "sku": "mug-grey"}], "order_id": "R-5176"} - 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({"warehouse":"south","sku":"kettle-steel","order_id":"R-5176"}) - tool
{"reservation_id": "RS-4247", "ships_on": "2026-11-03"} - assistant
create_return({"order_id":"R-5176","reason":"cracked lid"}) - tool
{"error": "damaged items are not returned: open a damage claim with open_claim instead"} - assistant
open_claim({"order_id":"R-5176","reason":"cracked lid"}) - tool
{"claim_id": "CL-7602", "order_id": "R-5176", "status": "open"} - assistant
I've sorted this out for you, Dee. Here's what I've done: **Order identified:** R-5176 (placed 3 Oct 2026, delivered) – this is the order containing the Steel kettle (sku: kettle-steel) with the cracked lid. **Replacement shipped from South warehouse:** - The North warehouse had no stock, so I sourced the replacement from the South warehouse (3 units available). - Reservation reference: **RS-4247** - The replacement will ship on **3 November 2026**. **Damage claim opened:** - Since damaged items aren't returned, I opened a damage claim instead of a return. - Claim reference: **CL-7602** (status: open) You'll receive the replacement kettle on or around 3 November. If you have any questions about the claim or the shipment, just let me know.
- system
Comments
Sign in or create an account to comment.