vendredi 29 avril 2016

How to make computer guess a number and return number of guesses (Javascript)?

I'm currently working on a mini-project that I find interesting.

The basic idea is to have the user enter a number between 1 - 5, and have the computer guess that number, showing the number of guesses it took to guess it. Here is my code so far ...

<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>

As you can see, I can not figure out how to make the computer keep guessing the numbers and then print out to the user the number of guesses it took. I think that it's some sort of loop, but then again, I'm not sure.

Any help is appreciated (excuse me if I'm not writing the question clearly enough, I'm quite new to SO and will get better with time!).




Aucun commentaire:

Enregistrer un commentaire