SNAKE game v0.3: round screen, swipe control

- 16x16 grid, 320px board centered on round 466 screen, designWidth 466
- pure snake logic in src/common/snake.js (step/turn/rotateDir/spawnFood, TDD'd)
- for-directive segment rendering, show-gated game-over overlay, 300ms tick
- swipe direction input (crown rotation confirmed unsupported on Vela S4)
- tests: snake logic + page wiring
This commit is contained in:
2026-09-09 15:09:23 +01:00
commit e618c02c1b
13 changed files with 10875 additions and 0 deletions
+59
View File
@@ -0,0 +1,59 @@
// Snake core — pure functions, no Vela APIs. Exports: initialSnake, step, turn, spawnFood.
function initialSnake() {
return [
{ x: 6, y: 7 },
{ x: 5, y: 7 },
{ x: 4, y: 7 }
]
}
// Advance the snake one cell in `dir` ({x,y} unit vector). Returns { snake, ate, alive }.
function step(snake, dir, food, N) {
const head = snake[0]
const nx = head.x + dir.x
const ny = head.y + dir.y
if (nx < 0 || ny < 0 || nx >= N || ny >= N) {
return { snake, ate: false, alive: false }
}
const ate = (nx === food.x && ny === food.y)
// tail cell vacates unless we grew, so exclude it from self-collision check
const body = ate ? snake : snake.slice(0, snake.length - 1)
for (let i = 0; i < body.length; i++) {
if (body[i].x === nx && body[i].y === ny) {
return { snake, ate: false, alive: false }
}
}
const next = [{ x: nx, y: ny }].concat(snake)
if (!ate) next.pop()
return { snake: next, ate, alive: true }
}
// Reject a 180° reversal; otherwise accept the new direction.
function turn(current, desired) {
if (current.x + desired.x === 0 && current.y + desired.y === 0) return current
return desired
}
// Rotate a direction 90°: clockwise order right->down->left->up. Always ±90°, never a reversal.
function rotateDir(dir, clockwise) {
const order = [{ x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }, { x: 0, y: -1 }]
let i = 0
for (let k = 0; k < 4; k++) {
if (order[k].x === dir.x && order[k].y === dir.y) { i = k; break }
}
return clockwise ? order[(i + 1) % 4] : order[(i + 3) % 4]
}
// Random empty cell, avoiding the snake.
function spawnFood(snake, N) {
const occupied = new Set(snake.map(s => s.x + ',' + s.y))
if (occupied.size >= N * N) return null
let x, y
do {
x = Math.floor(Math.random() * N)
y = Math.floor(Math.random() * N)
} while (occupied.has(x + ',' + y))
return { x, y }
}
module.exports = { initialSnake, step, turn, rotateDir, spawnFood }