Joining the Dots
Learn to set up the main function using all functions.
We'll cover the following
What we have
We have catered to all the components of the game. We’ve created all the game’s functionalities, but have we sorted our game yet? 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++;
}
}
// End Game
void endGame(){
cout << "The final score is: " << "You" << " " << player_score << " - Computer " << computer_score << endl;
if (player_score > computer_score) {
cout << "Congratulations! You are the winner!" << endl;
} else if (player_score == computer_score) {
cout << "It's a tie game!" << endl;
} else {
cout << "Sorry, the computer won." << endl;
}
}
What now?
Now, we need to create a main function, gameLoop(),
which manages the game’s flow. It takes rounds
as a parameter and runs the game for the total number of rounds using the for
loop.
These are the functions that we created in our game:
-
displayIntroductionAndRules()
-
getRound()
-
getPlayerChoice()
-
generateComputerChoice()
-
determineWinner()
-
endGame()
Let’s use these functions in the gameLoop()
function and set up the game flow.
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.