Javascript tic-tac-toe获胜者检查

时间:2016-11-18 12:46:22

标签: javascript jquery function variables

tic tac toe的代码:

$(".square").one("click", function() { 
if( gameOver == false ) {
 sq1 = $("#sq1").text(); // grabs the value of squares after being clicked.
 sq2 = $("#sq2").text(); 
 //same for all 9 squares
}

//To check winner : (Result is same but code is broken into statements to avoid length.)
function checkWinner() {
if(  sq1 != emptyStr && (sq1 == sq2 && sq2 == sq3) ) { //emptyStr = ""
    winner = 1; //Testing purposes
    //alert(winner);
}

else if( sq1 != emptyStr &&  (sq1 == sq4 && sq4 == sq7) ) {
    winner = 1;
    //alert(winner);
}

我的问题是..我应该如何调用checkWinner函数。是应该在每次点击时调用还是应该使用setInterval?

第二个问题:如果我在控制台中运行checkWinner并且条件为真,那么在额外点击之后,获胜者将变为1 而不是同时进行。

编辑:@sra要求的代码:

//2 buttons( x and o)
$("#x").on("click", function() {
  gameOver = false;
  player = 1;
  $("#o").attr("disabled","disabled");
})

$("#o").on("click", function() {
  gameOver = false;
  player = 2;
  $("#x").attr("disabled","disabled");
})

(使用相同的关键字检查其他问题,但找不到我的答案)

P.S。仍然是JavaScript的新手,所以请随意提供代码改进建议和编辑!

1 个答案:

答案 0 :(得分:1)

只要发生点击,您就应该完全检查。这是当你需要评估新的状态(是否有胜利者?,游戏是否以平局结束?)。

为了保持实际的匹配逻辑小一点,我会做这样的事情:

didPlayerWin = function(player) {
  sq1 = $("#sq1").text() == player;
  sq2 = $("#sq2").text() == player;
  sq3 = $("#sq3").text() == player;
  // ... for all the squares

  sq1 && sq2 && sq3 ||
  sq4 && sq5 && sq6 ||
  sq7 && sq8 && sq9 ||
  // ... for all the possible wins
}

$(".square").on("click", function() {
  if (didPlayerWin("x")) {
    alert("x rockz!");
  } else if (didPlayerWin("o")) {
    alert("o rockz!");
  } else {
    // check if all the squares are filled
  }
}

对于问题的第二部分(您需要额外点击以评估获胜者),我认为当您检查获胜者时,用户点击的实际DOM元素尚未更新为新值。那么什么时候将点击的DOM Elements文本设置为“x”或“o”?你也可以发布那段代码吗?