#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
void playGame();
int genRandNum();
string userChooses();
bool playAgain();
bool playAgain() {
string stayOrGo;
do {
cout << "\nType 'y' to play again, 'n' to quit.\n" << endl;
cin >> stayOrGo;
if (stayOrGo != "y" && stayOrGo != "n") {
cout << "\nThat is not correct input." << endl;
}
} while (stayOrGo != "y" && stayOrGo != "n");
return stayOrGo == "y";
}
int genRandNum() {
int randomNumber;
srand(time(0));
randomNumber = rand() % 3 + 1;
return randomNumber;
}
string userChooses() {
string userChoice;
do {
cout << "\nDo you choose 'rock', 'paper' or 'scissors'?\n\n";
cin >> userChoice;
if (userChoice != "rock"
&& userChoice != "paper"
&& userChoice != "scissors") {
cout << "\nThat is not correct input." << endl;
}
} while (userChoice != "rock"
&& userChoice != "paper"
&& userChoice != "scissors");
cout << "\nYou have chosen: " << userChoice << endl;
return userChoice;
}
string computerChooses(int randomNumber) {
string computerChoice;
if (randomNumber == 1) {
computerChoice = "rock";
cout << "\nThe computer has chosen: " << computerChoice << endl;
}
else if (randomNumber == 2) {
computerChoice = "paper";
cout << "\nThe computer has chosen: " << computerChoice << endl;
}
else {
computerChoice = "scissors";
cout << "\nThe computer has chosen: " << computerChoice << endl;
}
return computerChoice;
}
void compareChoices(string userChoice, string computerChoice) {
// If userChoice is rock
if (userChoice == "rock") {
if (computerChoice == "paper") {
cout << "\nPaper beats rock, you lose!" << endl;
} else if(computerChoice == "scissors") {
cout << "\nRock beats scissors, you win!" << endl;
}
else {
cout << "\nIt's a tie!" << endl;
}
}
// If userChoice is paper
if (userChoice == "paper") {
if (computerChoice == "scissors") {
cout << "\nScissors beats paper, you lose!" << endl;
}
else if (computerChoice == "rock") {
cout << "\nPaper beats rock, you win!" << endl;
}
else {
cout << "\nIt's a tie!" << endl;
}
}
// If userChoice is scissors
if (userChoice == "scissors") {
if (computerChoice == "rock") {
cout << "\nRock beats scissors, you lose!" << endl;
}
else if (computerChoice == "paper") {
cout << "\nScissors beats paper, you win!" << endl;
}
else {
cout << "\nIt's a tie!" << endl;
}
}
}
void playGame() {
string userChoice = userChooses();
string computerChoice = computerChooses(genRandNum());
compareChoices(userChoice, computerChoice);
}
int main() {
do {
playGame();
} while (playAgain());
cout << "\nYou have chosen to exit the game.\n" << endl;
system("PAUSE");
return 0;
}
Comments