Loading lessons...
Project 4: Number Guessing Game
Project 4: Number Guessing Game
You now have the pieces to build your first real game: the computer picks a secret number, and you try to find it with hints.
The goal
Generate a random number between 1 and 100, ask the user to guess, print Too high or Too low, and count attempts until the guess matches.
What you practice
- Random numbers with
mt19937anduniform_int_distribution - A
whileloop that keeps the game going if/else iffor the high and low hintscontinueto skip a bad guess- Counting attempts
Starter code
Start from this compile-able program:
#include <iostream>
#include <random>
using namespace std;
int main() {
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int> draw(1, 100);
int secret = draw(gen);
cout << "I picked a number from 1 to 100." << endl;
return 0;
}
Step-by-step
- Declare
int guess = 0;andint attempts = 0;. - Loop with
while (guess != secret). - Inside the loop ask
cout << "Your guess: "; cin >> guess;. - Reject out-of-range input: if
guess < 1 || guess > 100, printOut of range.andcontinue;. - Only after that,
attempts++;. - Add hints:
if (guess > secret)printToo high.,else if (guess < secret)printToo low.. - After the loop print
"You got it in " << attempts << " tries.".
Checklist
- [ ]
mt19937generates the random stream - [ ]
uniform_int_distribution<int>(1, 100)picks the secret - [ ] The
whileloop runs until the guess matches - [ ] Out-of-range guesses are skipped with
continue - [ ] Attempts only count for valid guesses
- [ ] Hints tell the player too high or too low
TL;DR
mt19937 gen(rd())creates a random generator.- A
whileloop keeps running until the condition turns false. continuejumps back to the top of the loop.- Count valid attempts, not rejected ones.