Leo Leo - 2 years ago 131
HTML Question

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



<title>Computer Guessing Game</title>



<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



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!).

Answer Source

I think you are pretty close to what you want. You can add a variable

var howManyGuesses = 0;

before the while loop, and increment this variable each time you calculate a new random number.

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.");

To prevent it to loop forever you can do something like

var myNumber = document.getElementById("myNumber").value;
if (myNumber < 1 || myNumber > 5) {
    alert('Please insert a number between 1 and 5');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download