我怎么能将div映射到二维数组tictactoe游戏

时间:2017-08-14 15:05:44

标签: javascript jquery html css

我有一个Tic-tac-toe游戏,我想用二维数组实现。现在我使用一个简单的数组,它工作正常。但我认为使用二维数组实现会更容易,因此在检查获胜者和其他事情时我可以利用for循环。

我的问题是我可以找到一种方法从div点击到两个昏暗数组中的索引。例如,如果用户单击UI上第二行的第3行,我该如何将其映射到2Darray[1][2](第二个子阵列索引2)?谢谢。

希望我能很好地解释这一点。对于那些有兴趣查看代码的人来说,我的代码是tic-tac-toe:https://codepen.io/zentech/pen/xLRzGr



var xPlayer = "X";
var oPlayer = "O";
var turn = "X";
var board = new Array(9);
var message = document.getElementById("message");

$(document).ready(function() {
  $(".square").click(function() {
    var sqrId = $(this).attr("id");
    playerMove(sqrId);
    if (checkWinners()) {
      message.innerHTML = "Message: " + turn + " Wins!";
      return;
    }
    if (checkBoard()) {
      message.innerTHML = "Message: " + turn + " move";
    } else {
      message.innerHTML = "Message: It's a draw!";
    }
    turn = (turn == 'X') ? 'O' : 'X';
  });

  $(".resetGame").click(function() {
    $(".square").text("");
    $("#message").text("Message: ");
    turn = "X";
    board = new Array(9);
  });
});

//getting user move and output to board
function playerMove(sqrId) {
  console.log("player move: " + $('#' + sqrId).attr("id") + " " + turn);
  if ($('#' + sqrId).text() == "") {
    $('#' + sqrId).text(turn);
    board[sqrId] = turn;
  } else {
    console.log("error!");
    message.innerHTML = "Message: Wrong move!..."
    return;
  }
}

//checking for winning combinations
function checkWinners() {
  console.log(board[1]);
  //checking rows
  if (board[0] != undefined && board[0] == board[1] && board[1] == board[2]) {
    return true;
  } else if (board[3] != undefined && board[3] == board[4] && board[4] == board[5]) {
    return true;
  } else if (board[6] != undefined && board[6] == board[7] && board[7] == board[8]) {
    return true;
  }

  //checking columns
  else if (board[0] != undefined && board[0] == board[3] && board[6] == board[8]) {
    return true;
  } else if (board[1] != undefined && board[1] == board[4] && board[4] == board[7]) {
    return true;
  } else if (board[2] != undefined && board[2] == board[5] && board[5] == board[8]) {
    return true;
  }

  //checking across
  else if (board[0] != undefined && board[0] == board[4] && board[4] == board[8]) {
    return true;
  } else if (board[2] != undefined && board[2] == board[4] && board[4] == board[6]) {
    return true;
  } else {
    return false;
  }
}

/* checking if there's more room to play, if not 
   then it's a draw'*/
function checkBoard() {
  for (var i = 0; i < board.length; i++) {
    // console.log(board[i]);
    if (board[i] == undefined) {
      return true;
    }
  }
  return false;
}
&#13;
body {
  background-color: #999;
  font-family: serif, verdana;
}

h1 {
  font-size: 50px;
}

h2 {
  margin-bottom: 30px;
}

.container {
  margin: 0 auto;
  text-align: center;
}

.row>div {
  margin: 2px;
  border: solid 1px black;
  display: inline-block;
  font-size: 35px;
  width: 50px;
  height: 50px;
  text-align: center;
  padding: 0px;
  vertical-align: top;
  line-height: 50px;
}

#message {
  /* display: inline-block; */
  text-align: center;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="header">
    <h1>TicTacToe</h1>
    <h2>You're playing against the computer!</h2>
  </div>
  <div class="ticTacToe">
    <div class="row">
      <div id="0" class="square"></div>
      <div id="1" class="square"></div>
      <div id="2" class="square"></div>
    </div>
    <div class="row">
      <div id="3" class="square"></div>
      <div id="4" class="square"></div>
      <div id="5" class="square"></div>
    </div>
    <div class="row">
      <div id="6" class="square"></div>
      <div id="7" class="square"></div>
      <div id="8" class="square"></div>
    </div>
  </div>
  <div class="controls">
    <h2 id="message">Message:</h2>
    <a href="#" class="resetGame">
      <h3>Reset Game</h3
    </a>
  </div>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

要从1d索引转到2d坐标,您可以使用这些&#34;公式&#34;:

要从行和列返回到1d索引,您可以使用:

  • index = row * ROW_SIZE + col

&#13;
&#13;
/* Indexes go from left to right (row), rows go top to bottom

    [ 
      0, 1, 2
      3, 4, 5
      6, 7, 8
    ]

*/

const ROW_SIZE = 3;

const rowForIndex = function(index) {
  return Math.floor(index / ROW_SIZE);
}

const columnForIndex = function(index) {
  return index % ROW_SIZE;
}

console.log([0,1,2,3,4,5,6,7,8].map(
  i => `index: ${i}, row: ${rowForIndex(i)}, col: ${columnForIndex(i)}`)
);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用您的DOM结构,这应该有效:

var field = new Array(3).fill(new Array(3)), width = field.length;
function div2coords(div) {
    var id = parseInt(div.id);
    return {
        x: id % width,
        y: Math.floor(id / width)
    };
}
function coords2div(coords) {
    var id = coords.y * width + coords.x;
    return document.getElementById(id.toString());
}

答案 2 :(得分:0)

如果你想要现代和想象,你可以使用data- attributes

所以你的标记看起来像:

  <div class="ticTacToe">
    <div class="row">
      <div data-x="0" data-y="0" class="square"></div>
      <div data-x="1" data-y="0" class="square"></div>
      <div data-x="2" data-y="0" class="square"></div>
    </div>
    <div class="row">
      <div data-x="0" data-y="1" class="square"></div>
      <div data-x="1" data-y="1" class="square"></div>
      <div data-x="2" data-y="1" class="square"></div>
    </div>
    <div class="row">
      <div data-x="0" data-y="2" class="square"></div>
      <div data-x="1" data-y="2" class="square"></div>
      <div data-x="2" data-y="2" class="square"></div>
    </div>
  </div>

使用dataset属性

可以轻松访问这些内容
var x = this.dataset.x;
var y = this.dataset.y;

或者使用jQuery:

var x = $(this).data('x');