Hello and welcome to our community! Is this your first visit?
AdSlot7
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Number Guessing game

1. ## Number Guessing game

Hello!

So, here is my problem.

I have to write a number-guessing game that prompts the visitor to guess the right number in a maximum of 4 attempts. If the visitor guesses the target number within 4 tries, I want to write an alert that congratulates them as well as indicates the number of tries taken.

If they guess incorrectly, I want to prompt with "Try again."

And I finally want to keep track of each number they typed with a document.write.

I have something like this, but its just not working out:

Code:
```<script type="text/javascript">

var count = "" ;

if (count >=0 && count <=88) {

for (i=1; i<=4; i++) {
count = prompt("I'm thinking of a number between 0-88. Can you guess it?", "");
document.write("Guess #" + i + ":" + count + "<br />");

}}
else if (count>88){
alert("Too high!")
}
else if (count=55){
alert("Congratulations, you guessed it in " + i + " tries!)
}
else{
alert ("Guess again!")
}

</script>```
Thank you for your time.

2. AdSlot6
3. Code:
`alert("Congratulations, you guessed it in " + i + " tries!`"`);`
and
Code:
`else if (count=55){`
Should be
Code:
`else if (count == 55){`
I know it does not fix it but its a start

You should do the if's based on the prompt reply. Your hung up in the loop.

4. Use the error console

5. Have a look at this, and learn from it.

Code:
```<html>
<head>
</head>
<body onload = "guessNum()">

<script type = "text/javascript">

function guessNum() {
var theNumber = 55;
var tries = 4;
var message = "";

for (var i =1; i <= tries; i++) {
var guess = parseInt(prompt("Please enter your guess number " + i + " in range 0 - 88",""));
while ((isNaN(guess)) || (guess <0) || (guess>88)) {alert ("Invalid Value!"); guess = parseInt(prompt("Invalid value entered!  Please enter your guess number " + i + " in range 0-88",""))}

if (guess == theNumber) {
i = tries;
message = "Well done! The number " + theNumber + " was correct!"
}
else if (i < tries) {
message = "No.  Try again.";
}
else {
message = ("You failed to guess the number correctly after " + tries + " tries.");
}

alert (message)

document.getElementById("theMessage").innerHTML = message;

}

}

</script>

<br><br><br>
<span id = "theMessage"></span>

</body>
</html>```

You should note that document.write() statements must be run before the page finishes loading. Any document.write() statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page (including the Javascript which called it). So document.write() is at best really only useful to write the original content of your page. It cannot be used to update the content of your page after that page has loaded.

Prompt() is also a primitive method of getting data from the user. I find that there is a bug in IE which prevents .innerHTML text being displayed in a <span> while a prompt box is active.

As Logic Ali says, you should use your error console to identify syntax errors.

"A man would do nothing, if he waited until he could do it so well that no one at all would find fault with what he has done." - Cardinal Newman

6. ## Users who have thanked Philip M for this post:

HungryChapstick (03-31-2012)

7. Ah. Thank you. This helped a lot, and I see where I was making a lot of mistakes. I am new to this, so your insight is much appreciated.

I was messing around with it, and I do have a few questions:

Say the user guessed correctly in their 1st or 2nd attempt, how would you get it to write, for example, "You guessed correctly on your 2nd attempt?"

And for that matter, would there be a way to to keep track of their previous guesses in the inner HTML?

Thank you.

8. Originally Posted by HungryChapstick
Say the user guessed correctly in their 1st or 2nd attempt, how would you get it to write, for example, "You guessed correctly on your 2nd attempt?"
Code:
```if (guess == theNumber) {
var arr = ["", "first", "second", "third", "fourth"];  // note that the zeroth element of the array is blank.
message = "Well done! The number " + theNumber + " was correct!  This was your " + arr[i] + " attempt.";
i = tries;
}```
I think you should solve the second question yourself, as you will only learn by doing things for yourself, rather than getting others to do your homework for you, but a hint is message += whatever which appends the new value to the existing value.

9. ## Users who have thanked Philip M for this post:

HungryChapstick (03-31-2012)

