Number guessing game

I am trying to make it so that I can have up to 10 guesses on a number chosen by a friend using a text box (input). This is my first go around, but what im trying to have happen is
once a text field is filled out and a link is clicked, the function checkInput will be run, which first converts the input into an integer, then runs guessNumber() if its between 1 & 999
The guessNumber function first makes the first div (with the instructions for the game) dissapear
Then a message shows up telling that the game has started.
a while loop loops around 10 times asking (prompt) for a number, then compares that number (guess) to the other (input) letting the user know if the guess was too big/small, if the guess is correct though a message showing you as the winner is shown.
If all 10 turns have been used (loop is done) a message letting you know you lost and what the number (input) was.

<script>

var turns = 10;
var hint = "Guess a whole number between 1 and 999";
var input = document.getElementById('myNumber').value;
var output = document.getElementById('output');

function checkInput(value) {	 

input = parseInt(input);

if((Input >= 1 || Input <= 999)){
 alert('Enter a whole number between 1 & 999');
} else {
	guessNumber();
}
}
function guessNumber() {
  
    document.getElementById("Introduction").style.display = "none";
  
	output.innerHTML = "<h1>Lets play a game</h1>";
	output.innerHTML = "<ol>";
	
	while (turns > 0) {
		//prompt the other user for a guess
		var guess = prompt(hint +' You have' + turns + 'guesses left.');
		//ensure they entered something
		if (!guess)
		break;
		//convert it to a number
		//guess = parseInt(guess);
		guess = Number(guess);
		
		  if (guess == input) {
			document.write('<p><img src="images/winner.png"></p>');
			turns = 0;
		  } else {
			hint = 'Nope.';
			if (guess < input) 
				output.innerHTML = '<li>Your Number: '+guess+' is too small!</li>';
			if (guess > input) 
				output.innerHTML = "<li>Your Number: "+guess+" is too big!</li>";
			turns--;
		  }
	}
	output.innerHTML = "</ol>";
}
document.write('<p><img src="images/loser.png"><br>The number was'+input+'</p>');

</script>
1 Like

This sounds like a good learning assignment. Keep us updated on how you progress.

1 Like

You might also take a look at http://www.felgall.com/jshom03.htm which presents a similar problem and compares the 20th century approach you are using with how it is done in modern JavaScript.

1 Like

ok,just trying to learn the basics first, then ill try to see how to do it using modern javascript.
So, as of now heres my script

<script>
var output = document.getElementById('output');

function checkInput() {	

 var input = document.getElementById('myNumber').value;

input = parseInt(input);

  if((input <  1) || (input > 999)) { 
 alert('Enter a whole number between 1 & 999');
  } else {
  guessNumber();
  }
}
function guessNumber() {
  
  
    document.getElementById("Introduction").style.display = "none";
        output.style.display = "block ";
  
	output.innerHTML = "<ol>";
	output.innerHTML = "<li></li>";	
    	output.innerHTML = "</ol>";
}
</script>

So I can enter a number into the textbox which converts it into an integer, then runs a check to see if its between 1 and 999.
If it is, then the other function is run (guessNumber()) is run whick makes the div (id=“Introduction”) dissapear and makes the other div (output) appear.and the number 1 be shown.

I can enter in a number fine (33 ) but when I click the link, The introduction div goes away, but the output div still cant be seen and there is no number either.

Am I using output right? Also, am I using innerHTML correctly?

1 Like

The output is better placed where you will be using it. Move the var output line in to the guessNumber function.

The innerHTML should use += for subsequent lines where you want to retain the previous output.

I don’t see anywhere that triggers the checkInput function either. If you have embedded that within the HTML code, that is a bad habit that needs to be improved on.

For example:

var form = document.getElementById("guessNumber");
form.onsubmit = checkInput;
1 Like

Thanks… changed the script

<script>
var button = document.getElementById("guessNumber");

button.onclick = checkInput;

function checkInput() {	

var input = document.getElementById('myNumber').value;

input = parseInt(input);

if((input <  1) || (input > 999) || (isNaN(input))) { 
 alert('Enter a whole number between 1 & 999');
} else {
  guessNumber();
}
}
function guessNumber() {
  
var output = document.getElementById('output');
  
    document.getElementById("Introduction").style.display = "none";
    document.getElementById('intro').style.display = "block";

	output.innerHTML = "<ol>";
	output.innerHTML += "<li>";
    	output.innerHTML += "</ol>";
}
</script>

Since its a link (not a form) I used the onclick event. I didn’t know you can call a function without ()s

But when I enter 25 (valid) this is the result


