[verified] Snake 0.7: queued controls, records, pause and wrap mode

This commit is contained in:
2026-09-12 12:23:09 +01:00
parent eacad97240
commit 5a7081b933
10 changed files with 548 additions and 109 deletions
+22 -13
View File
@@ -8,11 +8,14 @@ function initialSnake() {
}
// Advance the snake one cell in `dir` ({x,y} unit vector). Returns { snake, ate, alive }.
function step(snake, dir, food, N) {
function step(snake, dir, food, N, mode) {
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) {
let nx = head.x + dir.x
let ny = head.y + dir.y
if (mode === 'wrap') {
nx = (nx + N) % N
ny = (ny + N) % N
} else if (nx < 0 || ny < 0 || nx >= N || ny >= N) {
return { snake, ate: false, alive: false }
}
const ate = (nx === food.x && ny === food.y)
@@ -37,16 +40,17 @@ function turn(current, desired) {
// Classify every segment as a texture piece (head/body/corner/tail + compass side),
// so the page can render each cell with the right PNG. Returns one name per segment.
// Sides are screen compass (y grows down): e/w/n/s = right/left/up/down.
function renderPieces(snakeCells, dir) {
function renderPieces(snakeCells, dir, N) {
const D = { '1,0': 'e', '-1,0': 'w', '0,-1': 'n', '0,1': 's' }
const opp = { e: 'w', w: 'e', n: 's', s: 'n' }
const delta = d => N && d === N - 1 ? -1 : N && d === 1 - N ? 1 : d
return snakeCells.map((s, i) => {
if (i === 0) return 'head_' + D[dir.x + ',' + dir.y]
const prev = snakeCells[i - 1]
const next = snakeCells[i + 1]
const from = D[(prev.x - s.x) + ',' + (prev.y - s.y)] // side toward head
const from = D[delta(prev.x - s.x) + ',' + delta(prev.y - s.y)] // side toward head
if (!next) return 'tail_' + opp[from] // tip points away from body
const to = D[(next.x - s.x) + ',' + (next.y - s.y)] // side toward tail tip
const to = D[delta(next.x - s.x) + ',' + delta(next.y - s.y)] // side toward tail tip
if ((from === 'e' || from === 'w') && (to === 'e' || to === 'w')) return 'body_h'
if ((from === 'n' || from === 's') && (to === 'n' || to === 's')) return 'body_v'
// corner: name = the two sides it connects; pairs are alphabetically sorted
@@ -72,12 +76,17 @@ function rotateDir(dir, clockwise) {
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 }
// Select an empty-cell rank uniformly; at most N*N checks, even almost full.
let rank = Math.floor(Math.random() * (N * N - occupied.size))
for (let y = 0; y < N; y++) {
for (let x = 0; x < N; x++) {
if (!occupied.has(x + ',' + y)) {
if (rank === 0) return { x, y }
rank--
}
}
}
return null
}
module.exports = { initialSnake, step, turn, renderPieces, rotateDir, spawnFood }