0

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

Edited by HTMLperson5: Bad code

2
Contributors
3
Replies
9
Views
5 Years
Discussion Span
Last Post by sepp2k
0

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.

0

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"

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.