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
+31
View File
@@ -0,0 +1,31 @@
// m04 random: a tiny "state monad" for randomness. A Random<A> is a function seed -> [A, nextSeed],
// so every draw is a pure function and the seed is passed along explicitly instead of hidden.
/** mulberry32: a small, fast generator. `imul` is 32-bit integer multiplication (plain `*` would lose bits). */
export const nextUint32 = (seed) => {
const s = (seed + 0x6D2B79F5) >>> 0 // `>>> 0` keeps numbers unsigned 32-bit
const t1 = Math.imul(s ^ (s >>> 15), s | 1)
const t2 = t1 ^ (t1 + Math.imul(t1 ^ (t1 >>> 7), t1 | 61))
return [(t2 ^ (t2 >>> 14)) >>> 0, s]
}
/** A Random that always gives `a` and leaves the seed untouched. */
export const pure = (a) => (seed) => [a, seed]
/** Transform the value a Random produces; the seed threading is unchanged. */
export const map = (r, f) => (seed) => {
const [a, next] = r(seed)
return [f(a), next]
}
/** Run `r`, let `f` pick the next Random from its value, and run that with the seed `r` left behind. */
export const flatMap = (r, f) => (seed) => {
const [a, next] = r(seed)
return f(a)(next)
}
/** A Random giving a number in `[0, n)`. */
export const intBelow = (n) => map(nextUint32, (v) => v % n)
/** Run a Random from a seed: `[value, nextSeed]`. */
export const run = (r, seed) => r(seed)
+26
View File
@@ -0,0 +1,26 @@
// m04 spawn: placing apples with the Random from random.js.
import { range, contains } from './util.js'
import { point, pointEquals, initialState } from './model.js'
import { advance } from './rules.js'
import { intBelow, run } from './random.js'
/** Every board cell not covered by the snake, row-major (y outer, x inner). */
export const freeCells = (state) =>
range(state.height)
.flatMap((y) => range(state.width).map((x) => point(x, y)))
.filter((p) => !contains(state.snake, p, pointEquals))
/** Put an apple on a random free cell; a full board means the player has won. */
export const spawnApple = (state) => {
if (state.apple !== null || state.status !== 'Playing') return state
const cells = freeCells(state)
if (cells.length === 0) return { ...state, status: 'Won' }
const [i, seed] = run(intBelow(cells.length), state.seed)
return { ...state, apple: cells[i], seed }
}
/** One game step: move the snake, then make sure there is an apple. */
export const tick = (state) => spawnApple(advance(state))
/** A fresh game with its first apple already placed. */
export const newGame = (seed) => spawnApple(initialState(seed))