var x = Math.floor(Math.random() * 100) + 1;
var hint = 'Guess my number, 1-100!';
var userIsGuessing = true;
while (userIsGuessing) {
var guess = prompt(hint + ' Keep guessing!');
userIsGuessing++;
if (guess < x && (x - guess) < 15) hint += ' A little too small!';
else if (guess < x && (x - guess) >= 15) hint += ' Way too small!';
else if (guess > x && (x - guess) < 15) hint += ' A little too big!';
else if (guess > x && (x - guess) >= 15) hint += ' Way too big!';
else(guess === x); {
document.writeln("You win! It took you" + userIsGuessing + " times to
guess the number.
");
}
}
我正在尝试获取此代码,要求用户猜测1到100之间的数字。每次用户猜测时,他们都会得到四个提示之一。然后最后,当他们正确猜出时,他们会被告知他们花了多少次猜测。我真的被困住了,请帮忙。
最佳答案
如何开始userIsGuessing
是布尔值,切勿在其上使用++。
您在写文档赢得用户,您应该警告它,就像提示一样,但是还可以。
不要增加您的提示,人体工程学是可怕的。
查看评论
var x = Math.floor(Math.random() * 100) + 1;
var hint = 'Guess my number, 1-100!';
var userIsGuessing = false; // Boolean, begin at false
var count = 0; // Will count the try of the users
while (!userIsGuessing) {
var guess = prompt(hint + ' Keep guessing!'); count++; // We increment count
if(guess == x) { // CHECK IF RIGHT FIRST. EVER FOR THIS KIND OF STUFF.
userIsGuessing = true; // If right, then the Boolean come true and our loop will end.
alert("You win! It took you" + count + " times to guess the number.");
}
if (guess < x && (x - guess) < 15) hint = ' A little too small!';
else if (guess < x && (x - guess) >= 15) hint = ' Way too small!';
else if (guess > x && (x - guess) < 15) hint = ' A little too big!';
else if (guess > x && (x - guess) >= 15) hint = ' Way too big!';
}
关于javascript - 使用while循环和无限猜测的JavaScript猜游戏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40219646/