Created
November 23, 2021 21:30
-
-
Save jaymody/df215d6bf24b55a8aee7bf815aaeb3e4 to your computer and use it in GitHub Desktop.
Simple CLI coin flip game in functional Scala.
This file contains 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
import scala.io.StdIn.readLine | |
import scala.util.Random | |
import scala.annotation.tailrec | |
case class GameState(nFlips: Int, nCorrect: Int) | |
object Coin { | |
def prompt(): Unit = { print("(H) Heads, (T) Tails, (Q) End Game: ") } | |
def update(g: GameState): Unit = { println(s"nFlips = ${g.nFlips}, nCorrect = ${g.nCorrect}\n") } | |
def read(): String = readLine().trim.toUpperCase | |
def flip(): String = { if (Random.nextFloat() < 0.5) "H" else "T" } | |
@tailrec | |
def mainLoop(g: GameState): GameState = { | |
prompt() | |
val input = read() | |
input match { | |
case "Q" => { g } | |
case "H" | "T" => { | |
val newState = GameState(g.nFlips + 1, g.nCorrect + (if (flip() == input) 1 else 0)) | |
update(newState) | |
mainLoop(newState) | |
} | |
case _ => { | |
println("Invalid option, try again\n") | |
mainLoop(g) | |
} | |
} | |
} | |
def main(args: Array[String]): Unit = { | |
val g = mainLoop(GameState(0, 0)) | |
println() | |
println("Final Results:") | |
update(g) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment