From 6f68631cb0918733aa5b92386f231d5888398be1 Mon Sep 17 00:00:00 2001 From: Max Wilson Date: Sun, 3 Mar 2024 18:35:58 -0800 Subject: [PATCH] Write a very minimal game for guessing numbers --- scratch/GuessNumber.fsx | 29 +++++++++++++++++++++++------ scratch/SketchUI.fsx | 5 ++++- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/scratch/GuessNumber.fsx b/scratch/GuessNumber.fsx index 23d0674..2da6b4f 100644 --- a/scratch/GuessNumber.fsx +++ b/scratch/GuessNumber.fsx @@ -1,10 +1,27 @@ #load "SketchUI.fsx" open SketchUI - -let init = () -let update msg model = model +let r = System.Random() +type Model = { + truth: int + guesses: string list + wins: int + } + with static member fresh() = { truth = r.Next(1, 10); guesses = []; wins = 0 } +let init _ = Model.fresh() +let update msg model = + match msg with + | n when model.truth = n -> + let model = { Model.fresh() with wins = model.wins + 1 } + printfn "You guessed it! {n} is correct. You've now won %d times!" model.wins + model + | n -> + let feedback = if n < model.truth then $"{n}: Higher!" else $"{n}: Lower!" + { model with guesses = model.guesses @ [feedback] } let view model = - "Hello, world! Notice that there's no dispatch argument" -let send: unit -> unit = connect init update view + $"You've won {model.wins} times. What you know about this next number: {model.guesses}" +let send = connect init update view -send() \ No newline at end of file +send 10 +send 5 +send 3 +send 4 \ No newline at end of file diff --git a/scratch/SketchUI.fsx b/scratch/SketchUI.fsx index cfebd76..3e3d6e1 100644 --- a/scratch/SketchUI.fsx +++ b/scratch/SketchUI.fsx @@ -3,5 +3,8 @@ #endif let connect init update view = - let dispatch = notImpl + let mutable current = init() + let dispatch msg = + current <- update msg current + printfn "\n%s" (view current) dispatch