feat(fsharp): m01-m06 util, model, rules, random, spawn, game, view with Expecto tests

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Lucas Winther
2026-10-29 00:49:42 +01:00
co-authored by Claude Opus 5.5
parent 183821737e
commit 9cbefeb2be
27 changed files with 851 additions and 6 deletions
+38
View File
@@ -0,0 +1,38 @@
/// m05 game: one `update` turns every action into a new state; replaying a game is a fold over its actions.
/// m10 adds pause, restart and a frame clock that speeds up as the score grows.
module Snake.Game
open Snake.Model
/// How many frames pass between game steps: 8 at first, one fewer every 3 points, never fewer than 2.
let movesEvery (score: int) : int = max 2 (8 - score / 3)
// One animation frame: count it, and every `movesEvery score`-th frame run a game step.
let private frame (state: GameState) : GameState =
if state.Status <> Playing then
state
else
let counted = { state with Frame = state.Frame + 1 }
if counted.Frame % movesEvery counted.Score = 0 then Spawn.tick counted else counted
// Pause and resume only make sense in those two statuses; a finished game stays finished.
let private togglePause (state: GameState) : GameState =
match state.Status with
| Playing -> { state with Status = Paused }
| Paused -> { state with Status = Playing }
| GameOver
| Won -> state
// Every case is listed (no `| _ ->`): adding an Action later makes the compiler point here.
let update (state: GameState) (action: Action) : GameState =
match action with
| Tick -> Spawn.tick state
| Turn dir -> Rules.turn state dir
| TogglePause -> togglePause state
| Restart -> Spawn.newGame state.Seed
| Frame -> frame state
let replay (state: GameState) (actions: Action list) : GameState = List.fold update state actions
// List.scan is List.fold that keeps every intermediate result (the start state included).
let history (state: GameState) (actions: Action list) : GameState list = List.scan update state actions
+64
View File
@@ -0,0 +1,64 @@
/// m02 model: the data the whole game is built from. Records and unions are immutable.
module Snake.Model
/// A grid cell. Records compare structurally: two points with the same X and Y are `=`.
type Point = { X: int; Y: int }
type Direction =
| Up
| Down
| Left
| Right
type Status =
| Playing
| Paused
| GameOver
| Won
/// Everything that can happen to the game, as data.
type Action =
| Tick
| Turn of Direction
| TogglePause
| Restart
| Frame
/// The whole game. `Snake` is head first; `Seed` is the unsigned 32-bit random seed.
type GameState =
{ Width: int
Height: int
Snake: Point list
Dir: Direction
NextDir: Direction
Apple: Point option
Seed: uint32
Score: int
Status: Status
Frame: int }
let delta (dir: Direction) : Point =
match dir with
| Up -> { X = 0; Y = -1 }
| Down -> { X = 0; Y = 1 }
| Left -> { X = -1; Y = 0 }
| Right -> { X = 1; Y = 0 }
let opposite (dir: Direction) : Direction =
match dir with
| Up -> Down
| Down -> Up
| Left -> Right
| Right -> Left
let initialState (seed: uint32) : GameState =
{ Width = 20
Height = 20
Snake = [ { X = 10; Y = 10 }; { X = 9; Y = 10 }; { X = 8; Y = 10 } ]
Dir = Right
NextDir = Right
Apple = None
Seed = seed
Score = 0
Status = Playing
Frame = 0 }
+31
View File
@@ -0,0 +1,31 @@
/// m04 random: a tiny "state monad" for randomness. A Random<'a> wraps a function seed -> (value, nextSeed),
/// so every draw is a pure function and the seed is passed along explicitly instead of hidden.
/// Seeds and values are unsigned 32-bit numbers (uint32).
module Snake.Random
type Random<'a> = Random of (uint32 -> 'a * uint32)
let run (seed: uint32) (Random f: Random<'a>) : 'a * uint32 = f seed
let pure (a: 'a) : Random<'a> = Random(fun seed -> (a, seed))
let map (f: 'a -> 'b) (r: Random<'a>) : Random<'b> =
Random(fun seed ->
let a, next = run seed r
(f a, next))
let bind (f: 'a -> Random<'b>) (r: Random<'a>) : Random<'b> =
Random(fun seed ->
let a, next = run seed r
run next (f a))
// mulberry32. uint32 arithmetic wraps around at 2^32 (F# operators are unchecked) and `>>>` on uint32 is an
// unsigned shift, so the formula can be written down as it is.
let nextUint32: Random<uint32> =
Random(fun seed ->
let s = seed + 0x6D2B79F5u
let t1 = (s ^^^ (s >>> 15)) * (s ||| 1u)
let t2 = t1 ^^^ (t1 + (t1 ^^^ (t1 >>> 7)) * (t1 ||| 61u))
(t2 ^^^ (t2 >>> 14), s))
let intBelow (n: int) : Random<int> = map (fun v -> int (v % uint32 n)) nextUint32
+34
View File
@@ -0,0 +1,34 @@
/// m03 rules: the pure game rules. Each function takes a state and returns a new one.
module Snake.Rules
open Snake.Model
let move (p: Point) (dir: Direction) : Point =
let d = delta dir
{ X = p.X + d.X; Y = p.Y + d.Y }
let inBounds (state: GameState) (p: Point) : bool =
p.X >= 0 && p.X < state.Width && p.Y >= 0 && p.Y < state.Height
// Validate against `Dir` (last moved), not `NextDir`: Up then Left within one tick must not fold the snake back on itself.
let turn (state: GameState) (dir: Direction) : GameState =
if state.Status = Playing && dir <> opposite state.Dir then { state with NextDir = dir } else state
let advance (state: GameState) : GameState =
if state.Status <> Playing then
state
else
let d = state.NextDir
let head = move (List.head state.Snake) d
let eating = state.Apple = Some head
// When not eating, the tail leaves its cell this step, so the head may move into it.
let body = if eating then state.Snake else Util.dropLast state.Snake
if not (inBounds state head) || Util.contains body head (=) then
{ state with Dir = d; Status = GameOver }
else
{ state with
Snake = head :: body
Dir = d
Apple = if eating then None else state.Apple
Score = state.Score + (if eating then 1 else 0) }
+8
View File
@@ -1,9 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<!-- FS0046: `pure` is reserved for future use by F#; the course keeps the name used by every track. -->
<NoWarn>$(NoWarn);FS0046</NoWarn>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<Compile Include="Util.fs" />
<Compile Include="Model.fs" />
<Compile Include="Rules.fs" />
<Compile Include="Random.fs" />
<Compile Include="Spawn.fs" />
<Compile Include="Game.fs" />
<Compile Include="View.fs" />
</ItemGroup>
</Project>
+25
View File
@@ -0,0 +1,25 @@
/// 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)
+11 -1
View File
@@ -1,2 +1,12 @@
/// Placeholder; replaced by the m01 utilities.
/// m01 util: small helpers used by every later module.
/// (The JavaScript track also writes `pipe` and `compose` here; F# has them built in as `|>` and `>>`.)
module Snake.Util
let range (n: int) : int list = [ 0 .. n - 1 ]
let dropLast (xs: 'a list) : 'a list =
match xs with
| [] -> []
| _ -> List.take (List.length xs - 1) xs
let contains (xs: 'a list) (p: 'a) (eq: 'a -> 'a -> bool) : bool = List.exists (fun x -> eq x p) xs
+38
View File
@@ -0,0 +1,38 @@
/// m06 view: the picture is plain data (a list of shapes); drawing it is somebody else's job (m07).
module Snake.View
open Snake.Model
/// A thing to draw.
type Shape =
| Rect of x: int * y: int * w: int * h: int * color: string
| Text of x: int * y: int * text: string * color: string * size: int * align: string
/// A picture: shapes drawn in order.
type Scene = Shape list
let CELL = 20
let private text x y str size align = Text(x, y, str, "#ffffff", size, align)
// One cell, inset by 1px so neighbouring segments show a gap.
let private cell (p: Point) color =
Rect(p.X * CELL + 1, p.Y * CELL + 1, CELL - 2, CELL - 2, color)
let private overlay (state: GameState) : Scene =
let cx = state.Width * CELL / 2
let cy = state.Height * CELL / 2
let banner title hint = [ text cx cy title 32 "center"; text cx (cy + 30) hint 16 "center" ]
match state.Status with
| Paused -> banner "Paused" "Press Space to resume"
| GameOver -> banner "Game Over" "Press R to restart"
| Won -> banner "You Win!" "Press R to restart"
| Playing -> []
let view (state: GameState) : Scene =
[ Rect(0, 0, state.Width * CELL, state.Height * CELL, "#111111") ]
@ (state.Apple |> Option.map (fun a -> cell a "#e53935") |> Option.toList)
@ (state.Snake |> List.mapi (fun i p -> cell p (if i = 0 then "#7cb342" else "#43a047")))
@ [ text 6 18 $"Score: {state.Score}" 16 "left" ]
@ overlay state