import scala.io.StdIn.readLine
object SevenBoomGame {
def containsSeven(num: Int): Boolean =
num.toString.contains('7')
def isBoom(num: Int): Boolean =
num % 7 == 0 || containsSeven(num)
def getUserInput(prompt: String): String =
Option(readLine(prompt)).fold("")(_.trim)
def processTurn(expected: Int, input: String): Boolean = {
val lower = input.toLowerCase
val shouldBoom = isBoom(expected)
if (shouldBoom) {
if (lower != "boom") {
println(s"$input (should be Boom)")
println("YOU LOSE!")
return false
}
} else {
if (lower == "boom") {
println(s"Wrong move! It was $expected")
println("YOU LOSE!")
return false
}
input.toIntOption match {
case Some(value) if value == expected => // OK
case _ =>
println(s"Wrong move! It was $expected")
println("YOU LOSE!")
return false
}
}
true
}
def runGame(): Unit = {
val startInput = getUserInput("Enter a number from which you want to start the game (-1 to exit): ")
val startNum = startInput.toIntOption.getOrElse(-1)
if (startNum == -1) return
var current = startNum
while (true) {
val input = getUserInput("Enter a number (or Boom): ")
if (input == "-1") {
println("Game Over!")
return
}
if (!processTurn(current, input))
return
current += 1
}
}
def main(args: Array[String]): Unit = runGame()
}
/*
run:
Enter a number from which you want to start the game (-1 to exit): 6
Enter a number (or Boom): 6
Enter a number (or Boom): Boom
Enter a number (or Boom): 8
Enter a number (or Boom): 9
Enter a number (or Boom): 10
Enter a number (or Boom): 11
Enter a number (or Boom): 12
Enter a number (or Boom): 13
Enter a number (or Boom): Boom
Enter a number (or Boom): 15
Enter a number (or Boom): 16
Enter a number (or Boom): Boom
Enter a number (or Boom): 18
Enter a number (or Boom): 19
Enter a number (or Boom): 20
Enter a number (or Boom): 21
21 (should be Boom)
YOU LOSE!
*/