Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:19
Show Gist options
  • Save dacr/b0db29e236027e267dff9930af3a04c2 to your computer and use it in GitHub Desktop.
Save dacr/b0db29e236027e267dff9930af3a04c2 to your computer and use it in GitHub Desktop.
ZIO learning - guess number game / published by https://github.com/dacr/code-examples-manager #f20513ba-84fb-453a-b67c-25701c5fe819/39a1bade2d45f034042a77830b2765b47a8555ad
// summary : ZIO learning - guess number game
// keywords : scala, zio, learning, pure-functional, number-guess
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : f20513ba-84fb-453a-b67c-25701c5fe819
// created-on : 2021-10-30T09:50:44+02:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
//> using dep "dev.zio::zio:2.0.13"
//> using dep "dev.zio::zio-test:2.0.13"
//> using dep "fr.janalyse::zio-worksheet:2.0.13.0"
// ---------------------
import zio.*, zio.worksheet.*
val guessNumberGameLogic = for {
_ <- Console.printLine("Let's play a guess number game")
limit <- System.envOrElse("GAME_LIMIT", "5").mapAttempt(_.toInt)
numberToGuess <- Random.nextIntBounded(limit)
_ <- Console.printLine(s"Your choice( 0<=?<$limit) :")
givenNumber <- Console.readLine.mapAttempt(_.toInt)
result = if (numberToGuess == givenNumber) "YOU WIN" else "YOU LOOSE"
_ <- Console.printLine(result)
_ <- Console.printLine("Play again (yes/no) ? ")
playAgain <- Console.readLine.map(_.trim.toLowerCase)
} yield "no" != playAgain
guessNumberGameLogic.repeatWhileEquals(true).unsafeRun
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment