// 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))