Created
July 19, 2019 13:29
-
-
Save axhixh/21bf1fd1c48d0dcccfcac9c293fa86f6 to your computer and use it in GitHub Desktop.
Coin Flip Game from Functional Programming Simplified book
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Game | |
| open System | |
| type GameState = | |
| { numFlips : int | |
| numCorrectGuesses : int } | |
| // using this instead of strings like the book | |
| type FlipResult = | |
| | Head | |
| | Tail | |
| let showPrompt() = | |
| printf "\n(h)eads, (t)ails, or (q)quit: " | |
| let getUserInput() = | |
| let input = Console.ReadLine().Trim().ToUpper() | |
| match input with | |
| | "H" -> Some Head | |
| | "T" -> Some Tail | |
| | _ -> None | |
| let printableFlipResult flip = | |
| match flip with | |
| | Head -> "Heads" | |
| | Tail -> "Tails" | |
| let printGameStateOnly gameState = | |
| printfn "#Flips: %i, #Correct: %i" gameState.numFlips | |
| gameState.numCorrectGuesses | |
| let printGameState printableResult gameState = | |
| printf "Flip was %s. " printableResult | |
| printGameStateOnly gameState | |
| let printGameOver () = | |
| printfn "\n==== GAME OVER ====" | |
| let tossCoin (r : Random) = | |
| match r.Next(2) with | |
| | 0 -> Head | |
| | 1 -> Tail | |
| | _ -> failwith "unexpected random value" | |
| let rec mainLoop state random = | |
| showPrompt () | |
| match getUserInput () with | |
| | None -> | |
| printGameOver () | |
| printGameStateOnly state | |
| | Some guess -> | |
| let tossResult = tossCoin random | |
| let correctGuesses = | |
| match guess, tossResult with | |
| // can also do | x, y when x = y -> | |
| | Head, Head | Tail, Tail -> state.numCorrectGuesses + 1 | |
| | _ -> state.numCorrectGuesses | |
| let newState = | |
| { numFlips = state.numFlips + 1 | |
| numCorrectGuesses = correctGuesses } | |
| printGameState (printableFlipResult tossResult) newState | |
| mainLoop newState random | |
| [<EntryPoint>] | |
| let main argv = | |
| let state = | |
| { numFlips = 0 | |
| numCorrectGuesses = 0 } | |
| mainLoop state (Random()) | |
| 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment