类型错误:未定义

时间:2016-11-08 01:43:33

标签: javascript

我正在进行一个tic tac toe游戏,虽然游戏功能正常,当一个玩家获胜时,如果他们使用某些空间获胜,调试器会弹出。我收到一个类型错误,说“' O'不能设置未定义。同样在我的控制台中,当玩家通过仅点击某些空格获胜时,将为elementIndex输出负数。

在我的game.win函数中似乎来自这一行:

game.winCombos[elementIndex][unitIndex] = game.currentPlayerTurn;



var gameboard = {

  initialize: function() {
    for (var x = 0; x < 3; x++) {
      for (var y = 0; y < 3; y++) {
        var unit = $("<div class='unit'></div>");
        unit.appendTo('#gameboard');
      }
    }
    console.log(100);
    gameboard.addId();
  },

  addId: function() {
    var id = 1
    $('.unit').each(function() {
      $(this).attr('id', id);
      id++;
    });
  }
};

var players = {

  firstPlayer: {
    token: 'X'
  },
  secondPlayer: {
    token: 'O'
  }
};

var game = {

    newGame: function() {
      game.winCombos = game.clone();
      game.currentPlayerTurn = players.firstPlayer.token;
      gameboard.initialize();
      game.displayToken();
    },

    currentPlayerTurn: players.firstPlayer.token,

    displayToken: function() {
      $('.unit').click(function() {
        if (game.currentPlayerTurn === 'X' && !$(this).hasClass('selected')) {
          $(this).addClass('selected').removeClass('unit').text("X");
          game.currentPlayerTurn = players.secondPlayer.token;
        } else if (game.currentPlayerTurn === 'O' && !$(this).hasClass('selected')) {
          $(this).addClass('selected').removeClass('unit').text("O");
          game.currentPlayerTurn = players.firstPlayer.token;
        }
        game.win($(this));
      })
    },

    win: function(div) {

      game.winCombos.forEach(function(element) {
        element.forEach(function(unitIndex) {
          if (unitIndex.toString() === div.attr('id').toString()) {
            var elementIndex = game.winCombos.indexOf(element);
            var unitIndex = element.indexOf(unitIndex);
            game.winCombos[elementIndex][unitIndex] = game.currentPlayerTurn;
          }
        })

        var counter = 0

        for (var i = 0; i < element.length; i++) {
          if (element[i] === game.currentPlayerTurn) {
            counter++;
          }

          if (counter === 3) {
            counter = 0;
            game.gameOver(true);

          }

        }
      })
    },

    gameOver: function(bool) {
      if (bool === undefined) {
        bool = false;
      }
      $('.unit').remove();
      $('.selected').remove();
      game.newGame();
    },

    winCombos: [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
      [1, 4, 7],
      [2, 5, 8],
      [3, 6, 9],
      [1, 5, 9],
      [3, 5, 7]
    ],

    clone: function() {
      return [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
        [1, 4, 7],
        [2, 5, 8],
        [3, 6, 9],
        [1, 5, 9],
        [3, 5, 7]
      ]
    }
&#13;
&#13;
&#13;

0 个答案:

没有答案