...

View Full Version : Help with random number Game



ryukenblaze
02-07-2009, 05:54 PM
Im creating a random number game w/ javascript, but it keeps going into either an infinite loop or no loop at all. could someone please help here is my code:
<script type = "text/javascript">
<!--
// variables used to test the state of the game
var numberToGuess = 0,
latestGuess = 9999,
result,
numOne;



numberToGuess = randomNum
while (numberToGuess != latestGuess){
result= window.prompt(
"Enter a number", "0");

latestGuess = parseInt( result );
if (latestGuess = numberToGuess )
alert("CONGRATULATIONS, reload to restart");
else
if (latestGuess > numberToGuess)
alert("to high");
else
if (latestGuess < numberToGuess)
alert("to low");
}

function randomNum()
{


numOne=Math.floor ( 1 + Math.random() * 1000);

return numOne
}
// -->
</script>

gun5
02-07-2009, 06:35 PM
You forgot to call the randomNum function:



var latestGuess = 9999;
var result;
var numberToGuess = randomNum();
//document.title = numberToGuess;
while (numberToGuess != latestGuess){
result= window.prompt("Enter a number", 5);
latestGuess = parseInt(result);
if (latestGuess == numberToGuess ){
alert("CONGRATULATIONS, reload to restart");
}else{
if (latestGuess > numberToGuess){
alert("to high");
}else{
if (latestGuess < numberToGuess){
alert("to low");
}
}
}
}
function randomNum(){
var numOne=Math.floor ( 1 + Math.random() * 1000);
return numOne
}

Philip M
02-07-2009, 06:37 PM
A good many errors, I fear. You need to have a look at the use of () brackets and {} braces.

Try this (and learn from it, please!)


<script type = "text/javascript">

function playGame() {
// variables used to test the state of the game
var numberToGuess = 0;
var latestGuess = 0;
var numberToGuess = Math.floor (1 + Math.random() * 100);

while (numberToGuess != latestGuess){
var latestGuess = window.prompt("Enter a number", "");
if (latestGuess == null) {
alert ("Goodbye!");
return false; // end if "Cancel" button pressed
}

latestGuess = parseInt(latestGuess);

if (isNaN(latestGuess)) {
alert ("Invalid entry - you must enter a number");
}
if (latestGuess == numberToGuess ) {
alert("CONGRATULATIONS, reload to restart");
return false;
}
if (latestGuess > numberToGuess) {
alert("Too high - try again");
}
if (latestGuess < numberToGuess) {
alert("Too low - try again");
}

}
}

playGame()
</script>


"In the beginner's mind there are many possibilities, but in the expert's mind there are few” - Shunryu Suzuki (Japanese Zen priest, ?-1971)

MrEnder
02-08-2009, 03:04 AM
Your guys tabbing makes me cry :( sooo hard to read badly tabbed coding ><

ryukenblaze
02-10-2009, 05:44 AM
Thanks everyone for the help. Im a noob, so expect more bad code from me in the future



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum