如何让计算机猜一个数字并返回猜测数(Javascript)?

时间:2016-04-30 01:24:02

标签: javascript html css loops web

我正在研究一个我感兴趣的迷你项目。

基本思路是让用户输入1到5之间的数字,并让计算机猜出该数字,显示猜测它所需的猜测次数。 到目前为止,这是我的代码......

<html>

<head>

    <title>Computer Guessing Game</title>


</head>


    <body>

        <p>How many fingers are you holding up?</p>

        <input type = "text" id= "myNumber">

        <button id="guess">Guess!</button>

        <script type="text/javascript">

            document.getElementById("guess").onclick = function() {

            var myNumber = document.getElementById("myNumber").value;

            var gotIt = false; 

            while (gotIt == false) { 

                var guess = Math.random();

                guess = guess * 6;

                guess = Math.floor(guess);

                if (guess == myNumber) {

                    gotIt = true; 

                    alert ("Got it! It was a " + guess + ". It took me " + /*number of guesses */ + " guesses.");

                } else {

                    //computer should keep randomly guessing until it guessed correctly
                }
            }   
        }

        </script>

    </body>

正如您所看到的,我无法弄清楚如何让计算机继续猜测数字,然后向用户打印猜测的数量。我认为这是某种循环,但话又说回来,我不确定。

任何帮助都表示赞赏(对不起,如果我没有清楚地写出这个问题,我对SO很新,随着时间的推移会变得更好!)。

1 个答案:

答案 0 :(得分:2)

我认为你非常接近你想要的东西。您可以添加变量

var howManyGuesses = 0;
在while循环之前

,并在每次计算新的随机数时递增此变量。

while(gotIt == false){
    howManyGuesses = howManyGuesses  + 1; //increment the amount of guesses
    //your logic
    alert ("Got it! It was a " + guess + ". It took me " + howManyGuesses  + " guesses.");
}

为了防止它永远循环,您可以执行类似

的操作
var myNumber = document.getElementById("myNumber").value;
if (myNumber < 1 || myNumber > 5) {
    alert('Please insert a number between 1 and 5');
    return;
}