Models 44

Claude Haiku 5.5

by AnthropicReasoningClean
Open in new window

Running live in a sandboxed frame. Click inside it before using the keyboard.

How it went

Total time
23.1 s
Cost
$0.0036
Output tokens
7,035
Spent thinking
0 tokens
Speed
313.6 tok/s
Console errors
0
First token after
629 ms
First visible text after
629 ms
Prompt tokens
749
Code size
14.3 KB
Finish reason
stop
Served by
Claude Platform on AWS
Model id
anthropic/claude-haiku-5.5
Reasoning sent
{"effort":"none"}
Max output
32,000 tokens
Generated
Nov 10, 2026

What it was asked

The prompt
Build a polished Snake game in a single HTML file using vanilla JavaScript and a <canvas>. Requirements: - A grid of at least 20×20 cells, centered on the page. - Arrow keys and WASD control the snake. Quick successive key presses must both be honored, but the snake can never reverse onto itself. - Eating food adds 10 points and grows the snake by one cell; new food never spawns on the snake. - Game over when the snake hits a wall or itself, with an overlay showing the score; Space or Enter restarts, P pauses. - Visual polish: smooth movement, a snake with a distinct head and eyes facing its direction, and a small particle burst when eating. - Display the current score and the best score of the session.
System prompt, sent with every prompt
You are generating a self-contained web demo. It will be rendered automatically in a sandboxed iframe and compared side by side with the output of other AI models given the exact same task.

Output rules:
- Reply with exactly ONE fenced code block containing the complete file: ```html (or ```svg when the task asks for an SVG). No text before or after the code block.
- Everything must be inline: CSS in <style>, JavaScript in <script>. No external files, images, fonts or network requests, except the CDN URLs explicitly allowed by the task.
- Do not use localStorage, sessionStorage, cookies, IndexedDB, alert(), confirm(), prompt() or window.open(): they are blocked in the sandbox and will throw.
- The page must look right in a 1280×800 viewport and adapt gracefully down to 375px wide. No horizontal scrollbar.
- Something meaningful must be visible on first paint: a screenshot is taken automatically about 3 seconds after load, without any interaction.
- Everything that makes the demo interesting must be visible within the first seconds: nothing hidden behind a high score, a later level or a long play session.
- Games must start in a self-playing demo mode (a simple AI plays) behind a "Click or press a key to start" message, so the game can be judged in action without playing.
- The iframe only receives keyboard events after the user clicks it: if the demo uses the keyboard, display a clear "Click or press a key to start" message.
- The code must run with zero errors in the console of the latest Chrome.

