Hi there
Fairly new to programming and c, I decide to make a guess number game but I'm having some trouble with it, the random number is always 0 when the user guesses the right number and then chooses to play again, if the user selects 2 to exit it won't exit the program, here's my code, any help appreciated.
Code:
#include <stdio.h>#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
void headerMessage();
void getGuess(bool,int,int);
void outOfBounds(int);
void tooLow();
void tooHigh();
void guessNumber();
void guessesLeft();
void checkGuessAttempts();
void playAgain();
void outOfBounds2();
void goodBye();
static int selectedNumber;
static int userNumber;
static bool gameOver = false;
static bool keepGoing = true;
static int playagain;
static int const MAX_GUESS_ATTEMPTS = 5;
static int nTries = 0;
static int nTriesLeft = 5;
int main()
{
srand(time(NULL));
headerMessage();
getGuess(gameOver,userNumber,selectedNumber);
return 0;
}
void headerMessage(){
printf("\n********************");
printf("\n* Guess The *");
printf("\n* Number Game *");
printf("\n********************");
}
void getGuess(bool gameOver,int userNumber,int selectedNumber){
do{
//selectedNumber = rand()%20+1;
printf("\n%d" , selectedNumber);
printf("\nGuess a number between 1 and 20: ");
scanf("%d", &userNumber);
outOfBounds(userNumber);
}while(gameOver == false);
}
void outOfBounds(int userNumber){
if(userNumber < 0 || userNumber > 20){
printf("NUMBER ENTERED OUT OF BOUNDS! ");
}
else{
guessNumber(userNumber);
}
}
void tooLow(){
printf("TOO LOW! TRY AGAIN!");
}
void tooHigh(){
printf("TOO HIGH! TRY AGAIN! ");
}
void guessNumber(int userNumber){
if(userNumber < selectedNumber){
tooLow();
nTries++;
nTriesLeft--;
guessesLeft();
}
else if(userNumber > selectedNumber){
tooHigh();
nTries++;
nTriesLeft--;
guessesLeft();
}
else{
printf("You got it! press 1 to play again or 2 to quit: ");
printf("It took you %d ", nTries);
scanf("%d", &playagain);
nTriesLeft = 5;
nTries = 0;
playAgain();
}
checkGuessAttempts();
}
void guessesLeft(){
printf("You have %d ", nTriesLeft );
}
void checkGuessAttempts(){
if(nTries >= MAX_GUESS_ATTEMPTS){
printf("GAME OVER! ");
gameOver = true;
}
}
void playAgain(){
while(playagain !=1 && playagain !=2){
outOfBounds2();
scanf("%d", &playagain);
}
if(playagain == 2){
gameOver = true;
goodBye();
}
else{
selectedNumber = rand()%20+1;
}
}
void outOfBounds2(){
if(playagain < 1 || playagain > 2){
printf("OUT OF BOUNDS CHOICE, ONLY SELECT OPTION 1 OR 2! ");
}
}
void goodBye(){
printf("Goodbye! ");
}