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>