Exemplos
Mão na massa. Tudo ao vivo.
Escolha um exemplo para abrir em tela inteira, com a visualização ao vivo e o código lado a lado.
Escolha um exemplo para abrir em tela inteira, com a visualização ao vivo e o código lado a lado.
O game loop é um timer que chama step() em objetos simples e depois update() uma vez por tick. A cobra é um list() dos seus objetos de célula, e a cada tick o objeto da cauda vira a nova cabeça: um elemento se move e nenhum é criado. O contador de segmentos construídos só sobe quando a cobra come. A comida surge com uma animação keyframes().
Press an arrow key or Space
WASD works too. On a touch screen, swipe or use the pad.
// app.ts: the game. The loop is a setTimeout: each tick calls step() on the // plain game object, then update() once. The snake is a list() of its cell // objects, and step() makes the tail object the new head, so a tick moves one // existing element to the front and builds nothing. "Segments built" counts // mounts to prove it: it only goes up when the snake eats. import "nuclo"; import { interval, level, newGame, step, turn, type Cell, type Dir } from "./game.ts"; import { s } from "./styles.ts"; let game = newGame(); let state: "ready" | "playing" | "paused" | "over" = "ready"; let best = 0; let built = 0; // segment elements built, counted by their mount let timer: ReturnType<typeof setTimeout> | undefined; let swipe = { x: 0, y: 0 }; // where the last press on the board started function tick() { if (step(game)) timer = setTimeout(tick, interval(game)); else state = "over"; best = Math.max(best, game.score); update(); } function play() { state = "playing"; clearTimeout(timer); timer = setTimeout(tick, interval(game)); update(); } function pause() { clearTimeout(timer); state = "paused"; update(); } function restart() { game = newGame(); // new cell objects: the list builds three new segments built = 0; play(); } // Space, P and the middle of the pad. const toggle = () => (state === "playing" ? pause() : state === "over" ? restart() : play()); function steer(dir: Dir) { if (state === "over") return; turn(game, dir); if (state !== "playing") play(); } const KEYS: Record<string, Dir> = { arrowup: "up", w: "up", arrowdown: "down", s: "down", arrowleft: "left", a: "left", arrowright: "right", d: "right" }; const ARROWS: Record<Dir, string> = { up: "↑", left: "←", right: "→", down: "↓" }; const ANGLE: Record<Dir, string> = { right: "0deg", down: "90deg", left: "180deg", up: "-90deg" }; function onKeyDown(e: KeyboardEvent) { if (e.ctrlKey || e.metaKey || e.altKey) return; const key = e.key.toLowerCase(); if (KEYS[key]) steer(KEYS[key]); else if (key === " " || key === "p") toggle(); else return; // Escape and the rest go on to the modal e.preventDefault(); // the modal steps examples on arrow keys, unless the event was handled } function Segment(cell: Cell) { const isHead = () => cell === game.snake[0]; return div( s.segment, { class: () => cx(s.segment, isHead() ? s.head : null).className }, // The position goes in `translate` and the heading in `rotate`, which // leaves `transform` free for the head's slide in from the neck. { style: () => ({ translate: `${cell.x * 100}% ${cell.y * 100}%`, rotate: isHead() ? ANGLE[game.dir] : "", animationDuration: `${interval(game)}ms` }) }, on("mount", () => { built++; queueMicrotask(update); }), span(s.eye), span(s.eye), ); } const Food = (food: Cell) => div(s.food, { style: { translate: `${food.x * 100}% ${food.y * 100}%` } }); const Overlay = (title: string, ...content: NodeModLike<"div">[]) => div(s.overlay, strong(title), ...content); function Board() { return div( s.board, { tabIndex: 0, role: "application", "aria-label": "Snake: arrow keys or WASD steer, Space pauses" }, on("mount", (el) => { el.focus({ preventScroll: true }); // Leaving the example stops the loop. The game waits, paused, for the next visit. return () => { clearTimeout(timer); if (state === "playing") state = "paused"; built = 0; }; }), { onKeyDown, onBlur: () => { if (state === "playing") pause(); }, // Also runs after "Play again", whose button is gone by then: the focus comes back here. onClick: (e) => { e.currentTarget.focus(); if (state === "ready" || state === "paused") play(); }, onPointerDown: (e) => { swipe = { x: e.clientX, y: e.clientY }; }, onPointerMove: (e) => { if (e.pointerType !== "touch") return; // a mouse steers with the keyboard const dx = e.clientX - swipe.x; const dy = e.clientY - swipe.y; if (Math.hypot(dx, dy) < 24) return; steer(Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? "right" : "left") : dy > 0 ? "down" : "up"); swipe = { x: e.clientX, y: e.clientY }; // keep swiping to keep turning }, }, // A new food object is a new item: its element is built, and pops in. list(() => [game.food], Food), list(() => game.snake, Segment), when(() => state === "ready", Overlay("Snake", p("Press an arrow key or Space"), p(s.small, "WASD works too. On a touch screen, swipe or use the pad."))) .when(() => state === "paused", Overlay("Paused", p("Click to continue"))) .when(() => state === "over", Overlay("Game over", p(() => `Score ${game.score} · best ${best}`), button(s.again, "Play again", { onClick: restart }))), ); } const keepFocus = (e: MouseEvent) => e.preventDefault(); // a press on the pad leaves the focus on the board const PadButton = (area: string, label: string, glyph: NodeModLike<"button">, press: () => void) => button(s.padBtn, { style: { gridArea: area }, title: label, "aria-label": label, onPointerDown: press, onMouseDown: keepFocus }, glyph); const Stat = (label: string, value: NodeModLike<"dd">) => div(s.stat, dt(label), dd(value)); export function SnakeGame() { return div( s.app, div(s.stage, Board()), aside( s.panel, dl( s.stats, // A new score is a new item too, so its element is built again and the flash replays. Stat("Score", list(() => [game.score], (n) => span(n > 0 ? s.flash : null, String(n)))), Stat("Best", () => String(best)), Stat("Length", () => String(game.snake.length)), Stat("Segments built", () => String(built)), Stat("Speed", () => String(level(game))), ), p(s.note, "Each tick the tail element becomes the head: one element moves, none is built. ", strong("Segments built"), " only goes up when the snake eats."), ), div( s.pad, ...(Object.keys(ARROWS) as Dir[]).map((dir) => PadButton(dir, `Turn ${dir}`, ARROWS[dir], () => steer(dir))), PadButton("mid", "Pause or play", () => (state === "playing" ? "❚❚" : "►"), toggle), ), ); }
// game.ts: the rules, with no DOM. A snake is an array of { x, y } cells, head // first. step() moves it one cell by turning the tail object into the new // head: the same objects, in a new order. Only eating adds an object. export const GRID = 20; // cells per side const PER_LEVEL = 5; // foods per speed level export type Dir = "up" | "down" | "left" | "right"; export interface Cell { x: number; y: number; } export interface Game { snake: Cell[]; // head first food: Cell; dir: Dir; turns: Dir[]; // pressed but not taken yet: one per step score: number; } const DELTA: Record<Dir, Cell> = { up: { x: 0, y: -1 }, down: { x: 0, y: 1 }, left: { x: -1, y: 0 }, right: { x: 1, y: 0 } }; const OPPOSITE: Record<Dir, Dir> = { up: "down", down: "up", left: "right", right: "left" }; // Always the same start: the server and the browser render the same board. export const newGame = (): Game => ({ snake: [{ x: 6, y: 10 }, { x: 5, y: 10 }, { x: 4, y: 10 }], food: { x: 14, y: 10 }, dir: "right", turns: [], score: 0, }); export const level = (g: Game) => 1 + Math.floor(g.score / PER_LEVEL); export const interval = (g: Game) => Math.max(60, 160 - (level(g) - 1) * 15); // ms per step /** * Queues a turn. It is checked against the last queued one, so two quick * presses within one step both count, and a turn back into the neck is refused. */ export function turn(g: Game, dir: Dir) { const last = g.turns.at(-1) ?? g.dir; if (dir !== last && dir !== OPPOSITE[last] && g.turns.length < 3) g.turns.push(dir); } /** Moves one cell. Returns false when the game is over: a wall, the snake itself, or a full board. */ export function step(g: Game) { g.dir = g.turns.shift() ?? g.dir; const x = g.snake[0].x + DELTA[g.dir].x; const y = g.snake[0].y + DELTA[g.dir].y; const eats = x === g.food.x && y === g.food.y; const body = eats ? g.snake : g.snake.slice(0, -1); // the tail leaves its cell this step, unless the snake grows if (x < 0 || y < 0 || x >= GRID || y >= GRID || body.some((c) => c.x === x && c.y === y)) return false; if (eats) { g.snake.unshift({ x, y }); // the only new object g.score++; return placeFood(g); } const tail = g.snake.pop()!; tail.x = x; tail.y = y; g.snake.unshift(tail); // the tail object is the new head return true; } // Food goes on a random free cell. There is none left only when the snake fills the board. function placeFood(g: Game) { const taken = new Set(g.snake.map((c) => c.y * GRID + c.x)); const free = Array.from({ length: GRID * GRID }, (_, i) => i).filter((i) => !taken.has(i)); if (free.length === 0) return false; const i = free[Math.floor(Math.random() * free.length)]; g.food = { x: i % GRID, y: Math.floor(i / GRID) }; return true; }
// styles.ts: the look. Cells are sized in % of the board, so the board can // take any size: it is the largest square its stage can hold. import "nuclo"; import { GRID } from "./game.ts"; const mono = "ui-monospace, monospace"; const cell = `${100 / GRID}%`; const control = { height: "34px", padding: "0 12px", borderRadius: "8px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg)", color: "var(--c-text)", fontFamily: "inherit", fontSize: "0.875rem", fontWeight: "600" }; const slide = keyframes({ from: { transform: "translateX(-100%)" } }); // from the neck, in the head's rotated frame const pop = keyframes({ from: { transform: "scale(0)" } }); const flash = keyframes({ from: { color: "var(--c-primary-ink)", transform: "scale(1.4)" } }); export const s = { app: css("snake-app", { display: "grid", gridTemplateColumns: "minmax(0, 1fr)", gridTemplateRows: "auto minmax(240px, 1fr) auto", gridTemplateAreas: '"stats" "stage" "pad"', gap: "12px", width: "100%", height: "100%", "@media (min-width: 760px)": { gridTemplateColumns: "minmax(0, 1fr) 220px", gridTemplateRows: "auto minmax(0, 1fr)", gridTemplateAreas: '"stage stats" "stage pad"' }, }), // A size container: the board is 100cqmin, the smaller of its width and height. stage: css("snake-stage", { gridArea: "stage", display: "flex", alignItems: "center", justifyContent: "center", minHeight: "240px", containerType: "size" }), board: css("snake-board", { position: "relative", width: "100cqmin", height: "100cqmin", borderRadius: "12px", border: "1px solid var(--c-border)", overflow: "hidden", outline: "none", touchAction: "none", userSelect: "none", backgroundColor: "var(--c-bg-secondary)", backgroundImage: "radial-gradient(circle, var(--c-border-light) 1px, transparent 1.5px)", backgroundSize: `${cell} ${cell}`, focusVisible: { boxShadow: "0 0 0 2px var(--c-primary)" }, }), // No transition on the position: the element that moves each tick is the // tail jumping to the front, and it must not glide across the board. segment: css("snake-segment", { position: "absolute", top: "0", left: "0", width: cell, height: cell, borderRadius: "30%", border: "1px solid var(--c-bg-secondary)", backgroundColor: "var(--c-primary)" }), // The slide replays whenever this class lands on a new element. Its duration is one tick, set inline. head: css("snake-head", { zIndex: 1, backgroundColor: "var(--c-primary-dark)", animation: `${slide} linear`, "& > span": { display: "block" } }), eye: css("snake-eye", { display: "none", position: "absolute", right: "14%", width: "26%", height: "26%", borderRadius: "50%", backgroundImage: "radial-gradient(circle at 70% 50%, #111 38%, #fff 42%)", first: { top: "16%" }, last: { bottom: "16%" } }), food: css("snake-food", { position: "absolute", top: "0", left: "0", width: cell, height: cell, backgroundImage: "radial-gradient(circle closest-side, var(--c-accent-cool) 70%, transparent 76%)", animation: `${pop} 0.35s cubic-bezier(0.34, 1.56, 0.64, 1)` }), overlay: css("snake-overlay", { position: "absolute", inset: "0", zIndex: 2, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: "6px", padding: "16px", textAlign: "center", backgroundColor: "color-mix(in srgb, var(--c-bg) 88%, transparent)", backdropFilter: "blur(3px)", "& strong": { fontSize: "1.25rem" }, "& p": { fontSize: "0.875rem", color: "var(--c-text-dim)" }, }), small: css("snake-small", { fontSize: "0.75rem", color: "var(--c-text-muted)" }), again: css("snake-again", { ...control, marginTop: "8px", backgroundColor: "var(--c-primary-dark)", borderColor: "transparent", color: "#fff", hover: { filter: "brightness(0.92)" } }), panel: css("snake-panel", { gridArea: "stats", display: "flex", flexDirection: "column", gap: "10px", minWidth: "0" }), // Cells grow to fill each row, so five stats never leave one orphaned in a half-empty row. stats: css("snake-stats", { display: "flex", flexWrap: "wrap", gap: "6px", "& > *": { flex: "1 1 88px" } }), stat: css("snake-stat", { padding: "6px 10px", borderRadius: "10px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg-card)", "& dt": { fontSize: "0.6875rem", color: "var(--c-text-muted)" }, "& dd": { margin: "2px 0 0", fontFamily: mono, fontSize: "1rem", fontWeight: "600", fontVariantNumeric: "tabular-nums" }, }), flash: css("snake-flash", { display: "inline-block", animation: `${flash} 0.45s ease-out` }), note: css("snake-note", { fontSize: "0.75rem", lineHeight: "1.5", color: "var(--c-text-dim)", "& strong": { color: "var(--c-primary-ink)" }, "@media (max-width: 759px)": { display: "none" } }), // Touch screens and narrow windows get a pad; the keyboard does not need one. pad: css("snake-pad", { gridArea: "pad", display: "none", gridTemplateColumns: "repeat(3, 48px)", gridTemplateRows: "repeat(3, 48px)", gridTemplateAreas: '". up ." "left mid right" ". down ."', gap: "6px", justifyContent: "center", "@media (pointer: coarse), (max-width: 759px)": { display: "grid" }, }), padBtn: css("snake-padBtn", { ...control, height: "auto", padding: "0", fontSize: "1.125rem", touchAction: "manipulation", hover: { backgroundColor: "var(--c-bg-secondary)" }, active: { backgroundColor: "var(--c-primary-alpha-13)" } }), };