I have written the below shared code and wanted to ask for some optimization tips or even alternative (more elegant?) ways of solving the task at hand (maybe without goto
s?). My code, even if 'crude', should work properly.
The exercise basically asks me to recreate a Rock, Paper, Scissors game with the CPU (randomizing the CPU's moves) and to print a summary of our interaction.
//Rock, Paper, Scissors
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
//Variables Definition
int user_choice, computer_choice, rematch = 0; //Normal Variables
int games_number = 0, games_played = 0, user_wins = 0, computer_wins = 0, even_games = 0; //Counters
start:
//User Interface
printf("How many matches (to the best of 1) would you like to play?\n");
scanf("%d", &games_number);
//Input Management
if(games_number >= 1){
for(int i = 0; i < games_number; ++i){ //For cycle (match) beginning
srand(time(NULL)); //Computer choice randomization
games_played += 1; //Matches played counter increment
//Request of chosen move
printf("\nChoose your own move:\n1 = Rock\n2 = Paper\n3 = Scissors\n\n");
scanf("%d", &user_choice);
//Invalid input case
if(user_choice <= 0 || user_choice >= 4){
printf("\nYou have chosen an invalid move!\n(An invalid number was inserted)\n");
goto end;
}
//Computer move simulation
computer_choice = 1 + rand() % 3;
printf("(Computer's choice': %d)\n", computer_choice); //printf not required
//Results computation
if(user_choice == computer_choice){ //user == pc
printf("\nYou are even!\n");
even_games += 1;
}else if(user_choice == 1 && computer_choice == 2){ //user: rock | pc: paper
printf("\nThe user has won, congratulations!\n");
user_wins += 1;
}else if(user_choice == 1 && computer_choice == 3){ //user: rock | pc: scissors
printf("\nThe user has lost :(\n");
computer_wins += 1;
}else if(user_choice == 2 && computer_choice == 1){ //user: paper | pc: rock
printf("\nThe user has won, congratulations!\n");
user_wins += 1;
}else if(user_choice == 2 && computer_choice == 3){ //user: paper | pc: scissors
printf("\nThe user has lost :(\n");
computer_wins += 1;
}else if(user_choice == 3 && computer_choice == 1){ //user: scissors | pc: rock
printf("\nThe user has lost :(\n");
computer_wins += 1;
}else if(user_choice == 3 && computer_choice == 2){ //user: scissors | pc: paper
printf("\nThe user has won, congratulations!\n");
user_wins += 1;
}
}//for cycle (match) end
end:
//Rematch request
printf("\nDo you want to play again?\nYes: 1 || No: other\n");
scanf("%d", &rematch);
if(rematch == 1){
puts("");
goto start;
}
//Print summary
printf("\n| %s | %s | %s | %s |\n", "Matches Played", "User Victories", "Computer Victories", "Even Matches");
printf("| %14d | %14d | %17d | %12d |\n", games_played, user_wins, computer_wins, even_games);
}else{ //if (games_number >= 1) end
printf("\nAlright, go play something else then :'(\n");
}
return 0;
}