Javascript tic-tac-toe计时器

时间:2016-11-06 22:31:58

标签: javascript

我正在制作一个井字游戏,我被提议制作一个计数器,该计数器会说明需要花多少时间才能采取行动。让我们说10秒。如何制作在后台运行并在每次移动时重置的计时器,或者停止游戏让一个没有及时移动的人变得更加宽松? 继承人我的HTML:

x([2.4 3.4])

这是javascript / jquery:

x(3.4)

2 个答案:

答案 0 :(得分:1)

你可以这样做:

定义超时全局参考

var timeoutReference;

转弯的开始/改变

// the previous player made his move on time, clear his timeout
clearTimeout(timeoutReference);
// set a new timeout for the new player
timeoutReference = setTimeout(function(player) {
    return function() { setLose(player); }
}(currentPlayer), 10000);

其中currentPlayer是十字形或圆形,setLose是调用的函数,用于处理过早结束游戏并显示玩家输入丢失而其他玩家获胜。

setTimeout中,我们使用了一个闭包来保持玩家在函数范围内超时后丢失的引用。

答案 1 :(得分:1)

我实施了一款非常无聊的游戏,展示了如何实现这一目标。您需要注意的主要事情是跟踪setTimeout的返回值。此值应用于取消当前超时(使用clearTimeout),您希望每次玩家移动或游戏暂停或停止时都要执行此操作。



"use strict";

var timer;
var button;
var timeLeft;
var label;

function countdown() {
  if (timeLeft) {
    label.innerHTML = timeLeft;
    timeLeft--;
    timer = setTimeout(countdown, 1000);
  } else {
    label.innerHTML = "Fail";
    timer = undefined;
  }
}

function takeMove() {
  // timer will only be undefined if the game is not started
  if (typeof(timer) === "undefined") {
    button.innerHTML = "Move";
    timeLeft = 10;
    countdown();
  } else {
    clearTimeout(timer);
    timeLeft = 10;
    countdown();
  }
}

function init() {
  button = document.getElementById("move");
  label = document.getElementById("label");
  button.addEventListener("click", takeMove);
}

document.addEventListener("DOMContentLoaded", init, false);

<div id="game-board">
  <button id="move">Start</button>
</div>
<div id="output">
  Time left: <span id="label"><span>
</div>
&#13;
&#13;
&#13;

相关问题