一直在尝试做一个猜谜游戏,我想做3次猜测的限制,但我不知道,有人有想法吗
const minNum = 1;
const maxNum = 10;
const answer = Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;
let attempts = 3;
let guess;
let running = true;
while (running) {
guess = prompt(`Guess a number between ${minNum} - ${maxNum}`);
guess = Number(guess);
if (isNaN(guess)) {
prompt("This number isn't valid");
} else if (guess < minNum || guess > maxNum) {
prompt("This number isn't valid");
} else {
attempts++;
if (guess > answer) {
prompt("TOO HIGH, TRY AGAIN");
} else if (guess < answer) {
prompt("TOO LOW, TRY AGAIN");
} else {
prompt(`Correct, the number is ${answer}. it took you ${attempts} attempts!`);
running = false;
}
}
}
// Check if the user entered a valid number
if (isNaN(userGuess) || userGuess < 1 || userGuess > 10) {
alert("Please enter a number between 1 and 10.");
continue;
}
// Increment the number of attempts
attempts++;
// Check if the guess is correct
if (userGuess === targetNumber) {
guessedCorrectly = true;
alert("Congratulations! You guessed the correct number.");
} else {
if (attempts < maxAttempts) {
alert(`Incorrect. You have ${maxAttempts - attempts} guesses left.`);
} else {
alert(`Sorry, you're out of guesses. The correct number was ${targetNumber}.`);
}
}
}