Skip to content

Simple C++ game code

a computer screen with a bunch of code on it

Let’s create a simple C++ game. We’ll make a guessing game where the player has to guess a randomly chosen number between 1 and 100. This will help you understand basic concepts in C++ such as loops, conditionals, and input/output.

Here is the C++ code for the guessing game:


#include <iostream>
#include <cstdlib>
#include <ctime>

int main
() {
    // Initialize random seed
    std::srand(static_cast<unsigned int>(std::time(nullptr)));
    // Generate random number between 1 and 100
    int secretNumber = std::rand() % 100 + 1;
    int guess = 0;
    int numberOfTries = 0;
    std::cout << "Welcome to the Guessing Game!" << std::endl;
    std::cout << "I have chosen a number between 1 and 100." << std::endl;
    std::cout << "Can you guess what it is?" << std::endl;
    // Game loop
    while (guess != secretNumber) {
        std::cout << "Enter your guess: ";
        std::cin >> guess;
        numberOfTries++;
        if (guess < secretNumber) {
            std::cout << "Too low! Try again." << std::endl;
        } else if (guess > secretNumber) {
            std::cout << "Too high! Try again." << std::endl;
        } else {
            std::cout << "Congratulations! You guessed the number in " << numberOfTries << " tries." << std::endl;
        }
    }
    return 0;
}

Explanation

  1. Include Libraries:
    • #include <iostream>: For input and output operations.
    • #include <cstdlib>: For random number generation.
    • #include <ctime>: For seeding the random number generator with the current time.
  2. Main Function:
    • std::srand(static_cast<unsigned int>(std::time(nullptr))): Seeds the random number generator using the current time. This ensures the random number is different each time the program runs.
    • int secretNumber = std::rand() % 100 + 1: Generates a random number between 1 and 100.
    • int guess = 0 and int numberOfTries = 0: Initializes the variables for the player’s guess and the number of attempts.
  3. Game Loop:
    • The while loop continues to prompt the user for guesses until the correct number is guessed.
    • std::cin >> guess: Takes the player’s guess as input.
    • numberOfTries++: Increments the number of attempts each time the player makes a guess.
    • Conditional statements (if, else if, else) provide feedback to the player about whether their guess was too low, too high, or correct.

Leave a Reply

Your email address will not be published. Required fields are marked *