🎲
World 2 Β· The Guessing Game

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 Big Idea A game is just a program with rules. Our rules are simple: hide a number, take a guess, give a hint, and repeat until the guess is right. πŸ¦€

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.

New word A variable is a named box that holds a piece of information your program can use later, like a sticky note with a number on it.

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.

Think of it like this… It's like a "warmer, warmer, COLDER!" search for a friend's lost keys. The hints don't tell you the answer β€” they just nudge you the right way until you find it. πŸ”₯❄️
Try this! Change one of the guesses in the code β€” try let guess = 70; β€” and press β–Ά Run. Does the hint change to match? Then press β†Ί Reset to bring back the original game.
Ferris says: You just built a real game out of variables, comparing, and hints! Soon you'll learn how to read what a player types and pick a truly random number, so every round is a fresh surprise. πŸ¦€

Quick quiz

If your guess is bigger than the secret number, what hint should the game show?

You learned… You built a real guessing game! A variable holds the secret, 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! 🧱