I'm trying to learn coding by building a simple text game. The end game is going to have 4 rooms. You'll start in room 1, exit west to room 2, exit south to room 3, and finally exit east in room 4. (clockwise).
Anyway, my starting code is from a YouTube tutorial I found that consists of all if / else if statements. I already see that's terribly inefficient. My question is how do I improve this code?
I'm guessing I should make each room and it's contents an object (ie. Room 1 has a sword in it, so the object would contain the location of the room and the sword). I'm also guessing if I have a monster in a room, he'd be his own object.
My problem is if the above is correct (object) - I don't understand how to use the object once I create it. ie. if the user types "take sword" how do I call the object to do that?
If I'm on the complete wrong track, please point me back in the right direction.
Here's the current code for the first room:
$("form").submit(function() {
var input = $("#commandLine").val();
function check() {
check = true;
}
if (input == "help") {
$("#messageHelp").clone().insertBefore("#placeholder").fadeIn(1000);
check();
}
if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
else if (input != "take sword" && input != "help") {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
$("#commandLine").val("");
});
Ideally, I'd like to eliminate or greatly reduce my need to use if and else if statements for something more efficient.
Aucun commentaire:
Enregistrer un commentaire