在第0行找到无限循环

时间:2016-07-22 15:09:02

标签: javascript html infinite-loop

我正在尝试制作一个井字游戏,但在Codepen中我的Javascript给了我一个错误,说“在第0行找到了无限循环。行号近似所以仔细看看。”这是笔

请参阅Tic-Tac-Toe上Maris(@spacegeek224)的笔CodePen

这是我的JS:

(function() {
  var PLAYERS = ['X','O'];
  var TURN = PLAYERS[0];
  var BOARD = [new Array(3),new Array(3),new Array(3)];

  function togglePlayer() {
    TURN = (TURN == PLAYERS[0]) ? PLAYERS[1] : PLAYERS[0];
  }

  $('.square').click(function(e) {
    if ($(e.target).attr('data-p')) {

    } else {
      $(e.target).attr('data-p',TURN).text(TURN);

      BOARD[$(e.target).attr('data-y')][$(e.target).attr('data-x')] = TURN;
      if (checkWin(BOARD)) {
        $('.turn').attr('data-p',checkWin(BOARD)).text(checkWin(BOARD) + " wins!");
        $('.square:not([data-p])').attr('data-p',true);
      }
      else {
        togglePlayer();
        $('.turn').attr('data-p',TURN).text(TURN+"\'s turn");
      }    
    }
  });

  function checkWin(board) {
    for (var i = 0;i<3;i++) {
      if (board [0][i] !== undefined) 
        if (board[0][i]==board[1][i] && board[1][i] == board[2][i])
          return board[0][i];
      else if (board [i][0] !== undefined) 
        if (board[i][0]==board[i][1] && board[i][1] == board[i][2])
          return board[i][0];
      else if (board[1][1] !== undefined)
        if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
           return board[1][1];
        else if (board[0][2] == board[1][1] && board[1][1] == board[2][0])
           return board[1][1];
    }
    return false;
  }

  $('.container').on('dblclick',function() {
    $('.square').removeAttr('data-p').text('');
    BOARD = [new Array(3),new Array(3),new Array(3)];
    TURN = PLAYERS[0];
    $('.turn').attr('data-p',TURN).text(TURN+"\'s turn");
  });



})();

1 个答案:

答案 0 :(得分:0)

我想通了,我不敢相信我以前没有看到过这个。在checkWin函数中,我应该在for循环中放置if而不是if else