10. Thank you very much for the help.

I always at the very least attempt my homework. This was an extra "see if you can" assignment, and I just couldn't get it. I am not very skilled at this, but I try, and I do want to learn.

What you have shown me has helped me tremendously.

Thanks again!

11. Haha.

How in the world did you know to put the i = tries after the message ="". If its flipped, it always says 4th attempt. Why does that change make a difference, if you don't mind my barrage of questions?

12. Originally Posted by HungryChapstick
Haha.

How in the world did you know to put the i = tries after the message ="". If its flipped, it always says 4th attempt. Why does that change make a difference, if you don't mind my barrage of questions?
You should try to work thse things out for yourself.

If i = tries is placed before the message then i takes the value of 4. So it will always say fourth attempt. Note that tries is the number of tries allowed (a constant - 4), not the number of tries made so far which is the value of the variable i.

13. Originally Posted by HungryChapstick
Say the user guessed correctly in their 1st or 2nd attempt, how would you get it to write, for example, "You guessed correctly on your 2nd attempt?"
If you use an array like this
Originally Posted by Philip M
Code:
`var arr = ["", "first", "second", "third", "fourth"];`
then if you want to change the max allowed num. of guesses, you will have to edit the array as well as the variable containing the max allowed guesses

This example tells the user if each guess if too high/low or correct and on which guess without using arrays.

Code:
```        <p>Previous guesses:</p>
<p id="prevGuesses"></p>
<p>Total number of guesses: <span id="numGuesses"></span></p>
<div>
<button id="btnNewGame">New game</button>
</div>

<script>
document.getElementById('btnNewGame').onclick=startGame;
var prevGuessObj = document.getElementById('prevGuesses');
var numGuessesObj = document.getElementById('numGuesses');
var maxGuesses = 4;
function startGame(){
isGuessCorrect = false;
prevGuessObj.innerHTML = '';
numGuessesObj.innerHTML = '';
corrNum = Math.floor(Math.random()*10);
numGuesses = 0;
do{
var guessNum = getGuess();
if(guessNum != null){
numGuessesObj.innerHTML  = ++numGuesses;
if(guessNum < corrNum){
prevGuessObj.innerHTML += 'Guess '+numGuesses+': '+ guessNum +' is too low <br />';
} else if(guessNum > corrNum){
prevGuessObj.innerHTML += 'Guess '+numGuesses+': '+ guessNum +' is too high <br />';
} else {
prevGuessObj.innerHTML += 'Guess '+numGuesses+': '+ guessNum +' is CORRECT!!';
isGuessCorrect = true;
}
}
}while(!isGuessCorrect && numGuesses < maxGuesses && guessNum != null)
}
function getGuess(){
do{
var guess = window.prompt('Guess a number','');
if(guess == null){return null;}
guess = parseFloat(guess);
}while(isNaN(guess))
return guess;
}
</script>```
Instead of a window.prompt() for the guesses I would normally have an input textbox though.

14. The OP asked for "You guessed correctly on your 2nd attempt". In other words, ordinal numbers. You code gives cardinal numbers, so not a correct solution.

15. Originally Posted by Philip M
You code gives cardinal numbers, so not a correct solution.
I think the op can decide for him/her self if the example I posted is correct, useful or whatever to them. I doubt they need you to decide for them

You can create ordinal numbers without an array.

16. Originally Posted by Mishu
I think the op can decide for him/her self if the example I posted is correct, useful or whatever to them. I doubt they need you to decide for them
No, bullant/webdev1958/Mishu, if you post code which is not what the OP requested then you say it is up to the OP to decide. But if anyone else improves your code in some way you say that that was not what the OP requested. The truth is simply that you just love generating an argument. See your doctor right away!

17. Originally Posted by Philip M
But if anyone else improves your code in some way you say that that was not what the OP requested.
I don't recall ever having said that.

Can you post a link to a post where you say I said that.

18. Originally Posted by Mishu
I don't recall ever having said that.

Can you post a link to a post where you say I said that.
Not offhand. I waste as little time as possible on you.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•
AdSlot4
AdSlot5