Hello, first post here! I'm taking my first programming course, and working on an assignment. We are to accept input as r, p, s or q (rock, paper scissors, quit). It is a 2 player game both responses input by user, so not using rand fn. I have mine accepting the proper inputs, and incrementing and decrementing properly for wins/ties and printing output to screen once terminated.
My issue is how do I get it to reprompt the user for a response if they enter an invalid one, not sure if I need 2 loops, or if an if statement in between each input may suffice?
Any help much appreciated, source code at bottom of this post.
Here's a sample interaction from the assignment handout:
"Welcome to Rock, Paper, Scissors! It's Player 1's turn.
Choose Rock (r),Paper (p), Scissors (s), or Quit (q): p
It's Player 2's turn.
Choose Rock (r), Paper (p), Scissors (s), or Quit (q): s
Player 2 wins!
It's Player 1's turn.
Choose Rock (r),Paper (p), Scissors (s), or Quit (q): k
Player 1 bad input. Try again.
It's Player 1's turn.
Choose Rock (r),Paper (p), Scissors (s), or Quit (q): r
It's Player 2's turn.
Choose Rock (r), Paper (p), Scissors (s), or Quit (q): d
Player 2 bad input. Try again.
It's Player 2's turn.
Choose Rock (r), Paper (p), Scissors (s), or Quit (q): s
Player 1 wins!
It's Player 1's turn.
Choose Rock (r),Paper (p), Scissors (s), or Quit (q): p
It's Player 2's turn.
Choose Rock (r), Paper (p), Scissors (s), or Quit (q): p
Tie!
It's Player 1's turn.
Choose Rock (r),Paper (p), Scissors (s), or Quit (q): q
Here are the final results:
Player 1's wins: 1
Player 2's wins: 1
Ties: 1"
Code:
#include <stdio.h>int main (void)
{
char response1, response2;
int wins1 = 0, wins2 = 0, ties = 0;
printf("\nWelcome to Rock Paper Scissors!\n\n");
do {
printf("\nIt's Player 1's Turn\n");
printf("\nEnter Rock (r), Paper (p), Scissors (s), or Quit (q): ");
scanf("%c", &response1);
getchar();
printf("\nIt's Player 2's Turn\n");
printf("\nEnter Rock (r), Paper (p), Scissors (s), or Quit (q): ");
scanf("%c", &response2);
getchar();
// Output winner of match or if it's a tie and increment/decrement number of ties/wins/losses
if ((response1 == 'r' && response2 == 'r') || (response1 == 'p' && response2 == 'p') || (response1 == 's' && response2 == 's'))
{
ties++;
printf("\nIt's a tie!\n");
}
else if ((response1 == 'r' && response2 == 's') || (response1 == 'p' && response2 == 'r') || (response1 == 's' && response2 == 'p'))
{
wins1++;
printf("\nPlayer one wins\n\n");
}
else if ((response2 == 'r' && response1 == 's') || (response2 == 'p' && response1 == 'r') || (response2 == 's' && response1 == 'p'))
wins2++;
printf("\nPlayer two wins!\n\n");
}
while ((response1 == 's' || response1 == 'r' || response1 == 'p') && (response2 == 'r' || response2 == 's' || response2 == 'p'));
printf("\nTotals:\nPlayer 1:%2d\nPlayer 2:%2d\nTies:%2d\n", wins1, wins2, ties);
return 0;
}