C Programming Only Please I will rate 5 stars ! Problem #1: Rock/Paper/Sissors T
ID: 3532767 • Letter: C
Question
C Programming Only Please
I will rate 5 stars !
Problem #1: Rock/Paper/Sissors
This is the game of rock/paper/scissors. The user, Player 1, will play against the computer,
Player 2. The user will input his/her choice of rock/paper/scissor while the computer's choice
will be randomly generated. The user will select how many times he/she wants to play against
the computer.
An output table will be generated that shows the results of each try.
The rules for the game are:
P1 P2 Results
R R Tie
R P P2 win
R S P1 win
P R P1 win
P P Tie
P S P2 win
S R P2 win
S P P1 win
S S Tie
The overall winner will be acknowledged.
There are two functions main() and rockPaperSissors().
The first task in main is to explain the game (using a nice format)
The main function inputs the users
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int aiMove(void);
int evaluate(int ai, int player);
int main()
{
char p1Move;
int i;
printf("Enter number of rounds you want to play: ");
scanf("%d", &i);
getchar();
int counter = 1;
while(i){
printf("Round %d: ", counter);
//get player's move
printf("Player 1 Move (R - rock, P - paper, S - scissors): ");
p1Move = getchar();
//flush out enter
getchar();
//error checking
if (p1Move != 'R' && p1Move != 'P' && p1Move != 'S'){
printf("Sorry. %c is not a valid move. Please try again. ", p1Move);
continue;
}
//evaluate p1 move
int p1MoveValue = 0;
switch (p1Move){
case 'R':
p1MoveValue = 1;
printf("You chose Rock. ");
break;
case 'P':
p1MoveValue = 2;
printf("You chose Paper. ");
break;
case 'S':
p1MoveValue = 3;
printf("You chose Scissors. ");
break;
default:
break;
}
int ai = aiMove();
int judge = evaluate(ai, p1MoveValue);
switch (judge){
case -1:
printf("You lost. ");
i--;
counter++;
break;
case 0:
printf("You drew. ");
break;
case 1:
printf("You won. ");
i--;
counter++;
break;
default:
break;
}
printf(" ");
}
printf("End game: Thank you for playing! ^_^");
return 0;
}
int aiMove(void){
srand (time(NULL));
int returnVal = rand() % 3 + 1;
switch (returnVal){
case 1:
printf("The computer chose Rock. ");
break;
case 2:
printf("The computer chose Paper. ");
break;
case 3:
printf("The computer chose Scissors. ");
break;
default:
break;
}
return returnVal;
}
//returns 0 for draw, -1 for player lose and 1 for player win
int evaluate(int ai, int player){
//draw
if (ai == player)
return 0;
//player lose
if (player == 3 && ai == 1)
return -1;
if (player == 1 && ai == 3)
return 1;
if (player > ai)
return 1;
//player win
return -1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.