我正在创建一个“高级”井字游戏,其中每个回合在 10 秒后消失(即:放置的每个 X 或 O 在 10 秒后恢复为空白方块)。这一切都很好,但是如果用户决定取消当前游戏并开始新游戏,就会出现问题。
如果用户开始一个新游戏并点击一个先前被占用的方格,超时功能将根据前一次游戏的点击清除该方格——即在不到 10 秒内。
使用 clearTimeout 重置最近的计时器实例的计时器,但如果在用户重置游戏板时选择了多个方块,则无济于事。而且因为 setTimeout 在 onclick 函数中应用于每个 X 和 O,所以我没有办法跟踪多个实例 ID。
任何想法将不胜感激,代码如下。
编辑:您可以在此处查看游戏的实时版本(WIP):http: //kylechadha.com/projects/tic-tac-toe/
全局变量:
var elements = document.getElementsByClassName('cell');
var rows = document.getElementsByClassName('row');
var alternate = 0;
var counter = 0;
var timerX; // Handles setTimeout instances for 'X'
var timerO; // Handles setTimeout instances for 'O'
设置 X 和 O 的函数:
var play = function() {
for (i = 0; i < elements.length; i++) {
elements[i].onclick = function () {
if (this.className[0] == "c" && win == false) {
if (alternate % 2 == 0) {
this.className = "xmove";
alternate++;
counter++;
var paramPass = this;
timerX = setTimeout(function() {disappear(paramPass);}, 10000) // Handles ID of most recent instance of setTimeout for 'X'
} else {
this.className = "omove";
alternate++;
counter++;
var paramPass = this;
timerO = setTimeout(function() {disappear(paramPass);}, 10000) // Handles ID of most recent instance of setTimeout for 'O'
}
}
position(this);
analysis();
}
}
}
用户点击“新游戏”时的重置功能:
var reset = function() {
header[0].innerHTML = "Tic Tac Toe";
for (i = 0; i < rows.length; i++) {
for (j = 1; j < 6; j += 2) {
rows[i].childNodes[j].className = "cell animated bounceIn";
}
}
clearTimeout(timerX); // Clears Timeout for most recent instance (last 'X' clicked) before the game was reset
clearTimeout(timerO); // Clears Timeout for most recent instance (last 'O' clicked) before the game was reset
board = [["","",""],["","",""],["","",""]];
counter = 0;
alternate = 0;
win = false;
}