我正在尝试制作一个数字猜谜游戏,其中用户有3次机会猜出一个介于1到10之间的数字,而第三次尝试后,如果他们未能正确猜对这个数字,他们将会输掉这个数字输入被禁用。
因此,我的变量“ tryNum”是用户设置为3的猜测数。然后,我编写了if语句,借此,每次用户错误地猜出该数字时,tryNum的值将减少1.根据我的代码,当用户猜出3个不正确的数字时,应禁用输入并显示错误消息。但是,当我运行代码时,执行代码需要4个错误的猜测,而不是3个。
我不确定为什么会这样。任何帮助将不胜感激。
这是我的代码:
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");
}
}
答案 0 :(得分:1)
当用户猜错时,您应该检查distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
是否等于tryNum
,在这种情况下,您应该证明它已经结束。
0
答案 1 :(得分:0)
基本上,当您第三次不猜测数字时tryNum的值为0,但是您必须进行另一次猜测才能触发第一个if语句并输入最后的else块。
最简单的解决方案是将最终的else块放入tryNum-=1
下的if语句中,以检查变量是否为0