用更高效的语句替换if-else-if语句

Replacing if else if statements with something more efficient

本文关键字:语句 替换 if-else-if 高效      更新时间:2023-09-26

我正试图通过构建一个简单的文本游戏来学习编码。最终游戏将有4个房间。您将从1号房间开始,向西出口到2号房间,向南出口到3号房间,最后在4号房间向东出口。(顺时针)。

不管怎样,我的起始代码来自我在YouTube上发现的一个教程,其中包含了所有if/else-if语句。我已经意识到这是非常低效的。我的问题是如何改进此代码?

我想我应该把每个房间和里面的东西都做成一个物体(比如1号房间里有一把剑,所以这个物体会包含房间和剑的位置)。我也在猜测,如果我的房间里有一个怪物,他会是他自己的对象。

我的问题是,如果上面的是正确的(对象)-我不明白一旦我创建了对象,该如何使用它。例如,如果用户键入"take sword",我该如何调用对象来做到这一点?

如果我走错了路,请给我指回正确的方向。

这是第一个房间的当前代码:

$("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("");
});

理想情况下,我希望消除或大大减少使用if和else-if语句来获得更高效的结果。

首先让我们改进if语句中的逻辑,以减少重复条件,看看这能让您走多远:

if (input == "help") {
  $("#messageHelp").clone().insertBefore("#placeholder").fadeIn(1000);
  check();
} else if (input == "take sword") {
  if (currentRoom == "nCorridor") {
    $("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
    check();
  } else {
    $("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
    check();
  }
} else {
  $("<p>I don't understand " + input +  ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}

根据输入确定操作的另一种方法是使用switch,当您获得更多选项时,它可能更有用:

switch (input) {
  case "help":
    $("#messageHelp").clone().insertBefore("#placeholder").fadeIn(1000);
    check();
    break;
  case "take sword":
    if (currentRoom == "nCorridor") {
      $("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
      check();
    } else {
      $("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
      check();
    }
    break;
  default:
    $("<p>I don't understand " + input +  ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}

要继续使用对象来跟踪物品,你可以为剑创建一个对象(现在只有位置):

var sword = {
  room: "nCorridor"
};

在代码中,你可以使用这样的对象:

  if (currentRoom == sword.room) {
    $("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
    check();
  } else {
    $("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
    check();
  }

从那里,您可以向项添加更多属性和方法。例如,这些对象可能有一些方法,可以用来确定可以对它们做什么,比如apple可以吃,但sword不能吃。