Last active
September 5, 2022 07:25
-
-
Save crisu83/2568a30deb33102f32dabdd13f85512a to your computer and use it in GitHub Desktop.
A "guess a number game" implementation written in Kotlin that we wrote together with my 12 year old son when learning basic concepts in programming.
This file contains hidden or 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 kotlin.random.Random | |
fun main() { | |
val secretNumber = Random.nextInt(1, 100) | |
var numTries = 0 | |
var numTriesLeft: Int | |
var gameWon = false | |
println("Welcome to Guess a number!") | |
println("--------------------------") | |
println("I have chosen a secret number between 0 and 100.") | |
println("Your task is to guess what the secret number is.") | |
while (true) { | |
numTriesLeft = MAX_TRIES - numTries | |
if (numTriesLeft == 1) { | |
println("This is your last try") | |
} else { | |
println("You have $numTriesLeft tries left") | |
} | |
var guessedNumber: Int | |
do { | |
print("Guess a number: ") | |
guessedNumber = readLine()!!.toIntOrNull()!! | |
val isNumberValid = guessedNumber in 1..99 | |
if (!isNumberValid) { | |
println("Please enter a number between 0 and 100") | |
} | |
} while (!isNumberValid) | |
if (guessedNumber > secretNumber) { | |
println("Too high") | |
} else if (guessedNumber < secretNumber) { | |
println("Too low") | |
} else { | |
println("Your guess was correct!") | |
gameWon = true | |
break | |
} | |
numTries++ | |
if (numTries >= MAX_TRIES) { | |
println("Game over!") | |
break | |
} | |
} | |
println("The secret number was: $secretNumber") | |
if (gameWon) { | |
val score = numTriesLeft * POINTS_PER_TRY_LEFT | |
println("Congrats! You won") | |
println("Your score was: $score") | |
} | |
} | |
const val MAX_TRIES = 7 | |
const val POINTS_PER_TRY_LEFT = 100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment