feat(js): m04 random and spawn with fixtures and tests
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
2e39f23bb3
commit
08b462d5cc
@@ -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)
|
||||
@@ -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))
|
||||
@@ -0,0 +1,30 @@
|
||||
import { todo } from './todo.js'
|
||||
|
||||
/**
|
||||
* A `Random<A>` is a plain function from a seed to a pair: `seed => [value, nextSeed]`.
|
||||
* Seeds and values are unsigned 32-bit integers. Nothing is hidden or mutated: the caller carries the seed.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The generator (mulberry32). With `s = (seed + 0x6D2B79F5) mod 2^32`:
|
||||
* t = imul(s ^ (s >>> 15), s | 1)
|
||||
* t = t ^ (t + imul(t ^ (t >>> 7), t | 61))
|
||||
* value = (t ^ (t >>> 14)) >>> 0
|
||||
* Returns `[value, s]`: the new seed is `s`.
|
||||
*/
|
||||
export const nextUint32 = (seed) => todo('m04')
|
||||
|
||||
/** A Random that always gives `a` and leaves the seed untouched. */
|
||||
export const pure = (a) => todo('m04')
|
||||
|
||||
/** Transform the value a Random produces; the seed threading is unchanged. */
|
||||
export const map = (r, f) => todo('m04')
|
||||
|
||||
/** Run `r`, feed its value to `f` to pick the next Random, and run that with the seed `r` left behind. */
|
||||
export const flatMap = (r, f) => todo('m04')
|
||||
|
||||
/** A Random giving a number in `[0, n)`: `nextUint32` value modulo `n`. */
|
||||
export const intBelow = (n) => todo('m04')
|
||||
|
||||
/** Run a Random from a seed: `[value, nextSeed]`. */
|
||||
export const run = (r, seed) => todo('m04')
|
||||
@@ -0,0 +1,17 @@
|
||||
import { todo } from './todo.js'
|
||||
|
||||
/** Every board cell not covered by the snake, row-major (y outer loop, x inner loop). The apple does not count as occupied. */
|
||||
export const freeCells = (state) => todo('m04')
|
||||
|
||||
/**
|
||||
* Put an apple on a random free cell, drawing from `state.seed` (use `intBelow` and store the new seed).
|
||||
* Unchanged if there already is an apple or the status is not 'Playing'.
|
||||
* If no cell is free the board is full: status becomes 'Won' (seed unchanged, no apple).
|
||||
*/
|
||||
export const spawnApple = (state) => todo('m04')
|
||||
|
||||
/** One game step: `advance`, then make sure there is an apple. */
|
||||
export const tick = (state) => todo('m04')
|
||||
|
||||
/** A fresh game (`initialState`) with its first apple already placed. */
|
||||
export const newGame = (seed) => todo('m04')
|
||||
@@ -0,0 +1,52 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { nextUint32, pure, map, flatMap, intBelow, run } from '../src/random.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-random', (seed) => run(nextUint32, seed))
|
||||
fixtureTests('m04-int-below', (n, seed) => run(intBelow(n), seed))
|
||||
|
||||
test('m04 the recorded steps chain: each step starts from the previous step\'s seed', () => {
|
||||
const cases = loadFixture('m04-random').cases
|
||||
cases.forEach((c, i) => {
|
||||
if (!c.name.endsWith('-step-1')) assert.equal(c.args[0], cases[i - 1].expected[1])
|
||||
})
|
||||
})
|
||||
|
||||
test('m04 pure returns its value and leaves the seed alone', () =>
|
||||
assert.deepStrictEqual(run(pure('x'), 99), ['x', 99]))
|
||||
|
||||
test('m04 map applies f to the value and keeps the seed from the underlying step', () => {
|
||||
const [v, s] = run(nextUint32, 5)
|
||||
assert.deepStrictEqual(run(map(nextUint32, (x) => x + 1), 5), [v + 1, s])
|
||||
})
|
||||
|
||||
test('m04 map with the identity function changes nothing', () =>
|
||||
assert.deepStrictEqual(run(map(nextUint32, (x) => x), 5), run(nextUint32, 5)))
|
||||
|
||||
test('m04 flatMap threads the seed through both steps', () => {
|
||||
const [a, s1] = run(nextUint32, 5)
|
||||
const [b, s2] = run(nextUint32, s1)
|
||||
assert.deepStrictEqual(run(flatMap(nextUint32, (x) => map(nextUint32, (y) => [x, y])), 5), [[a, b], s2])
|
||||
})
|
||||
|
||||
test('m04 flatMap with pure on the left or right changes nothing', () => {
|
||||
assert.deepStrictEqual(run(flatMap(pure(3), (x) => map(nextUint32, (v) => v + x)), 5), run(map(nextUint32, (v) => v + 3), 5))
|
||||
assert.deepStrictEqual(run(flatMap(nextUint32, pure), 5), run(nextUint32, 5))
|
||||
})
|
||||
|
||||
test('m04 intBelow always lands in [0, n)', () => {
|
||||
const draws = (n, seed, count) =>
|
||||
count === 0 ? [] : ((([v, s]) => [v, ...draws(n, s, count - 1)])(run(intBelow(n), seed)))
|
||||
;[1, 2, 7, 400].forEach((n) =>
|
||||
draws(n, 123, 50).forEach((v) => assert.ok(Number.isInteger(v) && v >= 0 && v < n, `${v} not in [0, ${n})`)))
|
||||
})
|
||||
|
||||
test('m04 running a Random does not mutate anything: same seed, same answer', () =>
|
||||
assert.deepStrictEqual(run(nextUint32, 8), run(nextUint32, 8)))
|
||||
@@ -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)))
|
||||
Reference in New Issue
Block a user