我试图让游戏只让用户有3个猜测来正确猜测。问题在于它让用户第四次猜测,但是即使用户在第四次尝试中正确猜测,我也会收到错误的答案消息。我尝试更改猜测的数量,更改i = 0的开始位置,从for循环的maxGuesses中减去1。无论我尝试什么,这种关系都是一成不变的。到目前为止,这是我的代码。
let readlineSync = require("readline-sync");
let hint = "";
let maxGuesses = 3;
const maxRange = 10;
const minRange = 1;
let userGuess = readlineSync.question(
"I have chosen a number between " +
minRange +
" and " +
maxRange +
". You have " +
maxGuesses +
" tries to guess it!\n"
);
const randomNumber = Math.floor(Math.random() * maxRange + 1);
function handleGuess(userGuess) {
if (userGuess != null && userGuess != undefined && (userGuess <= maxRange && userGuess >= minRange)) {
for (i = 0; i <= maxGuesses - 1; i++) {
if (userGuess == randomNumber) {
console.log(userGuess + " is CORRECT! YOU WIN!");
return;
} else {
if (userGuess > randomNumber) {
hint = "Think lower you fool.";
} else {
hint = "Think higher you fool.";
}
console.log(hint);
userGuess = readlineSync.question("Guess again. \n");
}
}
console.log("Dude...YOU SUCK!");
return;
} else {
userGuess = readlineSync.question("Fix your answer fool! \n");
handleGuess(userGuess);
}
}
答案 0 :(得分:1)
我假设您的第一个电话是没有参数的handleGuess()
。
然后,您的程序向用户询问其首先猜测(带有消息“解决傻瓜!”)。如果您使用参数调用handleGuess()
,则仍然适用以下条件。
之后,循环将开始。
如果第一个答案是错误的,控制台将显示消息“想想你(傻瓜),(高/低)。”,然后要求 second (猜)。仍处于第一次循环迭代中。
您看到问题出在哪里吗?
如果第二个猜测仍然错误,则控制台将显示第二个错误消息,并在仍处于第二个循环迭代中时请求第三个猜测。
最后,如果第三个猜测仍然不正确,则会出现第三个“错误”消息,并且您的代码将在结束循环之前请求第四次猜测并显示消息“ Dude ... YOU”吸!”无需验证您的输入。
为防止这种情况,您可以执行以下操作:
function handleGuess(userGuess) {
i = 0;
do {
if(i > 0) {
if(userGuess > randomNumber) {
hint = "Think lower you fool.";
} else {
hint = "Think higher you fool.";
}
console.log(hint);
userGuess = readlineSync.question("Guess again. \n");
}
while(isNaN(userGuess)) {
userGuess = readlineSync.question("Correct you guess. \n");
}
} while(userGuess != randomNumber && i < maxGuesses);
if (userGuess == randomNumber) {
console.log(userGuess + " is CORRECT! YOU WIN!");
} else {
console.log("Dude...YOU SUCK!");
}
}
答案 1 :(得分:-1)
只需将循环条件设置为i < maxGuesses
而不是i <= maxGuesses -1
:
var maxGuesses = 3;
for (i = 0; i < maxGuesses; i++) {
console.log("Guess " + (i + 1)); // Only adding 1 here so output is 1-based
}