I am trying to make a number guessing game where the user gets 3 chances to guess a number between 1 to 10 and after the third try if they don't manage to guess the number correctly, they'll lose and the number input becomes disabled.
So my variable "tryNum" is meant to be the number of guesses the user gets which I set to be 3. And I then wrote my if statement whereby every time the user guesses the number incorrectly, the value of tryNum decreases by 1. And based on my code, by the time the user guesses 3 incorrect numbers, the input should become disabled and an error message should be displayed. However, when I run my code, it takes 4 incorrect guesses instead of 3 for my code to execute.
I am not sure why this is. Any help would be greatly appreciated.
Here is my code:
let min = 1,
max = 10,
winningNum = 3;
tryNum = 3;
function btnClciked(){
guessedNum = parseInt(userInput.value);
if (tryNum > 0){
let status;
if (isNaN(guessedNum) || guessedNum < min || guessedNum > max ){
if(document.querySelector(".error-display")){
status = false;
} else {
status = true;
}
isNaN(guessedNum) ? createDivElement("You havn't entered any number!", status, "#eb992d","black", true) : createDivElement(`You must guess a number between ${min} and ${max}`, status, "#eb992d", "black", true);
}
else if (guessedNum === winningNum){
status = true;
userInput.disabled = true;
userInput.style.borderColor = "green";
submitBtn.value = "Play Again!";
submitBtn.className += "play-again";
createDivElement(`Congratulations! You guessed the winning number: ${winningNum} Correctly!`, status, "green", "white");
}
else {
status = true;
userInput.style.borderColor = "red";
userInput.value = "";
tryNum -= 1;
createDivElement(`${guessedNum} isn't the winning number! You have ${tryNum} more guesses left!`, status, "red", "white");
}
} else {
userInput.disabled = true;
status = true;
userInput.style.borderColor = "red";
submitBtn.value = "Play Again!";
submitBtn.className += "play-again";
createDivElement(`Game Over! The winning number was ${winningNum}.`, status, "red", "white");
}
}
Aucun commentaire:
Enregistrer un commentaire