Last active
September 7, 2021 20:28
-
-
Save map0logo/04ca6582cfcd0ebb8893f0ba4af0ae78 to your computer and use it in GitHub Desktop.
[Bagels] #Scala #BigBookPython #qu4nt
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.util.control.Breaks.break | |
import scala.collection.mutable.ListBuffer | |
val NUM_DIGITS = 3 | |
val MAX_GUESSES = 10 | |
@main def main: Unit = { | |
println(s"""Bagels, a deductive logic game. | |
I am thinking of a $NUM_DIGITS-digit number with no repeated digits. | |
Try to guess what it is. Here are some clues: | |
When I say: That means: | |
Pico One digit is correct but in the wrong position. | |
Fermi One digit is correct and in the right position. | |
Bagels No digit is correct. | |
For example, if the secret number was 248 and your guess was 843, the | |
clues would be Fermi Pico.""") | |
while (true) { | |
val secretNum = getSecretNum | |
println("I have thought up a number.") | |
println(s"""You have $MAX_GUESSES guesses to get it.""") | |
var numGuesses = 1 | |
while (numGuesses <= MAX_GUESSES) { | |
var guess = "" | |
while ((guess.length != NUM_DIGITS) || !guess.forall(_.isDigit)) { | |
println(s"Guess #$numGuesses: ") | |
guess = readLine("> ") | |
} | |
var clues = getClues(guess, secretNum) | |
println(clues) | |
numGuesses += 1 | |
if (guess == secretNum) then break | |
if (numGuesses > MAX_GUESSES) { | |
println("You ran out of guesses.") | |
println(s"The answer was $secretNum.") | |
} | |
} | |
println("Do you want to play again? (yes or no)") | |
val check = readLine("> ") | |
if (check.toLowerCase.startsWith("y") != true) then break | |
} | |
} | |
def getSecretNum: String = { | |
Random.shuffle((0 to 9).toList).slice(0, 3).mkString | |
} | |
def getClues(guess: String, secretNum: String): String = { | |
var clues = new ListBuffer[String]() | |
if (guess == secretNum) { | |
return "You got it" | |
} else { | |
for (i <- 0 until NUM_DIGITS) { | |
if guess(i) == secretNum(i) then clues += "Fermi" | |
else if (secretNum.contains(guess(i))) then clues += "Pico" | |
} | |
} | |
if (clues.length == 0) then return "Bagels" | |
else return clues.sorted.mkString(" ") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment