feat(js): m04 random and spawn with fixtures and tests

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
Lucas Winther
2026-10-28 23:42:36 +01:00
co-authored by Claude Sonnet 5.5
parent 2e39f23bb3
commit 08b462d5cc
11 changed files with 1332 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { freeCells, spawnApple, tick, newGame } from '../src/spawn.js'
import { advance } from '../src/rules.js'
import { loadFixture, freeze } from './helpers.js'
const fixtureTests = (name, f) => {
const fx = loadFixture(name)
fx.cases.forEach((c) =>
test(`m04 ${fx.function}: ${c.name}`, () => assert.deepStrictEqual(f(...freeze(c.args)), c.expected)))
}
fixtureTests('m04-free-cells', freeCells)
fixtureTests('m04-spawn', spawnApple)
fixtureTests('m04-new-game', newGame)
// 3x2 board, one-cell snake, about to eat the apple at (1,0)
const eating = freeze({
width: 3, height: 2, snake: [{ x: 0, y: 0 }], dir: 'Right', nextDir: 'Right',
apple: { x: 1, y: 0 }, seed: 0, score: 0, status: 'Playing', frame: 0,
})
test('m04 tick: eating the apple spawns a new one in the same step', () => {
// snake becomes [(1,0),(0,0)]; free cells are (2,0),(0,1),(1,1),(2,1); seed 0 draws 1144304738 % 4 = 2 -> (1,1)
assert.deepStrictEqual(tick(eating), {
...eating, snake: [{ x: 1, y: 0 }, { x: 0, y: 0 }], apple: { x: 1, y: 1 }, score: 1, seed: 1831565813,
})
})
test('m04 tick is spawnApple after advance', () => assert.deepStrictEqual(tick(eating), spawnApple(advance(eating))))
test('m04 tick leaves the seed alone when no apple needs spawning', () => {
const s = freeze({ ...eating, apple: { x: 2, y: 1 } })
assert.equal(tick(s).seed, 0)
})
test('m04 newGame is reproducible: same seed, same game', () => assert.deepStrictEqual(newGame(42), newGame(42)))