0

I'm trying to make a tic-tac-toe game in JavaScript. I'm currently trying to compare an array in an object to a possible win combination and I'm unsure where I'm going wrong.

I'm planning to compare gameboard to an array of arrays that contain possible win combinations.

const tiles = document.querySelectorAll('.tile');
const _gameBoardObj = {
  gameboard: ["", "", "", "", "", "", "", "", ""],
};

function renderBoard() {
  for (i = 0; i < _gameBoardObj.gameboard.length; i++) {
    for (i = 0, max = tiles.length; i < max; i++) {
      if (_gameBoardObj.gameboard[i] === 0) {
        tiles[i].textContent = "O";
      } else if (_gameBoardObj.gameboard[i] === 1) {
        tiles[i].textContent = "X";
      } else {
        tiles[i].textContent = "";
      }
    }
  }
}

function chooseTile() {
  tiles.forEach((tile, index) => {
    tile.addEventListener('click', () => {
      if (_gameBoardObj.gameboard[index] == "") {
        _gameBoardObj.gameboard[index] = 1;
        renderBoard();
        checkGameOver();
      }

    })
  })
}

function checkGameOver() {
  if (_gameBoardObj.gameboard == [1, 1, 1, "", "", "", "", "", ""]) {
    alert("Game Over")
  }
}
chooseTile()
.board {
  display: grid;
  grid-template-columns: auto auto auto;
  padding: 10px;
  width: 300px;
  height: 300px;
}

.tile {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  font-size: 30px;
  text-align: center;
}
<div class="board">
  <div class="tile one" id="0">
  </div>
  <div class="tile two" id="1">
  </div>
  <div class="tile three" id="2">
  </div>
  <div class="tile four" id="3">
  </div>
  <div class="tile five" id="4">
  </div>
  <div class="tile six" id="5">
  </div>
  <div class="tile seven" id="6">
  </div>
  <div class="tile eight" id="7">
  </div>
  <div class="tile nine" id="8">
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
JF123
  • 13
  • 3
  • The "inside an object" is a useless qualifier. Array comparison works the same regardless. The majority of the code is also not at all needed. Literally the only thing you're asking is "how to compare two arrays". Doesn't matter where one comes from, the HTML is similarly not relevant. A `gameboard == [1, 1, 1, "", "", "", "", "", ""]` with initialisation of `gameboard` is what the question is about. – VLAZ Feb 09 '23 at 12:42
  • I made you a snippet. Please add the relevant CSS - I just pasted a grid one I found – mplungjan Feb 09 '23 at 12:50
  • [Better dupe](https://stackoverflow.com/questions/60781311/how-to-check-if-somebody-won-in-a-tic-tac-toe-game-in-javascript) – mplungjan Feb 09 '23 at 12:52

0 Answers0