Files
functional-programming-snake/fsharp/solutions/App.fs
T

29 lines
1.3 KiB
FSharp

/// m09 app: the whole game wired together as values: streams of actions in, a stream of drawings out.
module Snake.App
open Snake.Model
open Snake.IO
open Snake.Stream
let TICK_MS = 150L
let FRAME_MS = 25L
// Everything that can happen to the game: a Tick every TICK_MS, and an action for each bound key.
let classicActions: Stream<Action> =
Stream.merge (Stream.interval TICK_MS |> Stream.map (fun _ -> Tick)) (Stream.keyDowns |> Stream.choose Input.keyToAction)
// m10: a Frame every FRAME_MS instead of a Tick; the game itself decides (movesEvery) which frames take a step.
let speedActions: Stream<Action> =
Stream.merge (Stream.interval FRAME_MS |> Stream.map (fun _ -> Frame)) (Stream.keyDowns |> Stream.choose Input.keyToAction)
// Actions folded into game states. startWith puts the initial state first so it is drawn right away.
let states (seed: uint32) (actions: Stream<Action>) : Stream<GameState> =
actions |> Stream.scan Game.update (Spawn.newGame seed) |> Stream.startWith (Spawn.newGame seed)
let render (state: GameState) : IO<unit> = IO.drawScene (View.view state)
// The whole program as a value: get a seed, then turn the stream of states into a stream of drawings.
// Nothing runs here; Runtime interprets it.
let main () : IO<Stream<IO<unit>>> =
IO.randomSeed () |> IO.map (fun seed -> states seed speedActions |> Stream.map render)