我如何把逻辑操作在Javascript的while循环?



我想创建一个猜谜游戏,你在提示符中选择一个最大的数字,然后输入程序随机生成的数字。

然而,我希望当你按下"q"时,游戏会自动退出。

这是我的代码

let maximum = parseInt(prompt("Enter the maximum number"));

while (!maximum) {
maximum = parseInt(prompt("Please Enter a valid number!"));
}

let targetNum = Math.floor(Math.random() * maximum + 1);
console.log(targetNum)
let guess = parseInt(prompt("Enter your first guess!"));
let attempts = 1;
while(parseInt(guess) !== targetNum  || guess.toString !== "q") {
if (guess > targetNum) {
guess = prompt("too high! Enter a new guess")
}
else {
guess = prompt("too low! Enter a new guess")
attempts++;
}
}
console.log(`You got it! It took you ${attempts} guesses`)

每当我按q,它不工作。有谁能给我解释一下吗?

我把变量放在最上面,使它更干净。我还添加了一个else if,当我输入"q"时,它将打破循环。

let maximum = parseInt(prompt("Enter the maximum number"));
let guess = parseInt(prompt("Enter your first guess!"));
let attempts = 1;
let targetNum = Math.floor(Math.random() * maximum + 1);

while (!maximum) {
maximum = parseInt(prompt("Please Enter a valid number!"));
}
while(parseInt(guess) !== targetNum) {
if (guess > targetNum) {
guess = prompt("too high! Enter a new guess")
attempts++;
}
else if(guess < targetNum){
guess = prompt("too low! Enter a new guess")
attempts++;
}else if(guess == "q"){
break;
}
}
console.log(targetNum)
console.log(`You got it! It took you ${attempts} guesses`)

const guessNumberGame = {
start_  : function(){
let n = prompt( 'Enter the secret number:' );
if( n ){
if ( !isNaN( n ) ){
this.guess_(n);
}else{
alert( 'That is not a valid number!' );
this.start_();
}
}else{
alert( 'Cancel the game!' );
}
},
guess_ : function(n){
const g = prompt( 'guess the number!' );
if( g ){
if ( !isNaN( g ) ){
if( g > n ){
alert( 'Too high!' );
this.guess_(n);
}
else if( g < n ){
alert( 'Too low!' );
this.guess_(n);
}
else{
alert( 'Correct!' );
this.start_();
}
}else{
alert( 'That is not a valid number!' );
this.guess_(n);
}
}else{
this.start_();
}
}
};
guessNumberGame.start_();

相关内容

  • 没有找到相关文章

最新更新