#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int playerChoose()
{
char player_string;
int player_choice = 0;
printf("\nMake your choice using one of the letters: 'R' / 'P' / 'S':\n\n");
scanf(" %c", &player_string);
player_string = (char)toupper(player_string);
if(player_string == 'R') {
printf("\nYou chose rock.\n");
player_choice = 1;
} else if(player_string == 'P') {
printf("\nYou chose paper.\n");
player_choice = 2;
} else if(player_string == 'S') {
printf("\nYou chose scissors.\n");
player_choice = 3;
} else {
playerChoose();
}
return player_choice;
}
int computerChoose()
{
srand(time(NULL));
int computerChoice = 1 + rand() % 3; /* Return a random number between 1 and 3 */
if(computerChoice == 1) {
printf("\nThe computer chose rock.\n");
} else if(computerChoice == 2) {
printf("\nThe computer chose paper.\n");
} else if(computerChoice == 3) {
printf("\nThe computer chose scissors.\n");
}
return computerChoice;
}
int compareChoices(int playerChoice, int computerChoice)
{
if(playerChoice == 1) { /* User chooses rock */
if(computerChoice == 1) { /* Computer chooses rock */
printf("\nIt's a tie!\n");
} else if(computerChoice == 2) { /* Computer chooses paper */
printf("\nThe computer wins.\n");
} else if(computerChoice == 3) { /* Computer chooses scissors */
printf("\nYou win!\n");
}
} else if(playerChoice == 2) { /* Player chooses paper */
if(computerChoice == 1) { /* Computer chooses rock */
printf("\nYou win!\n");
} else if(computerChoice == 2) { /* Computer chooses paper */
printf("\nIt's a tie.\n");
} else if(computerChoice == 3) { /* Computer chooses scissors */
printf("\nThe computer wins.\n");
}
} else if(playerChoice == 3) { /* Player chooses scissors */
if(computerChoice == 1) { /* Computer chooses rock */
printf("\nThe computer wins.\n");
} else if(computerChoice == 2) { /* Computer chooses paper */
printf("\nYou win!\n");
} else if(computerChoice == 3) { /* Computer chooses scissors */
printf("\nIt's a tie.\n");
}
}
}
void playAgain()
{
char play_again;
printf("\nDo you want to play again? 'Y' / 'N'\n\n");
scanf(" %c", &play_again);
play_again = (char)toupper(play_again);
if(play_again == 'Y') {
playGame();
} else if(play_again == 'N') {
printf("\nThank you for playing.\n");
} else {
playAgain();
}
}
void playGame()
{
int playerChoice = playerChoose();
int computerChoice = computerChoose();
compareChoices(playerChoice, computerChoice);
playAgain();
}
int main()
{
playGame();
return 0;
}
Comments