BullsAndCows.frink

Download or view BullsAndCows.frink in plain text format

// Bulls and Cows - Written in Frink
println["Welcome to Bulls and Cows!"]

// Put 4 random digits into target array
digits = array[1 to 9]
target = new array
for i = 0 to 3
   target@i = digits.removeRandom[]

// Game variables
guessCount = 0
solved = false

while solved == false
{
   // Round variables
   bulls = 0
   cows = 0
   
   // Input guess from player
   guess = input["Guess a 4 digit number with numbers 1 to 9: "]
   
   // Valid Guess Tests. Set validGuess to true. If any test fails it will be set to false
   validGuess = true
   // Test for exactly 4 digits
   if length[guess] != 4
   {
      println["$guess is invalid. Your guess must be 4 digits."]
      validGuess = false
   }
   
   // Test for any characters not in 1 - 9 using regex
   if guess =~ %r/[^1-9]/
   {
      println["$guess is invalid. Your guess can only contain the digits 1 through 9."]
      validGuess = false
   }
   
   // Check for duplicate digits in guess
   comboCheck = true
   guessArr = charList[guess] // Split guess string into array of characters.
   guessArrCombos = guessArr.combinations[2] // Divide the array into all possible 2 digits combinations.
   for guessCombo = guessArrCombos
      if guessCombo@0 == guessCombo@1 // If the two digits in the combinations are the same mark the comboCheck as failed.
         comboCheck = false

   if comboCheck == false
   {
      println["$guess is invalid. Each digit in your guess should be unique."]
      validGuess = false
   }
   
   // If all tests pass, continue with the game.
   if validGuess == true
   {
      guessCount = guessCount + 1
      for i = 0 to 3
      {
         if parseInt[guessArr@i] == target@i // Convert guess from string to int. Frink imports all input as strings.
         {
            bulls = bulls + 1
            next // If bull is found, skip the contains check.
         }
         if target.contains[parseInt[guessArr@i]]
            cows = cows + 1
      }
      if bulls == 4
         solved = true // Exit from While loop.
      else
      {
         // Print the results of the guess. Formatting for plurals.
         bullsPlural = bulls == 1 ? "bull" : "bulls"
         cowsPlural = cows == 1 ? "cow" : "cows"
         println["Your guess of $guess had $bulls $bullsPlural and $cows $cowsPlural."]
      }
   }
}
guessPlural = guessCount == 1 ? "guess" : "guesses"
println["Congratulations! Your guess of $guess was correct! You solved this in $guessCount $guessPlural."]


Download or view BullsAndCows.frink in plain text format


This is a program written in the programming language Frink.
For more information, view the Frink Documentation or see More Sample Frink Programs.

Alan Eliasen was born 19963 days, 23 hours, 51 minutes ago.