Snake, with juice, built by Inkling 2 Mini
Hostedvia OpenCodeOpenRouter
43tok/s
First token included
104.3Ktokens
40m 6s
$0.31
Show the code the model wroteHide the code
<!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>
:root {
--bg: #0b0f14;
--panel: #141b24;
--ink: #e8eef4;
--muted: #8b98a8;
--accent: #34d399;
--food: #fb7185;
--danger: #f87171;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body {
background: var(--bg);
color: var(--ink);
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
overflow: hidden;
height: 100dvh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
user-select: none;
-webkit-user-select: none;
}
#hud {
display: flex;
justify-content: space-between;
align-items: center;
width: min(92vw, calc(100dvh - 140px), 640px);
min-height: 38px;
gap: 16px;
}
.hud-box {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 90px;
}
.hud-box.right { text-align: right; align-items: flex-end; }
.hud-label {
font-size: 10px;
letter-spacing: 0.22em;
text-transform: uppercase;
color: var(--muted);
}
.hud-value {
font-size: 26px;
font-weight: 700;
font-variant-numeric: tabular-nums;
line-height: 1.1;
}
#speedBadge {
display: inline-flex;
align-items: baseline;
gap: 8px;
background: var(--panel);
border: 1px solid #223041;
border-radius: 8px;
padding: 4px 12px;
transform-origin: center;
transition: border-color 0.2s;
}
#speedBadge.beat { animation: beat 0.45s ease-out; }
@keyframes beat {
0% { transform: scale(1); border-color: #223041; }
25% { transform: scale(1.28); border-color: var(--accent); box-shadow: 0 0 18px rgba(52, 211, 153, 0.45); }
100% { transform: scale(1); border-color: #223041; box-shadow: none; }
}
#speedBadge .lvl { color: var(--accent); font-size: 24px; font-weight: 700; }
#speedBadge .ms { color: var(--muted); font-size: 11px; letter-spacing: 0.08em; }
#wrap {
position: relative;
width: min(92vw, calc(100dvh - 132px), 640px);
height: min(92vw, calc(100dvh - 132px), 640px);
}
canvas {
display: block;
width: 100%;
height: 100%;
border-radius: 14px;
background: #0f1620;
box-shadow: 0 0 0 1px #1d2836, 0 24px 60px rgba(0,0,0,0.55), 0 0 90px rgba(52,211,153,0.05);
}
#overlay {
position: absolute;
inset: 0;
border-radius: 14px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
text-align: center;
background: rgba(8, 12, 17, 0.78);
backdrop-filter: blur(6px);
-webkit-backdrop-filter: blur(6px);
opacity: 0;
pointer-events: none;
transition: opacity 0.28s ease;
}
#overlay.show { opacity: 1; }
#overlay h1 {
font-size: clamp(28px, 7vmin, 46px);
letter-spacing: 0.12em;
font-weight: 800;
}
#overlay .sub {
color: var(--muted);
font-size: clamp(12px, 2.2vmin, 15px);
letter-spacing: 0.06em;
}
#overlay .big {
font-size: clamp(38px, 9vmin, 64px);
font-weight: 800;
color: var(--ink);
font-variant-numeric: tabular-nums;
line-height: 1;
}
#overlay .best {
color: var(--accent);
font-size: clamp(14px, 2.6vmin, 18px);
letter-spacing: 0.1em;
}
#overlay .keys {
margin-top: 10px;
color: var(--ink);
font-size: clamp(12px, 2.2vmin, 15px);
background: var(--panel);
border: 1px solid #223041;
border-radius: 10px;
padding: 10px 18px;
animation: blink 1.6s ease-in-out infinite;
}
@keyframes blink { 0%,100% { opacity: 0.55; } 50% { opacity: 1; } }
#pausedOverlay h1 { color: var(--ink); font-size: clamp(24px, 6vmin, 40px); }
@media (max-height: 520px) {
#hud { width: min(96vmin, 560px); flex-direction: row; gap: 10px; }
.hud-value { font-size: 20px; }
}
</style>
</head>
<body>
<div id="hud">
<div class="hud-box"><span class="hud-label">Score</span><span class="hud-value" id="score">0</span></div>
<div class="hud-box right"><span class="hud-label">Speed</span>
<span id="speedBadge"><span class="lvl" id="lvl">1</span><span class="ms" id="ms">150ms</span></span>
</div>
</div>
<div id="wrap">
<canvas id="game"></canvas>
<div id="overlay"></div>
</div>
<script>
(() => {
'use strict';
// ---------- constants ----------
const GRID = 24;
const TICK_BASE = 155;
const TICK_MIN = 62;
const TICK_STEP = 4.5; // ms shaved off per food eaten
const SCORE_PER_FOOD = 10;
const LEVEL_EVERY = 5; // foods per speed level
const DIRS = {
up: { x: 0, y: -1 },
down: { x: 0, y: 1 },
left: { x: -1, y: 0 },
right: { x: 1, y: 0 },
};
const OPPOSITE = { up: 'down', down: 'up', left: 'right', right: 'left' };
// ---------- DOM ----------
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const overlay = document.getElementById('overlay');
const scoreEl = document.getElementById('score');
const lvlEl = document.getElementById('lvl');
const msEl = document.getElementById('ms');
const speedBadge = document.getElementById('speedBadge');
// ---------- state ----------
let state = 'menu'; // menu | playing | paused | dead
let snake = []; // [{x,y}] head first
let prevSnake = []; // pre-tick snapshot for interpolation
let dir = 'right'; // current committed direction (grid)
let inputQueue = []; // buffered directions
let food = { x: 0, y: 0 };
let score = 0;
let best = 0;
let eats = 0;
let lastTick = 0; // ms timestamp of last tick
let tickInterval = TICK_BASE;
let level = 1;
let shake = 0; // decaying screen-shake magnitude (px)
let flash = 0; // death flash alpha 0..1
let time = 0; // global clock (seconds)
let particles = [];
let pops = [];
let rings = [];
// ---------- audio ----------
let actx = null;
function ensureAudio() {
if (!actx) {
const AC = window.AudioContext || window.webkitAudioContext;
if (AC) actx = new AC();
}
if (actx && actx.state === 'suspended') actx.resume();
}
function tone({ freq = 440, freqEnd = null, duration = 0.1, type = 'sine', gain = 0.16, delay = 0 }) {
if (!actx) return;
const t0 = actx.currentTime + delay;
const osc = actx.createOscillator();
const g = actx.createGain();
osc.type = type;
osc.frequency.setValueAtTime(freq, t0);
if (freqEnd) osc.frequency.exponentialRampToValueAtTime(Math.max(1, freqEnd), t0 + duration);
g.gain.setValueAtTime(0.0001, t0);
g.gain.linearRampToValueAtTime(gain, t0 + 0.006);
g.gain.exponentialRampToValueAtTime(0.0001, t0 + duration);
osc.connect(g).connect(actx.destination);
osc.start(t0);
osc.stop(t0 + duration + 0.05);
}
function noiseBurst({ duration = 0.25, gain = 0.2, delay = 0 }) {
if (!actx) return;
const t0 = actx.currentTime + delay;
const len = Math.floor(actx.sampleRate * duration);
const buffer = actx.createBuffer(1, len, actx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < len; i++) data[i] = (Math.random() * 2 - 1) * (1 - i / len);
const src = actx.createBufferSource();
src.buffer = buffer;
const filter = actx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(900, t0);
filter.frequency.exponentialRampToValueAtTime(120, t0 + duration);
const g = actx.createGain();
g.gain.setValueAtTime(gain, t0);
g.gain.exponentialRampToValueAtTime(0.0001, t0 + duration);
src.connect(filter).connect(g).connect(actx.destination);
src.start(t0);
}
const sfx = {
eat() {
tone({ freq: 523, freqEnd: 784, duration: 0.09, type: 'sine', gain: 0.18 });
tone({ freq: 1046, duration: 0.08, type: 'sine', gain: 0.09, delay: 0.055 });
},
levelUp() {
tone({ freq: 880, duration: 0.05, type: 'square', gain: 0.10 });
tone({ freq: 1318, duration: 0.07, type: 'square', gain: 0.08, delay: 0.05 });
},
death() {
tone({ freq: 220, freqEnd: 55, duration: 0.45, type: 'sawtooth', gain: 0.20 });
noiseBurst({ duration: 0.30, gain: 0.18 });
},
restart() {
tone({ freq: 392, freqEnd: 587, duration: 0.12, type: 'triangle', gain: 0.14 });
},
pause() {
tone({ freq: 330, duration: 0.05, type: 'triangle', gain: 0.09 });
},
};
// ---------- sizing / dpr ----------
let dpr = 1;
let viewSize = 0; // css px square side
let cell = 0; // css px per cell
function resize() {
const wrap = document.getElementById('wrap');
const rect = wrap.getBoundingClientRect();
viewSize = rect.width;
const dprNow = Math.min(window.devicePixelRatio || 1, 2);
dpr = dprNow;
canvas.width = Math.round(viewSize * dpr);
canvas.height = Math.round(viewSize * dpr);
cell = viewSize / GRID;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
window.addEventListener('resize', resize);
// ---------- helpers ----------
function freeCells() {
const occupied = new Set(snake.map(p => p.x + ',' + p.y));
const cells = [];
for (let y = 0; y < GRID; y++) {
for (let x = 0; x < GRID; x++) {
if (!occupied.has(x + ',' + y)) cells.push({ x, y });
}
}
return cells;
}
function placeFood() {
const cells = freeCells();
if (!cells.length) { food = { x: 0, y: 0 }; return; }
food = cells[Math.floor(Math.random() * cells.length)];
}
function tickFor(eatsCount) {
return Math.max(TICK_MIN, TICK_BASE - eatsCount * TICK_STEP);
}
function levelFor(eatsCount) {
return 1 + Math.floor(eatsCount / LEVEL_EVERY);
}
function clamp(v, a, b) { return Math.max(a, Math.min(b, v)); }
function lerp(a, b, t) { return a + (b - a) * t; }
// ---------- game flow ----------
function resetGame() {
const cx = Math.floor(GRID / 2);
snake = [
{ x: cx, y: cx },
{ x: cx - 1, y: cx },
{ x: cx - 2, y: cx },
];
prevSnake = snake.map(p => ({ ...p }));
dir = 'right';
inputQueue = [];
score = 0;
eats = 0;
level = 1;
tickInterval = tickFor(0);
shake = 0;
flash = 0;
particles = [];
pops = [];
rings = [];
time = 0;
placeFood();
lastTick = performance.now();
updateHud();
hideOverlay();
state = 'playing';
}
function showOverlay(html, visible = true) {
if (!visible) { overlay.classList.remove('show'); overlay.innerHTML = ''; return; }
overlay.innerHTML = html;
requestAnimationFrame(() => overlay.classList.add('show'));
}
function hideOverlay() { overlay.classList.remove('show'); }
function updateHud() {
scoreEl.textContent = score;
lvlEl.textContent = level;
msEl.textContent = Math.round(tickInterval) + 'ms';
}
function levelUpBeat() {
speedBadge.classList.remove('beat');
void speedBadge.offsetWidth;
speedBadge.classList.add('beat');
sfx.levelUp();
}
function gameOver() {
state = 'dead';
flash = 1;
shake = 16;
burst(snake[0].x, snake[0].y, '#f87171', 26, 1.5);
burst(snake[0].x, snake[0].y, '#34d399', 12, 1.0);
sfx.death();
if (score > best) best = score;
updateHud();
setTimeout(() => {
if (state !== 'dead') return;
showOverlay(`
<h1>GAME OVER</h1>
<div class="big">${score}</div>
<div class="best">BEST ${best}</div>
<div class="sub">Speed level ${level} · ${eats} bites</div>
<div class="keys">Press <b>SPACE</b> to restart</div>
`);
}, 450);
}
function restart() {
ensureAudio();
sfx.restart();
resetGame();
}
function togglePause() {
if (state === 'playing') {
state = 'paused';
sfx.pause();
showOverlay(`<h1>PAUSED</h1><div class="keys">Press <b>P</b> to resume</div>`);
} else if (state === 'paused') {
state = 'playing';
hideOverlay();
lastTick = performance.now();
sfx.pause();
}
}
// ---------- tick (one grid step) ----------
function step() {
prevSnake = snake.map(p => ({ ...p }));
// drain buffered input — apply first valid one
while (inputQueue.length) {
const d = inputQueue.shift();
if (d !== dir && d !== OPPOSITE[dir]) { dir = d; break; }
}
const head = { x: snake[0].x + DIRS[dir].x, y: snake[0].y + DIRS[dir].y };
const ateFood = head.x === food.x && head.y === food.y;
const keepsTail = ateFood;
// self-collision check (tail cell will vacate if this tick keeps nothing)
const bodyToCheck = keepsTail ? snake : snake.slice(0, snake.length - 1);
const hitsSelf = bodyToCheck.some(p => p.x === head.x && p.y === head.y);
const hitsWall = head.x < 0 || head.y < 0 || head.x >= GRID || head.y >= GRID;
if (hitsWall || hitsSelf) {
// crunch the head right up against the wall / into the body
const crunch = {
x: clamp(head.x, -0.45, GRID - 0.55),
y: clamp(head.y, -0.45, GRID - 0.55),
};
snake.unshift(crunch);
gameOver();
return;
}
snake.unshift(head);
if (ateFood) {
score += SCORE_PER_FOOD;
eats += 1;
const idx = levelFor(eats);
const newTick = tickFor(eats);
const leveled = idx > level;
level = idx;
tickInterval = newTick;
placeFood();
// juice: particle burst + rising score pop + eat blip
burst(head.x, head.y, '#fb7185', 16, 1.15);
burst(head.x, head.y, '#fde68a', 8, 0.8);
pops.push({ x: head.x + 0.5, y: head.y + 0.35, vy: -1.6, life: 1, text: '+' + SCORE_PER_FOOD });
rings.push({ x: head.x + 0.5, y: head.y + 0.5, life: 1 });
sfx.eat();
if (leveled) levelUpBeat();
} else {
snake.pop();
}
updateHud();
}
// ---------- particles / pops ----------
function burst(gx, gy, color, count, speedMul = 1) {
const cx = gx + 0.5, cy = gy + 0.5;
const base = cell;
for (let i = 0; i < count; i++) {
const ang = Math.random() * Math.PI * 2;
const sp = (0.8 + Math.random() * 1.6) * base * speedMul; // px/s-ish scale
particles.push({
x: cx, y: cy,
vx: Math.cos(ang) * sp,
vy: Math.sin(ang) * sp - base * 0.6,
life: 1,
decay: 1.6 + Math.random() * 1.4,
size: base * (0.10 + Math.random() * 0.13),
color,
});
}
}
function stepParticles(dt) {
const g = cell * 3.4; // gravity px/s^2
for (const p of particles) {
p.x += p.vx * dt;
p.y += p.vy * dt;
p.vy += g * dt;
p.vx *= (1 - 2.2 * dt);
p.life -= p.decay * dt;
}
particles = particles.filter(p => p.life > 0);
for (const p of pops) {
p.y += p.vy * dt;
p.life -= dt * 1.5;
}
pops = pops.filter(p => p.life > 0);
for (const r of rings) {
r.life -= dt * 2.1;
}
rings = rings.filter(r => r.life > 0);
}
// ---------- input ----------
const KEY_TO_DIR = {
arrowup: 'up', w: 'up',
arrowdown: 'down', s: 'down',
arrowleft: 'left', a: 'left',
arrowright: 'right', d: 'right',
};
window.addEventListener('keydown', (e) => {
const key = e.key.toLowerCase();
if (key === ' ' || key.startsWith('arrow')) e.preventDefault();
if (e.repeat) return;
ensureAudio();
// pause toggle
if (key === 'p') {
if (state === 'playing' || state === 'paused') togglePause();
return;
}
// restart / start
if (state === 'dead') {
if (key === ' ' || key === 'enter') restart();
return;
}
if (state === 'menu') {
if (KEY_TO_DIR[key] || key === ' ' || key === 'enter') {
restart();
const d = KEY_TO_DIR[key];
if (d && d !== dir) {
// pre-apply the requested direction as first buffered move
inputQueue.push(d);
}
}
return;
}
if (state !== 'playing') return;
const d = KEY_TO_DIR[key];
if (!d) return;
// validate against the last direction in the chain so a buffered
// 180° never gets committed out of turn
const last = inputQueue.length ? inputQueue[inputQueue.length - 1] : dir;
if (d === last || d === OPPOSITE[last]) return;
if (inputQueue.length >= 3) return;
inputQueue.push(d);
});
// tab hidden → pause
document.addEventListener('visibilitychange', () => {
if (document.hidden && state === 'playing') togglePause();
});
// ---------- rendering ----------
function drawGrid() {
const pad = cell * 0.5;
// vignette background wash
const grad = ctx.createRadialGradient(
viewSize / 2, viewSize / 2, viewSize * 0.2,
viewSize / 2, viewSize / 2, viewSize * 0.75
);
grad.addColorStop(0, '#101a26');
grad.addColorStop(1, '#0b1119');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, viewSize, viewSize);
// subtle grid
ctx.strokeStyle = 'rgba(148, 180, 210, 0.045)';
ctx.lineWidth = 1;
ctx.beginPath();
for (let i = 1; i < GRID; i++) {
const p = i * cell;
ctx.moveTo(p, 0); ctx.lineTo(p, viewSize);
ctx.moveTo(0, p); ctx.lineTo(viewSize, p);
}
ctx.stroke();
// faint center dots
ctx.fillStyle = 'rgba(148, 180, 210, 0.05)';
for (let y = 0; y < GRID; y++) {
for (let x = 0; x < GRID; x++) {
ctx.fillRect(x * cell + cell / 2 - 0.75, y * cell + cell / 2 - 0.75, 1.5, 1.5);
}
}
}
function drawFood() {
const cx = (food.x + 0.5) * cell;
const cy = (food.y + 0.5) * cell;
const pulse = 1 + 0.16 * Math.sin(time * 4.2);
const r = cell * 0.30 * pulse;
// glow
const glow = ctx.createRadialGradient(cx, cy, 0, cx, cy, cell * 1.1);
glow.addColorStop(0, 'rgba(251, 113, 133, 0.42)');
glow.addColorStop(1, 'rgba(251, 113, 133, 0)');
ctx.fillStyle = glow;
ctx.beginPath();
ctx.arc(cx, cy, cell * 1.1, 0, Math.PI * 2);
ctx.fill();
// ring with subtle breathing
ctx.strokeStyle = 'rgba(253, 164, 175, 0.55)';
ctx.lineWidth = Math.max(1, cell * 0.07);
ctx.beginPath();
ctx.arc(cx, cy, r + cell * 0.18 * (0.5 + 0.5 * Math.sin(time * 4.2 + Math.PI / 2)), 0, Math.PI * 2);
ctx.stroke();
// core
const core = ctx.createRadialGradient(cx - r * 0.35, cy - r * 0.35, r * 0.1, cx, cy, r);
core.addColorStop(0, '#fecdd3');
core.addColorStop(0.55, '#fb7185');
core.addColorStop(1, '#e11d48');
ctx.fillStyle = core;
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fill();
}
function drawSnake(f) {
// interpolate between prevSnake and snake
const pts = [];
for (let i = 0; i < snake.length; i++) {
const cur = snake[i];
const prev = prevSnake[i];
if (prev) {
pts.push({ x: lerp(prev.x, cur.x, f), y: lerp(prev.y, cur.y, f) });
} else {
pts.push({ ...cur });
}
}
const n = pts.length;
// travel direction for lean (head) — use committed dir for stability
const d = DIRS[dir];
const headP = pts[0];
const headCx = (headP.x + 0.5) * cell;
const headCy = (headP.y + 0.5) * cell;
const lean = cell * (0.18 + 0.07 * Math.sin(f * Math.PI)); // forward thrust bias
// build radii: taper from head → tail
const radii = [];
for (let i = 0; i < n; i++) {
const t = n <= 1 ? 0 : i / (n - 1);
radii.push(lerp(cell * 0.44, cell * 0.16, Math.pow(t, 0.85)));
}
// connected tapered body: draw from tail to head, half-way circles/lines
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// soft glow pass (subtle teal aura)
for (let i = n - 1; i > 0; i--) {
const x0 = (pts[i].x + 0.5) * cell, y0 = (pts[i].y + 0.5) * cell;
const x1 = (pts[i - 1].x + 0.5) * cell, y1 = (pts[i - 1].y + 0.5) * cell;
ctx.strokeStyle = 'rgba(52, 211, 153, 0.13)';
ctx.lineWidth = (radii[i] + radii[i - 1]) + cell * 0.55;
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
ctx.stroke();
}
// outline pass (darker, slightly wider)
for (let i = n - 1; i > 0; i--) {
const x0 = (pts[i].x + 0.5) * cell, y0 = (pts[i].y + 0.5) * cell;
const x1 = (pts[i - 1].x + 0.5) * cell, y1 = (pts[i - 1].y + 0.5) * cell;
ctx.strokeStyle = '#0f3d2b';
ctx.lineWidth = (radii[i] + radii[i - 1]) + cell * 0.14;
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
ctx.stroke();
}
// body pass
for (let i = n - 1; i > 0; i--) {
const x0 = (pts[i].x + 0.5) * cell, y0 = (pts[i].y + 0.5) * cell;
const x1 = (pts[i - 1].x + 0.5) * cell, y1 = (pts[i - 1].y + 0.5) * cell;
const t = n <= 1 ? 0 : i / (n - 1);
const w = (radii[i] + radii[i - 1]);
ctx.strokeStyle = mixColor('#34d399', '#0ea56f', t * 0.75);
ctx.lineWidth = w;
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
ctx.stroke();
}
// joint shading dots for a glossy segmented look
for (let i = 1; i < n; i++) {
const t = n <= 1 ? 0 : i / (n - 1);
const w = radii[i] * 0.72;
ctx.fillStyle = mixColor('#6ee7b7', '#10b981', t * 0.8);
ctx.beginPath();
ctx.arc((pts[i].x + 0.5) * cell, (pts[i].y + 0.5) * cell, w, 0, Math.PI * 2);
ctx.fill();
}
// ---- head ----
const angle = Math.atan2(d.y, d.x);
const hx = headCx + Math.cos(angle) * lean;
const hy = headCy + Math.sin(angle) * lean;
const hr = cell * 0.58;
ctx.save();
ctx.translate(hx, hy);
ctx.rotate(angle);
// head base: elongated ellipse leaning into direction
const headGrad = ctx.createRadialGradient(-hr * 0.25, -hr * 0.2, hr * 0.15, 0, 0, hr * 1.25);
headGrad.addColorStop(0, '#a7f3d0');
headGrad.addColorStop(0.55, '#34d399');
headGrad.addColorStop(1, '#15803d');
ctx.fillStyle = headGrad;
ctx.beginPath();
ctx.ellipse(0, 0, hr * 1.24, hr * 0.98, 0, 0, Math.PI * 2);
ctx.fill();
// rim light: brighter crescent toward the leading edge
ctx.strokeStyle = 'rgba(167, 243, 208, 0.85)';
ctx.lineWidth = Math.max(1.2, hr * 0.10);
ctx.beginPath();
ctx.ellipse(hr * 0.10, 0, hr * 0.82, hr * 0.66, 0, -0.55 * Math.PI, 0.55 * Math.PI);
ctx.stroke();
ctx.strokeStyle = '#0f3d2b';
ctx.lineWidth = Math.max(1.5, cell * 0.09);
ctx.stroke();
// eyes — placed forward, pupils shift toward travel direction
const eyeOff = hr * 0.46;
const eyeFwd = hr * 0.34;
for (const s of [-1, 1]) {
const ex = eyeFwd, ey = s * eyeOff;
// white
ctx.fillStyle = '#f8fafc';
ctx.beginPath();
ctx.arc(ex, ey, hr * 0.30, 0, Math.PI * 2);
ctx.fill();
// pupil, looking toward travel direction
ctx.fillStyle = '#0b1220';
ctx.beginPath();
ctx.arc(ex + hr * 0.12, ey, hr * 0.15, 0, Math.PI * 2);
ctx.fill();
// glint
ctx.fillStyle = '#ffffff';
ctx.beginPath();
ctx.arc(ex + hr * 0.08, ey - hr * 0.06, hr * 0.05, 0, Math.PI * 2);
ctx.fill();
}
ctx.restore();
}
// little color helper — parse hex → rgb, lerp (hex string in/out)
function hexToRgb(hex) {
const h = hex.replace('#', '');
return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
}
function mixColor(a, b, t) {
const A = hexToRgb(a), B = hexToRgb(b);
const r = Math.round(lerp(A[0], B[0], t));
const g = Math.round(lerp(A[1], B[1], t));
const bl = Math.round(lerp(A[2], B[2], t));
return `rgb(${r},${g},${bl})`;
}
function drawRings() {
for (const r of rings) {
const prog = 1 - r.life;
ctx.globalAlpha = Math.max(0, r.life) * 1.0;
ctx.strokeStyle = '#fecdd3';
ctx.lineWidth = Math.max(1.6, cell * 0.13 * r.life);
ctx.beginPath();
ctx.arc(r.x * cell, r.y * cell, prog * cell * 2.1 + cell * 0.3, 0, Math.PI * 2);
ctx.stroke();
}
ctx.globalAlpha = 1;
}
function drawParticles() {
for (const p of particles) {
ctx.globalAlpha = Math.max(0, p.life);
ctx.fillStyle = p.color;
ctx.beginPath();
ctx.arc(p.x * cell, p.y * cell, p.size, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = 1;
}
function drawPops() {
for (const p of pops) {
ctx.globalAlpha = Math.max(0, Math.min(1, p.life * 1.4));
ctx.font = `700 ${Math.round(cell * 0.62)}px ui-monospace, Menlo, monospace`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.lineWidth = 4;
ctx.strokeStyle = 'rgba(6,10,14,0.8)';
const x = p.x * cell, y = p.y * cell;
ctx.strokeText(p.text, x, y);
ctx.fillStyle = '#fde68a';
ctx.fillText(p.text, x, y);
}
ctx.globalAlpha = 1;
}
function drawFlash() {
if (flash <= 0) return;
ctx.fillStyle = `rgba(248, 113, 113, ${flash * 0.38})`;
ctx.fillRect(0, 0, viewSize, viewSize);
}
function render(dt) {
// shake decay
shake = Math.max(0, shake - dt * 42);
flash = Math.max(0, flash - dt * 2.2);
ctx.save();
if (shake > 0.1) {
ctx.translate((Math.random() - 0.5) * shake, (Math.random() - 0.5) * shake);
}
drawGrid();
// interpolation factor: how far we are toward the next tick
const elapsed = performance.now() - lastTick;
const f = clamp(elapsed / tickInterval, 0, 1);
drawFood();
drawSnake(f);
drawRings();
drawParticles();
drawPops();
drawFlash();
ctx.restore();
}
// ---------- main loop ----------
let lastFrame = performance.now();
function frame(now) {
const dt = Math.min(0.05, (now - lastFrame) / 1000);
lastFrame = now;
time += dt;
if (state === 'playing') {
// fixed-tick accumulator; cap catch-up so a long tab freeze can't spiral
let elapsed = now - lastTick;
let guard = 0;
while (elapsed >= tickInterval && guard < 6) {
elapsed -= tickInterval;
lastTick += tickInterval;
step();
guard++;
if (state !== 'playing') break; // died mid-loop
}
if (state === 'playing') lastTick = now - elapsed;
// flash light tick marking a new speed level is handled via levelUpBeat
}
if (state !== 'paused') stepParticles(dt);
render(dt);
requestAnimationFrame(frame);
}
// hash-guarded debug hook for automated testing (no effect on normal play)
if (location.hash === '#debug') {
window.__SNAKE__ = () => ({
state, score, eats, level, best,
head: { ...snake[0] },
food: { ...food },
snakeLen: snake.length,
tickInterval,
dir,
body: snake.slice(1).map(p => ({ x: p.x, y: p.y })),
});
}
// ---------- boot ----------
hideOverlay();
showOverlay(`
<h1>SNAKE</h1>
<div class="sub">Eat the rose. Don't bite yourself.</div>
<div class="keys">Press any arrow / WASD to start</div>
`);
state = 'menu';
resize();
snake = [ { x: 12, y: 12 }, { x: 11, y: 12 }, { x: 10, y: 12 } ];
prevSnake = snake.map(p => ({ ...p }));
placeFood();
updateHud();
requestAnimationFrame(frame);
})();
</script>
</body>
</html>Same prompt, other models
One email when a new model lands on the board or in the showcase. Unsubscribe anytime.