使用while循环和无限猜测在javascript中猜测游戏

时间:2016-10-24 13:24:34

标签: javascript arrays loops while-loop

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之间的数字。每次用户猜测时,他们都会得到四个提示之一。然后在最后,当他们猜对了,他们会被告知他们花了多少猜测。我真的被困了,请帮帮忙。

1 个答案:

答案 0 :(得分:2)

如何开始..

  • 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!';
}