Moortiii icon

Rock vs Paper vs Scissors

Moortiii | PRO | 09/11/16 05:21:09 PM UTC | 0 ⭐ | 321 👁️ | Never ⏰ | []
C++ |

2.43 KB

|

None

|

0 👍

/

0 👎

// Add necessary includes
 
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
 
// This is a simple game of "Rock, Paper, Scissors"
// It is also my first project ever in C++.
 
// Make it possible to replay the game without opening it again
void playAgain() {
    string playAgain;
    cout << "Play again ? Type 'y' for yes and 'n' for no\n" << endl;
    cin >> playAgain;
    if(playAgain == 'y') {
        playGame();
    }
    else {
        playGame();
    }
}
 
string userChoice() {
    string userChoice;
    cout << "Do you choose 'rock', 'paper' or 'scissors'?\n" << endl;
    cin >> userChoice;
    cout << "\nYou have chosen: " << userChoice << endl;
}
 
int genRandNum() {
    // Generate a pseudo-random number between 1 and 3
    int randomNumber;
    srand(time(0));
    randomNumber = rand() % 3 + 1;
}
 
string computerChoice() {
    // 1 = Rock, 2 = Paper, 3 = Scissors, assign a choice to the computer.
    string computerChoice;
    if (randomNumber == 1) {
        computerChoice = "rock";
    }
    else if (randomNumber == 2) {
        computerChoice = "paper";
    }
    else {
        computerChoice = "scissors";
    }
    cout << "\nThe computer chose: " << computerChoice << endl;
}
 
string compareChoices() {
    // Decide who wins by comparing the userChoice and computerChoice
    // Choose what happens if userChoice is rock
    if (userChoice == "rock") {
        if (computerChoice == "paper") {
            cout << "\nPaper beats rock, you lose!\n\n";
        }
        else if (computerChoice == "scissors") {
            cout << "\nRock beats scissors, you win!\n\n";
        }
        else {
            cout << "\nIt's a tie!";
        }
    }
 
 
    // Choose what happens if userChoice is paper
    if (userChoice == "paper") {
        if (computerChoice == "scissors") {
            cout << "\nScissors beats paper, you lose!\n\n";
        }
        else if (computerChoice == "rock") {
            cout << "\nPaper beats rock, you win!\n\n";
        }
        else {
            cout << "\nIt's a tie!";
        }
    }
 
 
    // Choose what happens if userChoice is scissors
    if (userChoice == "scissors") {
        if (computerChoice == "rock") {
            cout << "\nRock beats scissors, you lose!\n\n";
        }
        else if (computerChoice == "paper") {
            cout << "\nScissors beats paper, you win!\n\n";
        }
        else {
            cout << "\nIt's a tie!";
        }
    }
}
 
int playGame() {
    userChoice();
    genRandNum();
    computerChoice();
    compareChoices();
    playAgain();
}
 
int main(int nNumberofArgs, char* pszArgs[]) {
    // Let the user choose rock, paper or scissors
    playGame();
}

Comments