Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

Thread: Help with random number Game

1. Help with random number Game

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 )
else
if (latestGuess > numberToGuess)
else
if (latestGuess < numberToGuess)
}

function randomNum()
{

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

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

• You forgot to call the randomNum function:

Code:
```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 ){
}else{
if (latestGuess > numberToGuess){
}else{
if (latestGuess < numberToGuess){
}
}
}
}
function randomNum(){
var numOne=Math.floor ( 1 + Math.random() * 1000);
return numOne
}```

• Users who have thanked gun5 for this post:

ryukenblaze (02-07-2009)

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

Code:
```<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) {
return false;  // end if "Cancel" button pressed
}

latestGuess = parseInt(latestGuess);

if (isNaN(latestGuess)) {
alert ("Invalid entry - you must enter a number");
}
if (latestGuess == numberToGuess ) {
return false;
}
if (latestGuess > numberToGuess) {
}
if (latestGuess < numberToGuess) {
}

}
}

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)

• Thanks for the help

Thanks everyone for the help. Im a noob, so expect more bad code from me in the future

•