Rock, Paper, Scissors Game (c++ only) Write a program that lets the user play th
ID: 665437 • Letter: R
Question
Rock, Paper, Scissors Game (c++ only)
Write a program that lets the user play the game of Rock, Paper, Scissors against the computer. The program should work as follows.
When the program begins, a random number in the range of 1 through 3 is gener- ated. If the number is 1, then the computer has chosen rock. If the number is 2, then the computer has chosen paper. If the number is 3, then the computer has chosen scissors. (Don’t display the computer’s choice yet.)
The user enters his or her choice of “rock”, “paper”, or “scissors” at the keyboard. (You can use a menu if you prefer.)
The computer’s choice is displayed.
A winner is selected according to the following rules:
If one player chooses rock and the other player chooses scissors, then rock wins. (The rock smashes the scissors.)
If one player chooses scissors and the other player chooses paper, then scissors wins. (Scissors cuts paper.)
If one player chooses paper and the other player chooses rock, then paper wins. (Paper wraps rock.)
If both players make the same choice, the game must be played again to deter- mine the winner.
use srand()
Explanation / Answer
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
void cast(int);
int flag=0;
int main() {
int ch,i=0;
char choice;
do
{
// Seed the RNG once, at the start of the program
srand( time( NULL ) );
cout<<" Menu: ";
cout<<" 1.Rock";
cout<<" 2.Paper";
cout<<" 3.Scissors";
cout<<" Enter your choice : ";
cin>>ch;
if(ch<1||ch>3)
continue;
flag=0;
// Take your chance(start game)
cast(ch);
if(flag==1) //In case both get the same thing
{
cout<<" Its a tie!! Please play again";
continue;
}
cout<<" Do you want to play again ? (y/n)" ; //to continue playing or stop
cin>>choice;
if(choice=='n'||choice=='N')
i=1;
}while(i==0);
return 0;
}
void cast(int ch)
{
// Get a pseudo-random number among (1,2,3)
int num = (rand() % 3) + 1;
cout <<" The system has chosen : ";
switch(num)
{
case 1: cout<<"Rock!";
if(ch==1)
{flag=1;
cout<<" Your choice : Rock";
break;
}
else if(ch==2)
{
cout<<" Your choice : Paper";
cout<<" You Win!! ";
break;
}
else
{
cout<<" Your choice : Scissors";
cout<<" You Lose!! ";
break;
}
case 2: cout<<"Paper!";
if(ch==1)
{ cout<<" Your choice : Rock";
cout<<" You Lose!! ";
break;
}
else if(ch==2)
{ flag=1;
cout<<" Your choice : Paper";
break;
}
else
{
cout<<" Your choice : Scissors";
cout<<" You Win!! ";
break;
}
case 3: cout<<"Scissors!";
if(ch==1)
{ cout<<" Your choice : Rock";
cout<<" You Win!! ";
break;
}
else if(ch==2)
{
cout<<" Your choice : Paper";
cout<<" You Lose!! ";
break;
}
else
{flag=1;
cout<<" Your choice : Scissors";
break;
}
default : break;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.