...

View Full Version : Number-Guesser Script?



Hashim1
12-28-2010, 08:57 PM
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:



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



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

Old Pedant
12-28-2010, 09:57 PM
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.

Hashim1
12-28-2010, 10:13 PM
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.

Old Pedant
12-28-2010, 10:21 PM
??? 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...

Hashim1
12-28-2010, 10:34 PM
??? I still don't see any HTML in that post???

The HTML is there at the bottom of the main 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...

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. :o

Old Pedant
12-28-2010, 11:03 PM
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.

Hashim1
12-28-2010, 11:13 PM
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. :confused: I'll post that bit of code tomorrow so you can see what I mean. Right now, sleep calls. *insert-snoring-smiley-here*

Old Pedant
12-28-2010, 11:37 PM
Okay:


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

Hashim1
12-29-2010, 02:30 PM
Okay:


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. :confused:

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



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

Philip M
12-29-2010, 04:28 PM
The function giveUp() should advise the number to be guessed:-


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...."

Hashim1
12-29-2010, 04:50 PM
The function giveUp() should advise the number to be guessed:-


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. :o

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. :)

Hashim1
12-29-2010, 05:39 PM
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. :)


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:


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. :)

devnull69
12-29-2010, 05:57 PM
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 :)

Hashim1
12-29-2010, 09:34 PM
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?

Old Pedant
12-29-2010, 09:37 PM
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.

Hashim1
12-29-2010, 09:55 PM
Also, in the current script, every time an incorrect guess is made, the amount of tries used is increased and shown in the "tries" text field in form1. How would I modify the script for it to show the output somewhere else on the page instead, inside a div or something, rather than in a text field? This is so I can enlarge the text and place it to the right of the screen, making it more easily noticeable to anyone playing the game.

How would I go about doing that?

Hashim1
12-29-2010, 09:57 PM
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()?



Exactly what it should do. It shows the alert message that I set:

"Please enter a variable between 1 and 100."

:confused:



And the return there in the Guess() function has NOTHING WHATSOEVER to do with the reload that is in the GiveUp() function.

No, you misunderstood my question. I was just asking generally, what are the true and return statements for, and in which sort of situations would I use them?

Old Pedant
12-29-2010, 10:12 PM
I guess that makes sense. What happens is that when you compare "xyz" to 100, it changes the 100 to "100" and of course "xyz" *IS* greater than "100" when both are considered as strings.

***********

true is just what you expect: It's a boolean value that is the opposite of false. Most of the time, you don't really need to use the keyword. That is, doing if ( foo ) ... where foo is a true/false value is the same as doing if ( foo == true ) ... so why bother with the true? But there are occasions where it's useful.

return means "stop doing ANYTHING in the current function! quit right now and exit this function. Do not pass GO. Do not collect $200." But it can also be use to return a value from a function: return 17;

Really, you should read up more on JS. Find a good tutorial. Don't try to run (write complex programs) before you have learned to crawl (written dozens of little 5 to 10 line examples, for your own edification).

Old Pedant
12-29-2010, 10:16 PM
To put a value into a <div> or <span> or whatever, just give an ID to the element:
<div id="tries"></div> and then do
document.getElementById("tries").innerHTML = tries;

But, you know, you *can* make an <input> field have any appearance you want to give it, using styles. And especially for a readonly field, this is a fine way to display data:


<input name="tries" readonly style="border: none; margin-left: 300px; font-size: xx-large; color: red;" />

Or put all that into a <style> and then use a class in the <input>.

Hashim1
12-29-2010, 11:04 PM
I guess that makes sense. What happens is that when you compare "xyz" to 100, it changes the 100 to "100" and of course "xyz" *IS* greater than "100" when both are considered as strings.

So to conclude, it would be fine to use either then? :)


But, you know, you *can* make an <input> field have any appearance you want to give it, using styles.

I understand that you can, but I want to get experience with doing it via Javascript, in case I ever need it.

document.getElementById("tries").innerHTML = tries;

So, where would I input the text that I want to write into the div/span?

---

And yes, you're right, I do need a good Javascript tutorial/book, but can't seem to come across a simple one that I can make sense of. I'd appreciate it a lot if you could recommend me one or two.

Hashim1
12-29-2010, 11:17 PM
So, where would I input the text that I want to write into the div/span?

Never mind, figured that out for myself at least. :o

Old Pedant
12-29-2010, 11:58 PM
> So to conclude, it would be fine to use either then?

Theoretically or practically??

I guarantee you that in the future you will come across situations where you *WILL* need to use parseInt( ) or parseFloat( ) [same idea as parseInt but gets a floating point number...that is a any kind of number, not just integers]. You might as well get used to using them now.

********

Have you looked at this page?
http://www.codingforums.com/showthread.php?t=17254

It's the third permanent post in this forum, always at the top of the page.

Hashim1
12-30-2010, 11:52 AM
> So to conclude, it would be fine to use either then?

Theoretically or practically??

I guarantee you that in the future you will come across situations where you *WILL* need to use parseInt( ) or parseFloat( ) [same idea as parseInt but gets a floating point number...that is a any kind of number, not just integers]. You might as well get used to using them now.


Good point. And thanks for the link, I never saw the thread before for some reason, but checking out a good tutorial on JS now. :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum