Skip to content

Instantly share code, notes, and snippets.

@jaymody
Created November 23, 2021 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaymody/df215d6bf24b55a8aee7bf815aaeb3e4 to your computer and use it in GitHub Desktop.
Save jaymody/df215d6bf24b55a8aee7bf815aaeb3e4 to your computer and use it in GitHub Desktop.
Simple CLI coin flip game in functional Scala.
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