如何使一个函数等待另一个停止执行(西蒙游戏)的JavaScript

时间:2017-12-08 17:22:38

标签: javascript

我正在制作一个西蒙游戏,我已经添加了逻辑,但我不知道如何暂停执行,直到玩家按下了一个牌。我创建了一个名为user()的函数,它记录用户输入并将其推送到userSeq数组。然后我创建了一个函数checkTurn()来检查下一个是谁(计算机或用户)。如果是用户轮到那么我想在else中等待user()功能完成,然后调用callcheckClicks()检查用户的输入是否与计算机相同,然后继续到新的级别。请帮忙!

这是一个链接:https://codepen.io/Teo03/pen/yPvbwY



$(document).ready(function() {
  var green = document.getElementById("green");
  var red = document.getElementById("red");
  var yellow = document.getElementById("yellow");
  var blue = document.getElementById("blue");
  var tile = document.getElementsByClassName("tile");
  //audio for every click
  var audio = [
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"),
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3"),
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"),
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3")
  ];
  // record the round
  var round = 0;
  // record the random presses
  var compSeq = [];
  //record user clicks
  var userSeq = [];
  //if it's false computer moves
  var turn = false;
  //round number
  var round = 0;
  //count how many moves user does
  var playerIndex = 0;

  //start
  $(".start").click(function() {
    round++;
    turn = false;
    $("#round")
      .html("Round: " + round)
      .show();
    $(".start, .reset").hide();
    checkTurn();
  });

  function addNewRandomNumber() {
    var random = Math.floor(Math.random() * 4) + 1;
    computer(random);
    console.log("random" + random);
  }

  // call the computer to make an action
  function callComp() {
    addNewRandomNumber();
    enableClicks();
    turn = true;
    checkTurn();
  }

  function callCheckClicks() {
    checkClicks();
  }

  //check every time the user clicks if the user clicks are the same as the computer's
  function checkClicks() {
    console.log("random clicks: " + compSeq);
    //if user guess is correct
    if (userSeq[playerIndex] == compSeq[playerIndex]) {
      if (userSeq[playerIndex].length == compSeq[playerIndex].length) {
        // if they are then it's computer's turn
        callComp();
      } else {
        playerIndex += 1;
        $(".start")
          .html("Next")
          .show();
        // user is right, he can continue inputting another clicks if the sequence has
        checkTurn();
      }
    } else {
      resetUserVariables(); // user is wrong
    }
  }
  //reset playerIndex
  function resetUserVariables() {
    playerIndex = 0;
  }
  //press a random button
  function computer(ran) {
    switch (ran) {
      case 1:
        blink(green);
        audio[0].play();
        compSeq.push(1);
        break;
      case 2:
        blink(red);
        audio[1].play();
        compSeq.push(2);
        break;
      case 3:
        blink(blue);
        audio[2].play();
        compSeq.push(3);
        break;
      case 4:
        blink(yellow);
        audio[3].play();
        compSeq.push(4);
        break;
      default:
        return;
    }
    console.log("random clicks: " + compSeq);
    enableClicks();
    turn = true;
    checkTurn();
  }
  //blink a tile
  function blink(tile) {
    $(tile).fadeOut("slow", function() {
      $(this).fadeIn("slow", function() {
        return;
      });
    });
  }

  //user input
  function user() {
    if ($(this).is("#green")) {
      userSeq.push(1);
      audio[0].play();
      blink(green);
      playerIndex++;
    } else if ($(this).is("#red")) {
      userSeq.push(2);
      audio[1].play();
      blink(red);
      playerIndex++;
    } else if ($(this).is("#blue")) {
      userSeq.push(3);
      audio[2].play();
      blink(blue);
      playerIndex++;
    } else if ($(this).is("#yellow")) {
      userSeq.push(4);
      audio[3].play();
      blink(yellow);
      playerIndex++;
    }
    turn = false;
    checkTurn();
    console.log("user clicks: " + userSeq);
  }

  //add an event listener for user clicks
  function enableClicks() {
    for (var i = 0; i < tile.length; i++) {
      tile[i].addEventListener("click", user, false);
    }
  }
  //disable clicks when is computer's turn
  function disableClicks() {
    for (var i = 0; i < tile.length; i++) {
      tile[i].removeEventListener("click", user, false);
    }
  }
  //check who's turn is next
  function checkTurn() {
    if (turn === false) {
      //call computer
      callComp();
    } else {
      callCheckClicks();
    }
  }
  //document.ready().
});
&#13;
html * {
  text-align: center;
  background-color: #d3d3d3;
}

h1 {
  font-size: 60px;
  padding-bottom: 10px;
}

h3 {
  display: none;
  padding-bottom: 30px;
}

.circle {
  background: #d3d3d3;
  width: 320px;
  height: 320px;
  border-radius: 50%;
  border: 10px solid gray;
  margin: auto;
}

.tile {
  height: 150px;
  width: 150px;
  float: left;
  cursor: pointer;
}

#red {
  background-color: red;
  border-top-right-radius: 100%;
}

#green {
  background-color: green;
  border-top-left-radius: 100%;
}

#blue {
  background-color: blue;
  border-bottom-right-radius: 100%;
}

#yellow {
  background-color: yellow;
  border-bottom-left-radius: 100%;
}

btn {
  padding-top: 40px;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<h1 class="text-center">Simon Game</h1>
<div class="container text-center">
  <h3 id="round">Round: </h3>
  <div class="circle">
    <div class="tile" onclick="user()" id="green"></div>
    <div class="tile" onclick="user()" id="red"></div>
    <div class="tile" onclick="user()" id="yellow"></div>
    <div class="tile" onclick="user()" id="blue"></div>
  </div>
  <a class="btn start btn-default">Start</a>
  <a class="btn reset btn-default" onclick="reset()">Reset</a>

  <!-- container !-->
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我相信你要找的是setTimeout()

这需要2个参数,你的函数和毫秒数。

例如,如果你想在onc​​lick事件三秒后执行一个函数......

<button onclick="setTimeout(myFunction, 3000);">Try it</button>

<script>
function myFunction() {
    alert('Hello');
}
</script>

然后使用这里解释的承诺: Javascript - Wait the true ending of a function that uses setTimeout

需要注意的另一件事是程序的流程。目前,您使用checkTurn方法调用callCheckClicks方法,该方法再次调用checkClickscheckClicks来电checkTurn。有了这个,你的程序将永远崩溃,因为它不断循环。为此,您需要在if/else中激活checkClicks以获得

turn = true;
checkTurn();

看起来像

function checkClicks() {
  console.log("random clicks: " + compSeq);
  //if user guess is correct
  if (userSeq[playerIndex] == compSeq[playerIndex]) {
    if (userSeq[playerIndex].length == compSeq[playerIndex].length) {
      // if they are then it's computer's turn
      callComp();
    } else {
      playerIndex += 1;
      $(".start")
        .html("Next")
        .show();

      // user is right, he can continue inputting another clicks if the sequence has
      turn=true;

      checkTurn();

    }
  } else {
    resetUserVariables(); // user is wrong
  }
}

希望这是你正在寻找的。