So I wanted to just make a quick tic tac toe in HTML. I threw this together and now it only works when the first row wins. It doesn't like my tie check, or any other possible winning positions. It is fine with either X or O. I tried changing the order of the win states, which changes which win state is accepted. But IDK why it won't allow any of the others. I also tried changing [a,b,c] to a var instead of const, but that didn't fix it.
const board = document.querySelector('.board');
let turn = 'X';
board.addEventListener('click', e => {
const square = e.target;
if (square.innerText) {
return; // already clicked, do nothing!
}
square.innerText = turn;
if (turn === 'X') {
square.classList.add('x');
turn = 'O';
} else {
square.classList.add('o');
turn = 'X';
}
checkWin(); // check for a win after each turn!
});
function checkWin() {
const squares = document.querySelectorAll('.square');
// winning combinations (3 in a row)
const winningCombos = [
[0, 1, 2], // top row
[3, 4, 5], // middle row
[6, 7, 8], // bottom row
[0, 3, 6], // left column
[1, 4, 7], // middle column
[2, 5, 8], // right column
[0, 4, 8], // diagonal top left to bottom right
[2, 4, 6] // diagonal top right to bottom left
];
for (let i = 0; i < winningCombos.length; i++) { // loop through all winning combos
const [a, b, c] = winningCombos[i]; // destructure the current combo into 3 variables
if (squares[a].innerText && squares[a].innerText === squares[b].innerText && squares[a].innerText === squares[c].innerText) { // check if all 3 squares have the same innerText (X or O)
alert(`
Player $ {
squares[a].innerText
}
wins!`); // alert the winner!
board.removeEventListener('click', () => {}); // remove the click event listener so no more moves can be made
break; // break out of the loop since we found a winner!
} else if (squares.every(s => s.innerText)) { // check if all squares have been clicked (filled with X or O) and there is no winner yet
alert('It\'s a draw!'); // alert that it's a draw!
board.removeEventListener('click', () => {}); // remove the click event listener so no more moves can be made
break; // break out of the loop since it's a draw!
}
}
}
.board {
display: flex;
flex-wrap: wrap;
width: 300px;
height: 300px;
border: 1px solid #000;
}
.square {
width: 100px;
height: 100px;
display: flex;
align-items: center;
justify-content: center;
font-size: 48px;
font-weight: bold;
cursor: pointer;
}
.x {
color: #f00;
}
.o {
color: #00f;
}
<div class="board">
<div class="square" data-index="0"></div>
<div class="square" data-index="1"></div>
<div class="square" data-index="2"></div>
<div class="square" data-index="3"></div>
<div class="square" data-index="4"></div>
<div class="square" data-index="5"></div>
<div class="square" data-index="6"></div>
<div class="square" data-index="7"></div>
<div class="square" data-index="8"></div>
</div>