I dont understand why a 1 isn’t shown in the bullets place, it looks like the generated source code is

  1. but why is n’t it
    , wouldnt that show the number?

    got the number to show by doing this

    		document.getElementById('output').innerHTML = "<ol id='guesses'>";
    	document.getElementById('guesses').innerHTML = "<li>";
    


    But now how do I add more

  2. s to the list?

  3. ok, redid a few things in the script (thanks for walking me through it)

    <script>
    
    var turns = 10;
    var hint = "Guess a whole number between 1 and 999";
    var button = document.getElementById("guessNumber");
    
    button.onclick = checkInput;
    
    function checkInput() {	
    
    var input = document.getElementById('myNumber').value;
    
    input = parseInt(input);
    
    if((input <  1) || (input > 999) || (isNaN(input))) { 
     alert('Enter a whole number between 1 & 999');
    } else {
      guessNumber();
    }
    }
    function guessNumber() {
    
    var input = document.getElementById('myNumber').value;
    
        document.getElementById("Introduction").style.display = "none";
        document.getElementById('intro').style.display = "block";
    
    	document.getElementById('output').innerHTML = "<ol id='guesses'>";
    
    		do {
    		//prompt the other user for a guess
    		var guess = prompt(hint +' You have ' + turns + ' guesses left.');
    		//ensure they entered something
    		if (!guess)
    		break;
    		//convert it to a number
    		//guess = parseInt(guess);
    		guess = Number(guess);
    		
    		  if (guess == input) {
    			document.getElementById('guesses').innerHTML = '<p><img src="images/winner.png"></p>';
    			turns = 0;
    		  } else {
    			hint = 'Nope.';
    			if (guess < input) 
    				document.getElementById('guesses').innerHTML += '<li>Your Number: <b>'+guess+'</b> is too small!</li>';
    			if (guess > input) 
    				document.getElementById('guesses').innerHTML += "<li>Your Number: <b>"+guess+"</b> is too big!</li>";
    			turns--;
    		  }
    		} while (turns > 0) 
    	output.innerHTML += "</ol>";
    	if (turns = 0) document.getElementById('guesses').innerHTML = '<p><img src="images/loser.png"><br>The number was'+input+'</p>';
    }
    
    Everything seems sort of ok except that when 10 guesses are made, a loser image is supposed to pop-up, but nothing happens ![|690x388](upload://pLOs31phWkI7SoU1mjMDwscvAuB.png)

    heres what happens when a winner is guessed


    the do…while loop seems to be good, but why doesn’t the last if statement seem to work, shouldn’t it fire if there are 0 turns left?

    1 Like

    after you set turns to 0 it will always be false for the if test.

    im just trying to figure out how change the innerHTML of a div when turns is 0 and the full do…while loop is run (10 times.

    do {
    ...
    ....
    
    } while (turns > 0) 
    

    how do I know I reached the end of the loop then?

    the statement after the end of the loop will run.

    To test for turns equal to zero use (turns === 0)

    1 Like

    it works, heres the script

    <script>
    var turns = 10;
    var hint = "Guess a whole number between 1 and 999";
    var button = document.getElementById("guessNumber");
    
    button.onclick = checkInput;
    
    function checkInput() {	
    
    var input = document.getElementById('myNumber').value;
    
    input = parseInt(input);
    
    if((input <  1) || (input > 999) || (isNaN(input))) { 
     alert('Enter a whole number between 1 & 999');
    } else {
      guessNumber();
    }
    }
    function guessNumber() {
    
    var input = document.getElementById('myNumber').value;
    
        document.getElementById("Introduction").style.display = "none";
        document.getElementById('intro').style.display = "block";
    
    	document.getElementById('output').innerHTML = "<ol id='guesses'>";
    
    		do {
    		//prompt the other user for a guess
    		var guess = prompt(hint +' You have ' + turns + ' guesses left.');
    		//ensure they entered something
    		if (!guess)
    		break;
    		//convert it to a number
    		//guess = parseInt(guess);
    		guess = Number(guess);
    		
    		  if (guess == input) {
    			document.getElementById('guesses').innerHTML = '<p><img src="images/winner.png"></p>';
    			turns = 0;
    		  } else {
    			hint = 'Nope.';
    			if (guess < input) 
    				document.getElementById('guesses').innerHTML += '<li>Your Number: <b>'+guess+'</b> is too small!</li>';
    			if (guess > input) 
    				document.getElementById('guesses').innerHTML += "<li>Your Number: <b>"+guess+"</b> is too big!</li>";
    			turns--;
    		  }
    		} while (turns > 0) 
    	output.innerHTML += "</ol>";
    	if (turns ==  0) document.getElementById('guesses').innerHTML = '<p><img src="images/loser.png"><h2>The number was <span>'+input+'</span></h2>';
    }
    </script>
    

    But I have a few questions though, why why do I need the same variable (input) in both functions? and is that ok how I use the turns variable?

    1 Like

    Can I see the HTML/CSS you are using?

    sure, heres the whole thing…

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Assignment #5: Number Guessing Game</title>
    </head>
    <body>
    <div id="Introduction">
        <input type="text" id="myNumber" placeholder="Please Enter a Whole Number (1-999)">
        <a href="#" id="guessNumber">Start guessing!</a>
    </div>
    <h1 id="intro" style="display:none">Lets Play A Number Guessing Game!!!</h1>
    <div id="output">
    </div>
    <script>
    
    var turns = 10;
    var hint = "Guess a whole number between 1 and 999";
    var button = document.getElementById("guessNumber");
    
    button.onclick = checkInput;
    
    function checkInput() {	
    
    var input = document.getElementById('myNumber').value;
    
    input = parseInt(input);
    
    if((input <  1) || (input > 999) || (isNaN(input))) { 
     alert('Enter a whole number between 1 & 999');
    } else {
      guessNumber();
    }
    }
    function guessNumber() {
    
    var input = document.getElementById('myNumber').value;
    
        document.getElementById("Introduction").style.display = "none";
        document.getElementById('intro').style.display = "block";
    
    	document.getElementById('output').innerHTML = "<ol id='guesses'>";
    
    		do {
    		//prompt the other user for a guess
    		var guess = prompt(hint +' You have ' + turns + ' guesses left.');
    		//ensure they entered something
    		if (!guess)
    		break;
    		//convert it to a number
    		//guess = parseInt(guess);
    		guess = Number(guess);
    		
    		  if (guess == input) {
    			document.getElementById('guesses').innerHTML = '<p><img src="images/winner.png"></p>';
    			turns = 0;
    		  } else {
    			hint = 'Nope.';
    			if (guess < input) 
    				document.getElementById('guesses').innerHTML += '<li>Your Number: <b>'+guess+'</b> is too small!</li>';
    			if (guess > input) 
    				document.getElementById('guesses').innerHTML += "<li>Your Number: <b>"+guess+"</b> is too big!</li>";
    			turns--;
    		  }
    		} while (turns > 0) 
    	output.innerHTML += "</ol>";
    	if (turns ==  0) document.getElementById('guesses').innerHTML = '<p><img src="images/loser.png"><h2>The number was <span>'+input+'</span></h2>';
    }
    </script>
    </body>
    </html>
    

    but now the while loop seems messed, the same result seems to happen when I choose the number, and when I use all my turns

    			do {
    		...
    		...       
    		  if (guess == input) {
    			document.getElementById('guesses').innerHTML = '<p><img src="images/winner.png"></p><h2 id="winner">You Won!!!</h2>';
    turns = 0;
    			...}
    		} while (turns > 0) 
    	if (turns ==  0) document.getElementById('guesses').innerHTML = '<p><img src="images/loser.png"></p><h2 id="loser">The number was <span>'+input+'</span></h2>';
    

    I thought turns = 0 and turns == 0 were two separate things though

    I can’t see where your code has gone wrong - its about a decade since I looked at such old ways of doing things and my browser has the old debugging dialogs turned off as I no longer use alert confirm and prompt for debugging so I can’t even try testing your code.

    This particular task shouldn’t need any loops. You would just count the turns when the event to process a guess is triggered.

    This sounds like a good opportunity to refactor the code, as a demonstration of how this makes the code easier to understand.

    Alrighty then. Good work Luke. I bet you’ve learned a lot from writing this game so far. I consolidated and styled some of your code to come up with the following. It’s probably not where you want it to be but may be a step closer.

    <!DOCTYPE HTML>
    <html>
    
    <head>
      <meta charset="utf-8">
      <title>Assignment #5: Number Guessing Game</title>
      <style>
        #messageBox {
          text-align: center;
          background-color: yellow;
          min-height: 4em;
          border: 1px black solid;
          padding: 1%;
          width: 50%;
          margin: auto;
        }
        
        #myNumber {
          font-size: 150%;
          width: 4em;
          margin: 25px auto;
        }
        
        #output {
          min-height: 1em;
          /*border:1px solid black;*/
          width: 50%;
          margin: 25px auto;
          font-size: 150%;
          padding: 2%;
        }
        
        #inputDiv {
          width: 50%;
          margin: 1em auto;
          border: 1px solid black;
          text-align: center;
          font-size: 250%;
          padding: 1%;
          background-color: orangered;
        }
      </style>
    </head>
    
    <body>
      <div id="messageBox"></div>
      <div id="inputDiv">
        <label for="myNumber">Please Enter a Whole Number (1-999) </label>
        <input type="text" id="myNumber" min="1" max="999" autofocus onKeyUp="if(this.value>999){this.value='999';}else if(this.value<0){this.value='1';}">
      </div>
      <div id="output"></div>
    
      <script>
        var turns = 10;
        var answer = Math.floor(Math.random() * 999) + 1;
        var messageBox = document.getElementById("messageBox");
        var inputBox = document.getElementById('myNumber');
    
        messageBox.innerHTML = "<h1>Guess My Number</h1>Guess a whole number between 1 and 999.<br>You have " + turns + " tries.<br>Good Luck!";
    
        myNumber.addEventListener("change", function(e) {
          guessNumber(inputBox.value);
          inputBox.value = '';
        });
    
        function guessNumber(val) {
          var guess = val;
          if (--turns === 0) loser();
          messageBox.innerHTML = answer + '<br>You guessed: ' + guess + '<br>You have ' + turns + ' guesses left.';
          checkNum(answer, guess);
    
          function checkNum(answer, guess) {
            var result = "";
            if (guess == answer) result = "<h1>YOU WIN!</h1>";
            else result = 'Your Number: <b>' + guess + '</b> is too ' + (guess < answer ? "small" : "big") + "<br>";
    
            output.innerHTML += result;
          }
    
          function winner() {
            output.innerHTML += "YOU WIN!";
          }
    
          function loser() {
            //messageBox.innerHTML = '<p><img src="images/loser.png"><h2>The number was <span>' + input + '</span></h2>';
            output.innerHTML += "YOU LOST";
          }
    
        }
      </script>
    </body>
    
    </html>
    
    1 Like

    That solution is working,but the assignment asks me to use a loop to control the guesses.
    I must’ve screwed up something.as I tried to make it better
    I made it a form, so onnce its submitted, the checkInput function is run
    heres everything, everything seems to work but I think I screwed up my while loop.
    After I make 10 (wrong) guesses, im trying to get the error to display,

    document.getElementById('output').innerHTML = '<p><img src="images/loser.png"></p><h2 id="loser">The number was <span>'+input+'</span></h2>';
    

    but wasn’t sure how to test if turns = 0 so I tried to check it by =, ==, === with the same result
    If One of my guesses is right, the form shows up instead of my (winner) message
    And after 10 guesses, the form shows up instead of my (loser) message
    when I check the console to see if I have any errors, I only get

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <title>Assignment #5: Number Guessing Game</title>
    </head>
    <body>
    <h1>Lets Play A Number Guessing Game!!!</h1>
    <form id="Numbers">
        <input type="text" id="myNumber" placeholder="Please Enter a Whole Number (1-999)">
        <input type="submit" value="Start Guessing!">
    </form>
    <div id="output">
    </div>
    <script>
    
    var turns = 10;
    var hint = "Guess a whole number between 1 and 999";
    var button = document.getElementById("guessNumber");
    
    Numbers.onsubmit = checkInput;
    
    function checkInput() {	
    
    var input = document.getElementById('myNumber').value;
    
    input = parseInt(input);
    
     if((input <  1) || (input > 999) || (isNaN(input))) { 
     alert('Enter a whole number between 1 & 999');
     } else {
      guessNumber();
    }
    }
    function guessNumber() {
    
    var input = document.getElementById('myNumber').value;
    
        document.getElementById("Numbers").style.display = "none";
    
    	document.getElementById('output').innerHTML = "<ol id='guesses'>";
    
    		do {
    		//prompt the other user for a guess
    		var guess = prompt(hint +' You have ' + turns + ' guesses left.');
    		//ensure they entered something
    		if (!guess)
    		break;
    		//convert it to a number
    		//guess = parseInt(guess);
    		guess = Number(guess);
    		
    		  if (guess == input) {
    			document.getElementById('output').innerHTML = '<p><img src="images/winner.png"></p><h2 id="winner">You Won!!!</h2>';
    			turns = 0;
    		  } else {
    			hint = 'Nope.';
    			if (guess < input) 
    				document.getElementById('guesses').innerHTML += '<li>Your Number: <b>'+guess+'</b> is too small!</li>';
    			if (guess > input) 
    				document.getElementById('guesses').innerHTML += "<li>Your Number: <b>"+guess+"</b> is too big!</li>";
    			turns--;
    		  }
    		} while (turns > 0) 
    	output.innerHTML += "</ol>";
    	if (turns =  0) document.getElementById('output').innerHTML = '<p><img src="images/loser.png"></p><h2 id="loser">The number was <span>'+input+'</span></h2>';
    }
    </script>
    </body>
    </html>
    

    its at
    http://fixmysite.us/Web_Programming_With_Javascriipt/Assignment5

    So the problem is that the loser image is not appearing?

    If that’s the problem then check your line 67:

    > if (turns = 0) document.getElementById('output').innerHTML = '<p><img src="images/loser.png"></p><h2 id="loser">The number was <span>'+input+'</span></h2>';

    if (turns = 0) should be: if (turns == 0)
    Also, check that there is an images subfolder and that it has a loser.png in it.

    The loser image is showing, but it resets back to the actual HTML so quickly that you don’t see the image.

    1 Like