首页 > 解决方案 > 如何在 if 语句中添加多个命令?JavaScript

问题描述

我觉得这个实例真的很简单,我可能想多了,但是有没有办法可以在我的 if 语句中添加多个语句?我正在寻找类似的东西,如果我在游戏中选择去某个方向,你会得到“你决定去商店。你想探索吗?”这样的文字。并且有两种选择:

-是的,然后在输入框中输入“是”,然后它会给出“探索后,你决定买东西”的结果

-不,你决定离开。

我已经尝试了一个多小时,当我接近时,即使您不在那个位置,该命令仍然可以访问。例如。我的游戏中的位置是,“你在公园。如果在输入框中随机输入,“是”命令将返回,“探索后,你决定买东西”

我想要它,以便如果您在那个特定位置,该代码只能在该位置访问,而在其他任何地方都无法访问。

因此,如果您在公园作为地点并随机输入“是”,则不会发生任何事情,因为您不在商店的位置。

这是我的代码:

...

选择一个方向

<input id = "input" type = "text" placeholder = "Type 'Help1' for actions"/><button onClick = "button()">Confirm Action</button>
<p id = "message"></p>

<script>

  function button() {
    var textInput;
    var newInput = input.value;
    if (newInput == "North") {

      textInput = "you went to the Store. Do you explore?"; // <-- I'd like a way to put in "Yes" as a response which would print out a text saying "You explored the store and bought some food" //

      document.getElementById("message").innerHTML = textInput;

    }


    if (newInput == "North Again") {
      textInput = "you went to the Forest Home";
      document.getElementById("message").innerHTML = textInput;
    }

    if (newInput == "Help1") {
      textInput = "[Page 1 of 2. Type 'Help2' for page 2] Commands you can use: <ul><li>South</li><li>North</li><li>East</li><li>West</li><li>North Again</li><li>South again</li><li>West Again</li><li>East Again</li>";
      document.getElementById("message").innerHTML = textInput;
    }

    if (newInput == "Help2") {
      textInput = "[Page 2 of 2] Commands you can use: <li>North One More</li><li>East Once More</li><li>West Once More</li><li>South Once More</li>";
      document.getElementById("message").innerHTML = textInput;
    }
  }

</script>

</div>

<div id = "stat-box">
  <h2 align = "center">STATS</h2>
</div>

...

标签: javascripthtmlstatements

解决方案


看看状态机结构。您应该将用户的当前状态存储在游戏中,并在每次按下按钮时检查它。

状态机设计模式将检查您的播放器当前所在的位置,并采取相应的行动。

    var state = 'asked_for_direction';
    if (state == 'asked_for_direction' && newInput == "North") {

      textInput = "you went to the Store. Do you explore? (Yes/No)";

      document.getElementById("message").innerHTML = textInput;
      state = 'north';
    }

    if (state == 'north' && newInput == "Yes") {
      textInput = "You explored the store and bought some food";

      document.getElementById("message").innerHTML = textInput;
      state = 'north_explored';
    }

    if (state == 'north' && newInput == "No") {
      textInput = "You decided to leave";

      document.getElementById("message").innerHTML = textInput;
      state = 'asked_for_direction';
    }


    if (state == 'north' && newInput == "North Again") {
      textInput = "you went to the Forest Home";
      document.getElementById("message").innerHTML = textInput;
      state = 'forest_home';
      // Add how many states as you want
    }

我不知道您的游戏的确切结构,但您可以扩展此代码。


推荐阅读