Highscore tracking

Highscore tracking

You can get a random number by using the rand() function together with the modulus operator (%).

rand() % 100 + 1; // value between 1 and 100

Write a program that loads a highscore from a file named highscore.txt. The program should then run a simple number guessing game where the user tries to guess a randomly generated number between 1 and 100 while getting feedback in the form of "lower"/"higher" outputs. The program should count the number of turns the user takes to guess the number correctly. If the user completes the game in fewer turns than the highscore, update highscore.txt with the new score.

Example Console Output

Current Highscore: 8 turns
Guess the number between 1 and 100!
Enter your guess: 50
Higher!
Enter your guess: 75
Lower!
Enter your guess: 60
Higher!
Enter your guess: 65
Higher!
Enter your guess: 70
Lower!
Enter your guess: 67
Lower!
Enter your guess: 66
Congratulations! You guessed the number in 7 turns.
New highscore! Your score has been saved.

Answer

This is one of many ways to do it.

#include <iostream>
#include <fstream>

// Function to load the highscore from "highscore.txt"
int loadHighscore() {
    std::ifstream inFile("highscore.txt");
    int highscore = 1000; // Default highscore if file doesn't exist or is invalid

    if (inFile) {
        inFile >> highscore;
    }

    return highscore;
}

// Function to save a new highscore to "highscore.txt"
void saveHighscore(int newHighscore) {
    std::ofstream outFile("highscore.txt");
    if (outFile) {
        outFile << newHighscore;
    } else {
        std::cerr << "Failed to open highscore.txt for writing." << std::endl;
    }
}

// Function to generate a random number between 1 and 100
int generateRandomNumber() {
    return rand() % 100 + 1;
}

// Function to play the game and return the number of turns taken
int playGame(int secretNumber) {
    int guess, turns = 0;

    std::cout << "Guess the number between 1 and 100!" << std::endl;

    do {
        std::cout << "Enter your guess: ";
        std::cin >> guess;
        turns++;

        if (guess < secretNumber) {
            std::cout << "Higher!" << std::endl;
        } else if (guess > secretNumber) {
            std::cout << "Lower!" << std::endl;
        }
    } while (guess != secretNumber);

    std::cout << "Congratulations! You guessed the number in " << turns << " turns." << std::endl;

    return turns;
}

int main() {
    int highscore = loadHighscore();

    std::cout << "Current Highscore: " << highscore << " turns" << std::endl;

    int secretNumber = generateRandomNumber();
    int turns = playGame(secretNumber);

    if (turns < highscore) {
        saveHighscore(turns);
        std::cout << "New highscore! Your score has been saved." << std::endl;
    } else {
        std::cout << "You did not beat the highscore." << std::endl;
    }

    return 0;
}
Questions