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 23
  1. #1
    Regular Coder
    Join Date
    Dec 2010
    Location
    Sheffield, UK
    Posts
    138
    Thanks
    81
    Thanked 1 Time in 1 Post

    Number-Guesser Script?

    Hey there. Firstly, I am a total beginner to Javascript. I know basic HTML and some CSS, but Javascript seriously confuzzles me; even just basic stuff like calling functions. :S I've joint this forum in the hope of learning more about Javascript and how to use it properly, in terms of writing my own code, etc.

    My problem is this. I've come across this number-guessing script:

    Code:
    <script language="javascript" type="text/javascript">
    
    var num = Math.floor(Math.random() * 100) + 1;
    
    var tries = 0;
    
    function Guess() {
    var g = document.form1.guess1.value;
    
    tries++;
    
    document.form1.tries.value = tries + "/10";
    
    if (g < num)
            document.form1.hint.value = "Nope, try guessing higher.";
    
    if (g > num)
            document.form1.hint.value = "Nope, try guessing lower.";
    
    if (g == num) {
    	window.alert("Correct! Congratulations, you guessed it in " + tries + " tries.");
    	location.reload();
        }
    
    if (tries == 10) { 
        window.alert("Sorry, you've ran out of guesses! The number was " + num + ".");
    	location.reload();
        }
    
    }
    </script>
    ... which I love. I understand the basics of it. However, I want to try and improve on it. For example, I'd like to implement a Give Up button, so that when you press this button the script reveals the number for you instead (in an alert message) and when this alert message clears, the page is automatically reloaded/cleared and a new game begins.

    Suggestions, also, for how it can be improved and how I can go about doing it, are much appreciated.

    I know it may be a lot to ask, but I am seriously in need of help.

    Here is the HTML by the way:

    Code:
    <html>
    <body>
    <h1>Guess The Number</h1>
    <hr/>
    <p>I'm thinking of a number between 1 and 100. Try to guess it, but be warned - you only have 10 tries!</p>
    <form name="form1">
    <b>Guess:</b>
    <input type="text" name="guess1" size="5" maxlength="3"/>
    <input type="button" value="Guess" onclick="Guess();"/>
    <br/>
    <input type="text" size="25" name="hint" disabled="disabled"/> 
    <br/>
    <b>Tries Used:</b>
    <input type="text" size="4" name="tries" disabled="disabled"/>
    <br/>
    </form>
    </body>
    </html>
    Last edited by Hashim1; 12-28-2010 at 10:18 PM.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,576
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    For starters, create the HTML to go with the JavaScript.

    This script is useless without the correct HTML.

    And the giveup button is trivial once you have the correct HTML for it.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Regular Coder
    Join Date
    Dec 2010
    Location
    Sheffield, UK
    Posts
    138
    Thanks
    81
    Thanked 1 Time in 1 Post
    I created the HTML, but never really thought it would be useful, so didn't include in the original post. Original post has now been edited to include the HTML.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,576
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    ??? I still don't see any HTML in that post???

    Suggestions for improvement of the JS:

    -- Make sure the user really did input a number. Your choice as to whether you want to count a "guess" that doesn't have a number as a "try" or not.

    -- Make sure the number is in the range 1 to 100. Ditto re your choice...
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Hashim1 (12-29-2010)

  • #5
    Regular Coder
    Join Date
    Dec 2010
    Location
    Sheffield, UK
    Posts
    138
    Thanks
    81
    Thanked 1 Time in 1 Post
    Quote Originally Posted by Old Pedant View Post
    ??? I still don't see any HTML in that post???
    The HTML is there at the bottom of the main post.

    Quote Originally Posted by Old Pedant
    Suggestions for improvement of the JS:

    -- Make sure the user really did input a number. Your choice as to whether you want to count a "guess" that doesn't have a number as a "try" or not.

    -- Make sure the number is in the range 1 to 100. Ditto re your choice...
    How would I go about that? Say, if a user didn't enter a valid number, or entered nothing at all in the field, what would be the script to display an alert message telling the user to enter a number?

    Like I said, total noob at javascript.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,576
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    So first question: Is this homework?

    If it is, see www.codingforums.com/rules.htm and especially rule 1.5

    Hints we can give. Answers we can't.

    So...

    A hint or two, for now:

    The builtin function parseInt( ) is the most useful way to check for a valid integer number input. You use it in combination with the isNaN( ) function.

    If you want a "give up" button, just add it to the HTML and link it to a function. Same as Guess button is linked to the Guess() function.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Hashim1 (12-29-2010)

  • #7
    Regular Coder
    Join Date
    Dec 2010
    Location
    Sheffield, UK
    Posts
    138
    Thanks
    81
    Thanked 1 Time in 1 Post
    No, it's not homework.

    I'm 15, studying at home, and currently just studying Javascript out of interest in my spare time. These sort of things interest me.

    Also, full answers would be much appreciated, as they help me to work out what's going a lot more than hints do.

    And I did try using a function and calling to it, but it didn't work for some reason. I'll post that bit of code tomorrow so you can see what I mean. Right now, sleep calls. *insert-snoring-smiley-here*
    Last edited by Hashim1; 12-28-2010 at 11:15 PM.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,576
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    Okay:
    Code:
    function Guess() {
        var g = parseInt( document.form1.guess1.value );
        if ( isNaN(g) || g < 1 || g > 100 )
        {
            alert("You must enter ONLY an integer (whole number) from 1 to 100");
            return; // you would bump "tries" first if you wanted to count this as a try
        }
        ... rest of code same ...
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Hashim1 (12-29-2010)

  • #9
    Regular Coder
    Join Date
    Dec 2010
    Location
    Sheffield, UK
    Posts
    138
    Thanks
    81
    Thanked 1 Time in 1 Post
    Quote Originally Posted by Old Pedant View Post
    Okay:
    Code:
    function Guess() {
        var g = parseInt (document.form1.guess1.value);
        if ( isNaN(g) || g < 1 || g > 100 )
        {
            alert("You must enter ONLY an integer (whole number) from 1 to 100");
            return; // you would bump "tries" first if you wanted to count this as a try
        }
        ... rest of code same ...
    That's great, I'll implement that into the code as soon as I get the chance. A couple of questions, if you don't mind. Firstly, what exactly do the parseInt and isNaN functions do - what other situations can they be used in? And secondly, what do those symbols that I've outlined in red do? I've never seen them used in Javascript before.

    And, as promised, here's the code that I used before to try and implement a Give Up button into the script.

    Code:
    <html>
    <head>
    <script language="javascript" type="text/javascript">
    
    var num = Math.floor(Math.random() * 100) + 1;
    
    var tries = 0;
    
    function Guess() {
    var g = document.form1.guess1.value;
    
    tries++;
    
    document.form1.tries.value = tries + "/10";
    
    if (g < num)
            document.form1.hint.value = "Nope, try guessing higher.";
    
    if (g > num)
            document.form1.hint.value = "Nope, try guessing lower.";
    
    if (g == num) {
    	window.alert("Correct! Congratulations, you guessed it in " + tries + " tries.");
    	location.reload();
        }
    
    if (tries == 10) { 
        window.alert("Sorry, you've ran out of guesses! The number was " + num + ".");
    	location.reload();
        }
    
    }
    
    function GiveUp() {
    	alert("Please enter a valid number between 1 and 100.");
    }
    </script>
    </head>
    
    <body>
    <h1>Guess The Number</h1>
    <hr/>
    <p>I'm thinking of a number between 1 and 100. Try to guess it, but be warned - you only have 10 tries!</p>
    <form name="form1">
    <b>Guess:</b>
    <input type="text" name="guess1" size="5" maxlength="3"/>
    <input type="button" value="Guess" onclick="Guess();"/>
    <br/>
    <input type="text" size="25" name="hint" disabled="disabled"/> 
    <br/>
    <b>Tries Used:</b>
    <input type="text" size="4" name="tries" disabled="disabled"/>
    <br/>
    <input type="button" value="Give Up?" onclick="GiveUp();"/>   
    <br/>
    </form>
    </body>
    </html>
    There's the entire page of code, and highlighted are the parts where I created the function, and then called it using an onClick event handler in the Give Up button. It seems perfectly fine to me, yet it didn't work when I tested it - nothing happens when I click that Give Up button.
    Last edited by Hashim1; 12-29-2010 at 02:33 PM.

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,151
    Thanks
    203
    Thanked 2,548 Times in 2,526 Posts
    The function giveUp() should advise the number to be guessed:-

    Code:
    function GiveUp() {
    alert("The number was " + num);
    window.location.reload(true);  // start again
    }
    You should check out w3schools for basic Javascript syntax.
    parseInt() changes a string value into an integer. All values input by the user are strings initially and if they are to be the subject of a mathematical calculation must be changed to numbers by one of sevral different methods.
    isNaN means is not a number
    var x = "abc"
    if (isNaN(x)) {alert (x + " is not a number")}
    || means or.

    So if ( isNaN(g) || g < 1 || g > 100 )
    means "if the value of g is not a number, or is a number smaller than 1, or is a number greater than 100...."

  • Users who have thanked Philip M for this post:

    Hashim1 (12-29-2010)

  • #11
    Regular Coder
    Join Date
    Dec 2010
    Location
    Sheffield, UK
    Posts
    138
    Thanks
    81
    Thanked 1 Time in 1 Post
    Quote Originally Posted by Philip M View Post
    The function giveUp() should advise the number to be guessed:-

    Code:
    function GiveUp() {
    alert("The number was " + num);
    window.location.reload(true);  // start again
    }
    You should check out w3schools for basic Javascript syntax.
    parseInt() changes a string value into an integer. All values input by the user are strings initially and if they are to be the subject of a mathematical calculation must be changed to numbers by one of sevral different methods.
    isNaN means is not a number
    var x = "abc"
    if (isNaN(x)) {alert (x + " is not a number")}
    || means or.

    So if ( isNaN(g) || g < 1 || g > 100 )
    means "if the value of g is not a number, or is a number smaller than 1, or is a number greater than 100...."
    Ah, my mistake on not including the right text for the GiveUp() function. That text was supposed to go in the alert for the isNaN function. Must have got confused when posting the code onto this forum.

    And thanks for your insightful post, I can honestly say I learned a lot from it. With regards to the GiveUp function, it seems to be working now that I rewrote it, even without those improvements you stated above. Maybe it was just a newbie mistake that I didn't realize. Once again, thanks for that.

    And I also get the ParseInt and isNaN functions now, too. Cheers. Working on those improvements now.

  • #12
    Regular Coder
    Join Date
    Dec 2010
    Location
    Sheffield, UK
    Posts
    138
    Thanks
    81
    Thanked 1 Time in 1 Post
    I have a couple more questions about the script. Don't mean to be annoying or anything, just trying to make sure that I know what I'm doing when I do it and for what reason, to make it easier for myself in future.

    Code:
    function Guess() {
        var g = parseInt (document.form1.guess1.value);
        if ( isNaN(g) || g < 1 || g > 100 )
        {
            alert("Please enter a valid number between 1 to 100.");
            return; // you would bump "tries" first if you wanted to count this as a try
        }
    There's the improved Guess function.

    Firstly - you explained what the parseInt() function is for, but what exactly is the use of it in this case, since the script works perfectly, in the exact same way, without it, like this:

    var g = document.form1.guess1.value;

    Secondly, what's the use of the return statement at the end of the above script, and the true statement here:

    Code:
    function GiveUp() {
    alert("The number was " + num);
    window.location.reload(true);  // start again
    }
    I understand what they do with regards to this script, but otherwise, how would they be used and in what situations? Why do you need to use them?

    Thanks again for your great input, and for being patient with me.
    Last edited by Hashim1; 12-29-2010 at 05:45 PM.

  • #13
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    location.reload(true) is supposed to reload the page bypassing the browser cache, so it will be really reloaded from the server

    The "return" will finish the execution of the function at that point and return to the caller function or to the global scope respectively

    The parseInt will ensure that the value of the field will be turned into an integer. Maybe it will work without it, but surely it will work with it

  • #14
    Regular Coder
    Join Date
    Dec 2010
    Location
    Sheffield, UK
    Posts
    138
    Thanks
    81
    Thanked 1 Time in 1 Post
    Quote Originally Posted by devnull69 View Post
    location.reload(true) is supposed to reload the page bypassing the browser cache, so it will be really reloaded from the server

    The "return" will finish the execution of the function at that point and return to the caller function or to the global scope respectively

    The parseInt will ensure that the value of the field will be turned into an integer. Maybe it will work without it, but surely it will work with it
    So, it's basically the same thing? It's up to me whether I use parseInt or not?
    Last edited by Hashim1; 12-29-2010 at 09:51 PM.

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,576
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    Leave the code as var g = document.form1.guess1.value; and then enter "xyz" as your guess.

    What happens?

    Still think it works the same, without the parseInt()?

    ************

    And the return there in the Guess() function has NOTHING WHATSOEVER to do with the reload that is in the GiveUp() function.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Hashim1 (12-29-2010)


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