Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 26
  1. #1
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    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.

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    3,763
    Thanks
    23
    Thanked 548 Times in 547 Posts
    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.

  • #3
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Use the error console

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,732
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    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
    Last edited by Philip M; 03-31-2012 at 04:47 PM.

    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.

  • Users who have thanked Philip M for this post:

    HungryChapstick (03-31-2012)

  • #5
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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.

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,732
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    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.
    Last edited by Philip M; 03-31-2012 at 05:59 PM.

    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.

  • Users who have thanked Philip M for this post:

    HungryChapstick (03-31-2012)

  • #7
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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!

  • #8
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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?

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,732
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    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.

  • #10
    Banned
    Join Date
    Mar 2012
    Posts
    306
    Thanks
    1
    Thanked 28 Times in 28 Posts
    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.

  • #11
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,732
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    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.

  • #12
    Banned
    Join Date
    Mar 2012
    Posts
    306
    Thanks
    1
    Thanked 28 Times in 28 Posts
    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.

  • #13
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,732
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    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.

  • #14
    Banned
    Join Date
    Mar 2012
    Posts
    306
    Thanks
    1
    Thanked 28 Times in 28 Posts
    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.

  • #15
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,732
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    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.


  •  
    Page 1 of 2 12 LastLast

    Tags for this Thread

    Posting Permissions

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