DavidK DavidK - 3 months ago 9
Javascript Question

Why is this else statement printing every time?

I'm making a simple text game. For some reason when I input the correct text the else text will always be output, along with the correct output text. The else text should only be displayed if incorrect text is input. What am I doing wrong?

//take commands
if (input == "text 1" && currentroom == "area_1")
$("<p>reply 1.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
else if (input == "text 1" && "currentroom" != "area_1")
$("<p>reply 2.</p>").hide().insertBefore("#placeholder").fadeIn(1000);


//got to room
if (input == "go to area 2" && "currentroom" == "area_1") {
currentroom = "area_outside";
$("<p>You are now in area 2.</p>");
} else if (input == "go to area 2" && "currentroom" != "area_1")
$("<p>You cant go that way.</p>").hide().insertBefore("#placeholder").fadeIn(1000);

if (input == "go to area 1" && "currentroom" == "area_2") {
currentroom = "area_outside";
$("<p>You are back in area 1.</p>")
} else { //invaild commands/dont understand.
$("<p>"+input+" is not vaild. type help for vaild commands.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}

Answer

Your else at the end is only connected to this if:

if (input == "go to area 1" && "currentroom" == "area_2")

So if input == "go to area 1" is false or "currentroom" == "area_2" is false (which it always will be), your else code will be run.

You probably meant that to be

if (input == "go to area 1" && currentroom == "area_2")
// No quotes ------------------^----------^

there and in a couple of other places, and you may or may not want to use else if in a couple of places you've used if.

So perhaps:

if (input == "text 1" && currentroom == "area_1") {
    $("<p>reply 1.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
else if (input == "text 1" && currentroom != "area_1") {
    $("<p>reply 2.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
else if (input == "go to area 2" && currentroom == "area_1") {
    currentroom = "area_outside";
    $("<p>You are now  in area 2.</p>")
}
else if (input == "go to area 2" && currentroom != "area_1") {
    $("<p>You cant go that way.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
else if (input == "go to area 1" && currentroom == "area_2") {
    currentroom = "area_outside";
    $("<p>You are back in area 1.</p>")
}
else {
    //invaild commands/dont understand.
    $("<p>" + input + " is not vaild. type help for vaild commands.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}

...although you may be able to refactor that a bit.

Comments