Lesson 79 +30 XP

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 mt19937 and uniform_int_distribution
  • A while loop that keeps the game going
  • if / else if for the high and low hints
  • continue to 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

  1. Declare int guess = 0; and int attempts = 0;.
  2. Loop with while (guess != secret).
  3. Inside the loop ask cout << "Your guess: "; cin >> guess;.
  4. Reject out-of-range input: if guess < 1 || guess > 100, print Out of range. and continue;.
  5. Only after that, attempts++;.
  6. Add hints: if (guess > secret) print Too high., else if (guess < secret) print Too low..
  7. After the loop print "You got it in " << attempts << " tries.".

Checklist

  • [ ] mt19937 generates the random stream
  • [ ] uniform_int_distribution<int>(1, 100) picks the secret
  • [ ] The while loop 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 while loop keeps running until the condition turns false.
  • continue jumps back to the top of the loop.
  • Count valid attempts, not rejected ones.