1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <stdlib.h>
#include <time.h>
using namespace std;
void showMenu ()
{
cout << "1 - Rock" << endl;
cout << "2 - Paper" << endl;
cout << "3 - Scissors" << endl;
cout << "4 - Exit" << endl;
}
int getComputerChoice()
{
int compChoice = 0;
int choice = rand() % 3;
if (choice == 0)
compChoice = 1;
else if (choice == 1)
compChoice = 2;
else if (choice == 2)
compChoice = 3;
return compChoice;
}
int getUserChoice()
{
int userChoice;
cout << "Please select your choice: " << endl;
cin >> userChoice;
return userChoice;
}
void determineWinner(int user, int comp)
{
if (user == comp)
cout << "Tie!" << endl;
else if (user == 1 && comp == 2)
cout << "Paper beats rock, you lose!" << endl;
else if (user == 1 && comp == 3)
cout << "Rock beats scissors, you win!\n";
else if (user == 2 && comp == 3)
cout << "Scissors beats paper, you lose!" << endl;
else if (user == 2 && comp == 1)
cout << "Paper beats rock, you win!" << endl;
else if (user == 3 && comp == 1)
cout << "Rock beats scissors, you lose!\n";
else if (user == 3 && comp == 2)
cout << "Scissors beats paper, you win!\n";
}
void displayChoice(int user, int comp)
{
switch (user)
{
case 1:
cout << "You chose rock" << endl;
break;//your program also lacked brake statements.
case 2:
cout << "You chose paper" << endl;
break;
case 3:
cout << "You chose scissors" << endl;
break;
default:
cout<<"\nPlease select a valid choice.\n";//The whole if statement can be replaced by a default statement.
}
switch (comp)
{
case 1:
cout << "Computer chose rock" << endl;
break;
case 2:
cout << "Computer chose paper" << endl;
break;
case 3:
cout << "Computer chose scissors" << endl;
break;
}
}
int main()
{
//Seed random number generator
srandom((unsigned int)time(NULL));
//Declare variables, default values
int user = 0, comp = 0, playAgain = 0;
//Loop of program
do
{
showMenu();
comp = getComputerChoice();
user = getUserChoice();
if (user == 4)
exit(0);
displayChoice(user, comp);
determineWinner(user, comp);
//Play again?
cout << "Do you want to play again? Choose 'Y' for yes, and 'N' for no" << endl;
cin >> playAgain;
if (playAgain != 'Y' &&playAgain != 'y'&& playAgain != 'N' && playAgain != 'n'){//Earlier if statement was logically wrong
cout << "Invalid choice, please choose a valid choice" << endl;
}
}
while (playAgain == 'Y' || playAgain == 'y');
return 0;
}
|