Member Avatar for HTMLperson5

Hi guys, I was making a text based game in javascript..
Here it is:

<!doctype html>

<script type="text/javascript">
//Experimental Code - Text Based RPG
function error() {
alert(+choice+ "is not a recognised command")
maingame()
}
function maingame() {
choice = prompt('You find yourself in a dark room...do you\n[1]Eat cheese\n[2]Do stuff')
if (choice==2) {
next()
} else {
error()
}
}

</script>
<body onload="javascript: maingame()">
</html>

Ok. And here is the faulty part of the code (if you could not find it above)

function error() {
alert(+choice+ "is not a recognised command")
maingame()
}

It should give an alert box returning "foo is not a recognised command." but instead i get "NaNis is not a recognised command"

What am I doing wrong!?

You have a plus sign on either side of choice. But on the left side there's no left operand for addition. So the left plus is interpreted as the unary plus operator (which is the opposite of the unary minus (negation) and basically does nothing on numeric operands). Like most numeric operations, the unary plus operator converts its argument to a number. So if choice is not a valid number, you will get NaN.

If you don't want choice to be converted to a number, you should remove the left plus from your call to alert.

PS: You should avoid using global variables like you have in your code and instead make choice a local variable that you pass to error as a parameter.

Member Avatar for HTMLperson5

Thanks, I got the code to work using your advice

<!doctype html>

<script type="text/javascript">
//Experimental Code - Text Based RPG
function error() {
alert(choice+ "is not a recognised command")
maingame()
}
function maingame() {
choice = prompt('You find yourself in a dark room...do you\n[1]Eat cheese\n[2]Do stuff')
if (choice==2) {
next()
} else {
error()
}
}

</script>
<body onload="javascript: maingame()">
</html>

So "NaN" (i am assuming) stands for "Not a Number"

Yes, it does.

PS: Your error function shouldn't be calling maingame() back. This infinite recursion will eventually lead to a stackoverflow error if error is called often enough (though admittedly the user would have to enter invalid input a lot of times before this happens). You should use loops instead.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.