End Game

Learn to set up the game’s end.

What we have

We already have almost a complete game, but after checking the winner of each round, we have to display the results at the end. This is our inventory of already created functions:

// Function to display game introduction and rules
void displayIntroductionAndRules() {
    cout << "Welcome to Rock-Paper-Scissors game!\n" << endl;
    cout << "The rules of the game are simple:" << endl;
    cout << "1. Rock beats scissors" << endl;
    cout << "2. Scissors beats paper" << endl;
    cout << "3. Paper beats rock" << endl;
}

// Function to get number of rounds
int getRound() {
    int rounds;
    cout << "How many rounds would you like to play? ";
    cin >> rounds;
    return rounds;
}

// Function to get player's choice
string getPlayerChoice() {
    string choice;
    cout << "Choose rock, paper, or scissors: ";
    cin >> choice;
    return choice;
}

// Function to generate computer's choice
string generateComputerChoice() {
    srand(time(NULL));
    int rand_num = rand() % 3;
    if (rand_num == 0) {
        return "rock";
    } else if (rand_num == 1) {
        return "paper";
    } else {
        return "scissors";
    }
}

// Function to determine the winner of the round and update scores
void determineWinner(string player_choice, string computer_choice) {
    if (player_choice == computer_choice) {
        cout << "It's a tie!" << endl;
    } else if ((player_choice == "rock" && computer_choice == "scissors") ||
               (player_choice == "scissors" && computer_choice == "paper") ||
               (player_choice == "paper" && computer_choice == "rock")) {
        cout << "You win!" << endl;
        player_score++;
    } else {
        cout << "The computer wins!" << endl;
        computer_score++;
    }
}

What now?

We can create a function to print the results when the game ends. It should print a final message and display the scores of both players. These are the steps we need to perform in this task:

  • Print the final scores.
  • Announce the winner.

Try it yourself

Write your code in the code widget below and click the “Run” button to execute your code.

If you’re unsure how to do this, click the “Show Hint” button.

Get hands-on with 1400+ tech skills courses.