TIC TAC TOE javascript

时间:2015-11-28 20:51:49

标签: javascript jquery angularjs

创造一个tic tac toe游戏。我正在尝试阅读tic tac toe的列和行来检查谁赢了。我正在使用$scope.checkResults()来获取列和行并将它们传递到allTheSame函数中以检查值是否相等而哪些不起作用。 这是codepen链接。 http://codepen.io/theMugician/pen/ojJrRp

var app = angular.module("ticTacToe", []);
app.controller("MainCtrl", function($scope){
  var cell = $(".square");
  $scope.player = "";
  $scope.AI = "";
  // changed special chars to X and O as the if statement failed.
  var cross = "✖";
  var circle = "◯";

  /*** Choose a shape ***/
  $scope.choosePlayer = function(e) {
  $scope.player = $(e.currentTarget).text();
        $('.choose').css('top', '-2000px');
        $('#wrapper').css('top', '-600px');
        $('#wrapper').css('opacity', '1');
    //these if statements failed before (AI was always empty)
    if($scope.player === cross){
    $scope.AI = circle;
    }else if($scope.player === circle){
    $scope.AI = cross;
  }
}

  /*** Shape Cells ***/
  $scope.cells = [ { value: '' }, { value: '' }, { value: '' }, 
     { value: '' }, { value: '' }, { value: '' } ,
    { value: '' }, { value: '' }, { value: '' }  
  ];
  // made a ref to scope cells
  $scope.emptyCells = $scope.cells;

  /*** Make a move ***/
  $scope.move = function(cell){
    cell.value = $scope.player;
    var round = 0;
    /*** AI makes a move ***/
    while(round < 1){
     // filtered to get only available cells (for performance)
      $scope.emptyCells = $scope.cells.filter(function(cell){
        return cell.value === '';
      });
      // got random cell according to empty cells
      var randomCell =  $scope.emptyCells[Math.floor((Math.random()*($scope.emptyCells.length-1))+1)];
      if(randomCell.value === "" ){
      randomCell.value = $scope.AI;
      round = 1;
      }else{
        round = 0;
      } 
    }
  $scope.checkResults();
  };

  //checks if values are the same
  function allthesame(arr){
    var L= arr.length-1;
    while(L){
        if(arr[L--]!==arr[L]) return false;
    }
    alert(arr[L].value + "is the winner");
}

  //checks Columns and rows
  $scope.checkResults = function(){
    var allCells = $scope.cells;
    // check rows
     var cellRows = [];
    while(allCells > 0){
      cellRows.push(allCells.splice(0,3));
    }
      for(var i = 0; i < cellRows.length; i++){
        allTheSame(cellRows[i]);
      }
    // check columns
       var cellCols = [];
         while(allCells > 0){
          cellCols.push(allCells.splice(0));
          cellCols.push(allCells.splice(3));
          cellCols.push(allCells.splice(6));
      }
      while(cellCols > 0){
      cellCols.push(cellCols.splice(0,3));
    }
      for(var i = 0; i < cellCols.length; i++){
        allTheSame(cellCols[i]);
      }
  }

$scope.reset = function(){
  $scope.cells = [ { value: '' }, { value: '' }, { value: '' }, 
     { value: '' }, { value: '' }, { value: '' } ,
    { value: '' }, { value: '' }, { value: '' }  
  ];
}
});

4 个答案:

答案 0 :(得分:2)

所以你有一个包含9个值的数组,需要比较8个可能的获胜排列,3个垂直,3个水平和2个对角线。对于“获胜”组合的跟随列表的数组迭代可能是你想要做的

{0,1,2}
{3,4,5}
{6,7,8}
{0,3,6}
{1,4,7}
{2,5,8}
{0,4,8}
{2,4,6}

我刚出门,我可以稍后发布一些代码,但我认为将此列表保存为您的单元格的比较项可能是更简单的方法。

以下是我快速抓取的参考文章:这应该很容易转换为javascript:http://www.codeproject.com/Articles/2400/Tic-Tac-Toe-in-C

答案 1 :(得分:0)

使用Frodo的建议我想出了一个比以前更简单的解决方案。

我将所有获胜组合存储到一个数组中。然后我检查了每个获胜的组合,看看该组合中每个单元格的值是否匹配。就这么简单。

var winningNums = [
    [0,1,2],
    [3,4,5],
    [6,7,8],
    [0,3,6],
    [1,4,7],
    [2,5,8],
    [0,4,8],
    [2,4,6]
   ];


  //checks if values are the same
  $scope.checkResults = function(){
    var allCells = $scope.cells;
    for(var i = 0; i < winningNums.length; i++){
        var a = winningNums[i][0],b=winningNums[i][1],c=winningNums[i][2];
        var cell1 = allCells[a].value, cell2 = allCells[b].value, cell3 = allCells[c].value;
      if(cell1 == "" || cell2 == "" || cell3 == "" ){
        break;
      }
        if(cell1 === cell2 && cell2 === cell3 ){
            var winnerDiv = "<div><h1>" + cell1 + " is the winner</h1></div>";
          $(
"#wrapper").append(winnerDiv);
        }

      }

  }

答案 2 :(得分:0)

此答案不使用 jQuery

使用类似于上面??答案中显示的数组,我们可以使用几种不同的数组方法:

const WINNING_INDICES = [
  [0, 1, 2],
  [0, 3, 6],
  [0, 4, 8],
  [1, 4, 7],
  [2, 5, 8],
  [2, 4, 6],
  [3, 4, 5],
  [6, 7, 8],
];

function check4Winner(board, letter) {
  return WINNING_INDICES.some(winningIndices =>
    winningIndices.every(winningIndex => board[winningIndex] === letter),
  );
}

console.log(check4Winner(['X', 'O', 'O', 'X', 'O', 'X', 'X', '', '']), "X");

在这里,我传入了一个平面阵列的硬编码板。它代表井字棋盘上的九个方格。

总而言之,我们想看看是否至少有一个实例 (some),其中 {{1} 的给定 元素 (winningIndices) 的所有索引},与WINNING_INDICES一起使用时,匹配给定的字母(board)。

答案 3 :(得分:0)

这只是我的代码的功能,以确定谁在游戏中获胜。我还在代码中使用了获胜组合号码。

      var i = -1;
      var WinnerChecker = setInterval(() =>{
      var p1 = 0, p2 = 0;
      i = i<TileCombos.length ? ++i : 0
      for(let j = 0; j<3; j++){
          if(player[TileCombos[i][j]].innerHTML == chk[0].innerHTML){
                  p1 += 1;
         }
           if(player[TileCombos[i][j]].innerHTML == chk[1].innerHTML){
                  p2 += 1;
         }
      }
      if(p1 == 3){
        console.log('PLAYER 1 WON');
      }
      if(p2 == 3){
        console.log('PLAYER 2 WON');
      }    

      })