Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 03-31-2012, 12:10 PM   PM User | #1
HungryChapstick
New to the CF scene

 
Join Date: Feb 2012
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
HungryChapstick is an unknown quantity at this point
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.

Last edited by HungryChapstick; 03-31-2012 at 01:13 PM..
HungryChapstick is offline   Reply With Quote
Old 03-31-2012, 03:25 PM   PM User | #2
sunfighter
Senior Coder

 
Join Date: Jan 2011
Location: Missouri
Posts: 2,382
Thanks: 18
Thanked 350 Times in 349 Posts
sunfighter is on a distinguished road
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.

Last edited by sunfighter; 03-31-2012 at 03:30 PM..
sunfighter is offline   Reply With Quote
Old 03-31-2012, 03:33 PM   PM User | #3
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 959
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
Use the error console
Logic Ali is online now   Reply With Quote
Old 03-31-2012, 04:44 PM   PM User | #4
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,036
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 03-31-2012 at 04:47 PM..
Philip M is offline   Reply With Quote
Users who have thanked Philip M for this post:
HungryChapstick (03-31-2012)
Old 03-31-2012, 05:36 PM   PM User | #5
HungryChapstick
New to the CF scene

 
Join Date: Feb 2012
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
HungryChapstick is an unknown quantity at this point
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.
HungryChapstick is offline   Reply With Quote
Old 03-31-2012, 05:53 PM   PM User | #6
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,036
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by HungryChapstick View Post
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.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 03-31-2012 at 05:59 PM..
Philip M is offline   Reply With Quote
Users who have thanked Philip M for this post:
HungryChapstick (03-31-2012)
Old 03-31-2012, 06:07 PM   PM User | #7
HungryChapstick
New to the CF scene

 
Join Date: Feb 2012
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
HungryChapstick is an unknown quantity at this point
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!
HungryChapstick is offline   Reply With Quote
Old 03-31-2012, 06:21 PM   PM User | #8
HungryChapstick
New to the CF scene

 
Join Date: Feb 2012
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
HungryChapstick is an unknown quantity at this point
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?
HungryChapstick is offline   Reply With Quote
Old 03-31-2012, 06:33 PM   PM User | #9
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,036
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by HungryChapstick View Post
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.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
Philip M is offline   Reply With Quote
Old 04-01-2012, 04:05 AM   PM User | #10
Mishu
Banned

 
Join Date: Mar 2012
Posts: 306
Thanks: 1
Thanked 28 Times in 28 Posts
Mishu can only hope to improve
Quote:
Originally Posted by HungryChapstick View Post
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
Quote:
Originally Posted by Philip M View Post
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.

Last edited by Mishu; 04-01-2012 at 10:19 AM..
Mishu is offline   Reply With Quote
Old 04-01-2012, 09:27 AM   PM User | #11
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,036
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
Philip M is offline   Reply With Quote
Old 04-01-2012, 09:34 AM   PM User | #12
Mishu
Banned

 
Join Date: Mar 2012
Posts: 306
Thanks: 1
Thanked 28 Times in 28 Posts
Mishu can only hope to improve
Quote:
Originally Posted by Philip M View Post
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.

Last edited by Mishu; 04-01-2012 at 09:39 AM..
Mishu is offline   Reply With Quote
Old 04-01-2012, 09:43 AM   PM User | #13
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,036
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by Mishu View Post
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!
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
Philip M is offline   Reply With Quote
Old 04-01-2012, 09:46 AM   PM User | #14
Mishu
Banned

 
Join Date: Mar 2012
Posts: 306
Thanks: 1
Thanked 28 Times in 28 Posts
Mishu can only hope to improve
Quote:
Originally Posted by Philip M View Post
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.
Mishu is offline   Reply With Quote
Old 04-01-2012, 09:48 AM   PM User | #15
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,036
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by Mishu View Post
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.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
Philip M is offline   Reply With Quote
Reply

Bookmarks

Tags
game, guess, javascript, number, problem

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 07:06 PM.


Advertisement
Log in to turn off these ads.