Code run-1.html · 507 lines

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake</title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  html, body {
    height: 100%;
    background: radial-gradient(ellipse at center, #1b2a3a 0%, #0b1118 100%);
    color: #e6f1ff;
    font-family: "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    overflow-x: hidden;
  }
  body {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    padding: 16px;
  }
  .wrap {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 14px;
    width: 100%;
    max-width: 640px;
  }
  .hud {
    display: flex;
    justify-content: space-between;
    width: 100%;
    max-width: 560px;
    font-size: 18px;
    letter-spacing: 1px;
    text-transform: uppercase;
  }
  .hud .box {
    background: rgba(255,255,255,0.06);
    border: 1px solid rgba(120,200,255,0.25);
    border-radius: 10px;
    padding: 8px 16px;
    min-width: 130px;
    text-align: center;
  }
  .hud .label { font-size: 11px; opacity: 0.6; }
  .hud .value { font-size: 22px; font-weight: 700; color: #7ef0c0; }
  .board-wrap {
    position: relative;
    width: min(92vw, 560px);
    aspect-ratio: 1 / 1;
  }
  canvas {
    width: 100%;
    height: 100%;
    display: block;
    border-radius: 14px;
    box-shadow: 0 0 40px rgba(60,200,255,0.18), inset 0 0 0 2px rgba(120,200,255,0.25);
    background: #0f1c28;
  }
  .overlay {
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 10px;
    background: rgba(8,14,22,0.72);
    border-radius: 14px;
    text-align: center;
    padding: 20px;
    pointer-events: none;
    transition: opacity 0.25s;
  }
  .overlay.hidden { opacity: 0; }
  .overlay h1 {
    font-size: clamp(28px, 6vw, 40px);
    color: #7ef0c0;
    text-shadow: 0 0 18px rgba(126,240,192,0.5);
  }
  .overlay p { font-size: clamp(14px, 3vw, 17px); opacity: 0.85; }
  .overlay .blink { animation: blink 1.2s infinite; color: #ffd166; font-weight: 600; }
  @keyframes blink { 50% { opacity: 0.35; } }
  .help {
    font-size: 13px;
    opacity: 0.55;
    text-align: center;
  }
  @media (max-width: 420px) {
    .hud { font-size: 14px; }
    .hud .box { min-width: 0; flex: 1; margin: 0 4px; padding: 6px 8px; }
    .hud .value { font-size: 18px; }
  }
</style>
</head>
<body>
<div class="wrap">
  <div class="hud">
    <div class="box"><div class="label">Score</div><div class="value" id="score">0</div></div>
    <div class="box"><div class="label">Best</div><div class="value" id="best">0</div></div>
  </div>
  <div class="board-wrap">
    <canvas id="game"></canvas>
    <div class="overlay" id="overlay">
      <h1 id="ovTitle">SNAKE</h1>
      <p id="ovText">Click or press a key to start</p>
      <p class="blink" id="ovHint"></p>
    </div>
  </div>
  <div class="help">Arrows / WASD to move &nbsp;·&nbsp; P to pause &nbsp;·&nbsp; Space / Enter to restart</div>
</div>

<script>
(function () {
  const canvas = document.getElementById('game');
  const ctx = canvas.getContext('2d');
  const scoreEl = document.getElementById('score');
  const bestEl = document.getElementById('best');
  const overlay = document.getElementById('overlay');
  const ovTitle = document.getElementById('ovTitle');
  const ovText = document.getElementById('ovText');
  const ovHint = document.getElementById('ovHint');

  const COLS = 24, ROWS = 24;
  const TICK_MS = 110;          // logical step interval
  const DPR = Math.min(window.devicePixelRatio || 1, 2);

  let cell = 0, size = 0;

  function resize() {
    const rect = canvas.getBoundingClientRect();
    size = Math.round(rect.width);
    canvas.width = size * DPR;
    canvas.height = size * DPR;
    ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
    cell = size / COLS;
    draw();
  }
  window.addEventListener('resize', resize);

  // ---------- State ----------
  const DIRS = {
    up:    { x: 0, y: -1 },
    down:  { x: 0, y: 1 },
    left:  { x: -1, y: 0 },
    right: { x: 1, y: 0 }
  };
  let snake, dir, nextDirs, food, score, best = 0;
  let state = 'demo';           // 'demo' | 'ready' | 'playing' | 'paused' | 'over'
  let particles = [];
  let lastTick = 0, acc = 0;
  let headPos;                  // interpolated {x,y} in cell units
  let prevSnake;                // snapshot for interpolation
  let deathFlash = 0;
  let started = false;         // user has interacted once

  function newGame() {
    const cx = Math.floor(COLS / 2), cy = Math.floor(ROWS / 2);
    snake = [
      { x: cx, y: cy },
      { x: cx - 1, y: cy },
      { x: cx - 2, y: cy }
    ];
    prevSnake = snake.map(s => ({ ...s }));
    dir = DIRS.right;
    nextDirs = [];
    score = 0;
    particles = [];
    headPos = { x: snake[0].x, y: snake[0].y };
    placeFood();
    updateHud();
  }

  function placeFood() {
    const occupied = new Set(snake.map(s => s.x + ',' + s.y));
    const free = [];
    for (let x = 0; x < COLS; x++)
      for (let y = 0; y < ROWS; y++)
        if (!occupied.has(x + ',' + y)) free.push({ x, y });
    food = free.length ? free[Math.floor(Math.random() * free.length)] : null;
  }

  function updateHud() {
    scoreEl.textContent = score;
    bestEl.textContent = best;
  }

  // ---------- Overlay ----------
  function showOverlay(title, text, hint) {
    ovTitle.textContent = title;
    ovText.textContent = text;
    ovHint.textContent = hint || '';
    overlay.classList.remove('hidden');
  }
  function hideOverlay() { overlay.classList.add('hidden'); }

  // ---------- Input ----------
  const KEYMAP = {
    ArrowUp: 'up', KeyW: 'up',
    ArrowDown: 'down', KeyS: 'down',
    ArrowLeft: 'left', KeyA: 'left',
    ArrowRight: 'right', KeyD: 'right'
  };

  function turnTo(name) {
    const d = DIRS[name];
    // Compare against the last queued direction (or current) to forbid reversing
    const ref = nextDirs.length ? nextDirs[nextDirs.length - 1] : dir;
    if (d.x === -ref.x && d.y === -ref.y) return;
    if (d.x === ref.x && d.y === ref.y) return;
    if (nextDirs.length < 3) nextDirs.push(d);
  }

  function startPlaying() {
    newGame();
    state = 'playing';
    hideOverlay();
    lastTick = performance.now();
  }

  window.addEventListener('keydown', (e) => {
    started = true;
    const name = KEYMAP[e.code];
    if (name) {
      e.preventDefault();
      if (state === 'demo' || state === 'ready') startPlaying();
      if (state === 'playing') turnTo(name);
      return;
    }
    if (e.code === 'KeyP') {
      e.preventDefault();
      if (state === 'playing') {
        state = 'paused';
        showOverlay('PAUSED', 'Press P to resume', '');
      } else if (state === 'paused') {
        state = 'playing';
        hideOverlay();
        lastTick = performance.now();
      }
      return;
    }
    if (e.code === 'Space' || e.code === 'Enter') {
      e.preventDefault();
      if (state === 'demo' || state === 'ready' || state === 'over') startPlaying();
    }
  });

  canvas.addEventListener('click', () => {
    started = true;
    if (state === 'demo' || state === 'ready' || state === 'over') startPlaying();
  });
  overlay.addEventListener('click', () => {
    if (state === 'demo' || state === 'ready' || state === 'over') startPlaying();
  });

  // ---------- Particles ----------
  function burst(gx, gy, color) {
    const px = (gx + 0.5) * cell, py = (gy + 0.5) * cell;
    for (let i = 0; i < 18; i++) {
      const a = Math.random() * Math.PI * 2;
      const sp = 40 + Math.random() * 90;
      particles.push({
        x: px, y: py,
        vx: Math.cos(a) * sp,
        vy: Math.sin(a) * sp,
        life: 1,
        color
      });
    }
  }

  // ---------- AI for demo mode ----------
  function aiChooseDir() {
    const head = snake[0];
    const candidates = [];
    for (const k of Object.keys(DIRS)) {
      const d = DIRS[k];
      if (d.x === -dir.x && d.y === -dir.y) continue;
      const nx = head.x + d.x, ny = head.y + d.y;
      if (nx < 0 || ny < 0 || nx >= COLS || ny >= ROWS) continue;
      if (snake.some((s, i) => i < snake.length - 1 && s.x === nx && s.y === ny)) continue;
      const dist = food ? Math.abs(nx - food.x) + Math.abs(ny - food.y) : 0;
      candidates.push({ d, dist });
    }
    if (!candidates.length) return dir;
    candidates.sort((a, b) => a.dist - b.dist);
    return candidates[0].d;
  }

  // ---------- Logic tick ----------
  function step() {
    if (state === 'demo') {
      if (!nextDirs.length) nextDirs.push(aiChooseDir());
    }

    prevSnake = snake.map(s => ({ ...s }));

    if (nextDirs.length) dir = nextDirs.shift();

    const head = snake[0];
    const nx = head.x + dir.x, ny = head.y + dir.y;

    // Wall or self collision
    const hitWall = nx < 0 || ny < 0 || nx >= COLS || ny >= ROWS;
    const bodyCheck = snake.slice(0, snake.length - 1);
    const hitSelf = bodyCheck.some(s => s.x === nx && s.y === ny);

    if (hitWall || hitSelf) {
      if (state === 'demo') {
        // restart demo silently
        newGame();
        return;
      }
      gameOver();
      return;
    }

    snake.unshift({ x: nx, y: ny });

    if (food && nx === food.x && ny === food.y) {
      score += 10;
      if (score > best) best = score;
      burst(nx, ny, '#ffd166');
      placeFood();
      updateHud();
      // keep tail (grow)
      prevSnake.push({ ...prevSnake[prevSnake.length - 1] });
    } else {
      snake.pop();
    }

    if (!food) {
      // board filled — victory-ish: restart
      if (state !== 'demo') {
        gameOver();
      }
    }
  }

  function gameOver() {
    state = 'over';
    deathFlash = 1;
    const head = snake[0];
    burst(head.x, head.y, '#ff6b6b');
    showOverlay('GAME OVER', 'Score: ' + score + (score >= best && score > 0 ? '  ·  New best!' : ''),
      'Space / Enter to restart');
    updateHud();
  }

  // ---------- Drawing ----------
  function roundRect(x, y, w, h, r) {
    ctx.beginPath();
    ctx.moveTo(x + r, y);
    ctx.arcTo(x + w, y, x + w, y + h, r);
    ctx.arcTo(x + w, y + h, x, y + h, r);
    ctx.arcTo(x, y + h, x, y, r);
    ctx.arcTo(x, y, x + w, y, r);
    ctx.closePath();
  }

  function drawGrid() {
    ctx.strokeStyle = 'rgba(120,200,255,0.06)';
    ctx.lineWidth = 1;
    ctx.beginPath();
    for (let i = 1; i < COLS; i++) {
      ctx.moveTo(i * cell, 0); ctx.lineTo(i * cell, size);
    }
    for (let j = 1; j < ROWS; j++) {
      ctx.moveTo(0, j * cell); ctx.lineTo(size, j * cell);
    }
    ctx.stroke();
  }

  function drawFood(t) {
    if (!food) return;
    const cx = (food.x + 0.5) * cell, cy = (food.y + 0.5) * cell;
    const pulse = 1 + Math.sin(t / 180) * 0.08;
    const r = cell * 0.34 * pulse;
    const g = ctx.createRadialGradient(cx, cy, 1, cx, cy, cell * 0.9);
    g.addColorStop(0, 'rgba(255,209,102,0.45)');
    g.addColorStop(1, 'rgba(255,209,102,0)');
    ctx.fillStyle = g;
    ctx.beginPath(); ctx.arc(cx, cy, cell * 0.9, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = '#ffd166';
    ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = 'rgba(255,255,255,0.7)';
    ctx.beginPath(); ctx.arc(cx - r * 0.3, cy - r * 0.3, r * 0.25, 0, Math.PI * 2); ctx.fill();
  }

  function segPos(i, t) {
    const cur = snake[i];
    const prev = prevSnake[i] || cur;
    return {
      x: (prev.x + (cur.x - prev.x) * t + 0.5) * cell,
      y: (prev.y + (cur.y - prev.y) * t + 0.5) * cell
    };
  }

  function drawSnake(t) {
    const n = snake.length;
    // body as connected rounded segments
    for (let i = n - 1; i >= 1; i--) {
      const p = segPos(i, t);
      const k = i / n;
      const color = `hsl(${150 - k * 20}, ${70 - k * 15}%, ${52 - k * 18}%)`;
      ctx.fillStyle = color;
      const s = cell * (0.86 - k * 0.22);
      roundRect(p.x - s / 2, p.y - s / 2, s, s, s * 0.35);
      ctx.fill();
    }
    // head
    const hp = segPos(0, t);
    const hs = cell * 0.92;
    ctx.save();
    ctx.shadowColor = 'rgba(126,240,192,0.7)';
    ctx.shadowBlur = 12;
    ctx.fillStyle = '#7ef0c0';
    roundRect(hp.x - hs / 2, hp.y - hs / 2, hs, hs, hs * 0.4);
    ctx.fill();
    ctx.restore();

    // eyes facing direction
    const d = dir;
    const perpX = -d.y, perpY = d.x;
    const eyeOff = cell * 0.2, eyeFwd = cell * 0.12;
    const eyes = [
      { x: hp.x + d.x * eyeFwd + perpX * eyeOff, y: hp.y + d.y * eyeFwd + perpY * eyeOff },
      { x: hp.x + d.x * eyeFwd - perpX * eyeOff, y: hp.y + d.y * eyeFwd - perpY * eyeOff }
    ];
    eyes.forEach(e => {
      ctx.fillStyle = '#fff';
      ctx.beginPath(); ctx.arc(e.x, e.y, cell * 0.14, 0, Math.PI * 2); ctx.fill();
      ctx.fillStyle = '#0b1118';
      ctx.beginPath();
      ctx.arc(e.x + d.x * cell * 0.04, e.y + d.y * cell * 0.04, cell * 0.07, 0, Math.PI * 2);
      ctx.fill();
    });
  }

  function drawParticles(dt) {
    particles = particles.filter(p => p.life > 0);
    for (const p of particles) {
      p.x += p.vx * dt;
      p.y += p.vy * dt;
      p.vx *= 0.95; p.vy *= 0.95;
      p.life -= dt * 2.2;
      ctx.globalAlpha = Math.max(0, p.life);
      ctx.fillStyle = p.color;
      ctx.beginPath();
      ctx.arc(p.x, p.y, 2.5 * Math.max(0.2, p.life) + 1, 0, Math.PI * 2);
      ctx.fill();
    }
    ctx.globalAlpha = 1;
  }

  function draw(t = performance.now(), dt = 0) {
    if (!size) return;
    ctx.clearRect(0, 0, size, size);
    drawGrid();
    drawFood(t);
    if (snake) drawSnake(state === 'playing' || state === 'demo' ? Math.min(acc / TICK_MS, 1) : 1);
    drawParticles(dt);
    if (deathFlash > 0) {
      ctx.fillStyle = `rgba(255,80,80,${deathFlash * 0.25})`;
      ctx.fillRect(0, 0, size, size);
    }
  }

  // ---------- Main loop ----------
  let lastFrame = performance.now();
  function frame(now) {
    const frameDt = Math.min((now - lastFrame) / 1000, 0.05);
    lastFrame = now;

    if (state === 'playing' || state === 'demo') {
      acc += now - lastTick;
      lastTick = now;
      while (acc >= TICK_MS) {
        acc -= TICK_MS;
        step();
        if (state === 'over') { acc = 0; break; }
      }
    } else {
      lastTick = now;
    }

    if (deathFlash > 0) deathFlash = Math.max(0, deathFlash - frameDt * 2);

    draw(now, frameDt);
    requestAnimationFrame(frame);
  }

  // ---------- Boot ----------
  resize();
  newGame();
  state = 'demo';
  lastTick = performance.now();
  showOverlay('SNAKE', 'Click or press a key to start', '');
  overlay.style.background = 'rgba(8,14,22,0.35)';
  requestAnimationFrame(frame);
})();
</script>
</body>
</html>