Files

26 lines
897 B
FSharp

/// m04 spawn: placing apples with the Random from Random.fs.
module Snake.Spawn
open Snake.Model
let freeCells (state: GameState) : Point list =
[ for y in Util.range state.Height do
for x in Util.range state.Width do
let p = { X = x; Y = y }
if not (Util.contains state.Snake p (=)) then
yield p ]
let spawnApple (state: GameState) : GameState =
if state.Apple.IsSome || state.Status <> Playing then
state
else
match freeCells state with
| [] -> { state with Status = Won }
| cells ->
let i, seed = Random.run state.Seed (Random.intBelow (List.length cells))
{ state with Apple = Some(List.item i cells); Seed = seed }
let tick (state: GameState) : GameState = spawnApple (Rules.advance state)
let newGame (seed: uint32) : GameState = spawnApple (initialState seed)