Build a Guessing Game
Today we build a real mini-game! π Itβs the classic guessing game: the computer hides a secret number, and the player keeps guessing until they find it. Each guess gets a hint β too high or too low β untilβ¦ you win!
Weβre going to combine the pieces you already know to make something that actually feels like a game.
The secret number
First we need a place to keep the secret. We use a variable β a labeled box
that holds a value. Letβs put the number 42 inside a box called secret.
To check a guess, the computer compares numbers. Is the guess less than the
secret? Then itβs too low. Greater than? Too high. The same? You win! In Rust we
write that with if, else if, and else.
Letβs play!
Real games read what a player types and pick a random number each time. We havenβt
learned those tools yet, so for now weβll pretend: the secret is always 42,
and weβll line up three guesses right inside the code β 50, then 25, then 42.
Press βΆ Run and watch the game play itself!
See how the hints guide the player closer and closer? First too high, then too low, then β bullseye! That sneaky pattern of checking again and again is the heart of a loop, which repeats steps over and over until something happens.
let guess = 70; β and press
βΆ Run. Does the hint change to match? Then press
βΊ Reset to bring back the original game.
Quick quiz
If your guess is bigger than the secret number, what hint should the game show?
if / else if / else compare
the guess and give hints, and a loop repeats until the player wins.
Next up is World 3: Building Blocks, where we dig into the pieces
that make every Rust program tick! π§±