Im making a tic tac toe in js for learning purposes however I am a little stuck. my code is:
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 2; j++) {
const newElement = document.createElement('td');
tableR.item(i).appendChild(newElement);
newElement.addEventListener('click', () => {
if (elementIsEmpty(newElement)) {
const img = document.createElement('img');
if (xTurn) {
img.src = 'images/x.svg';
x.push(String(i) + String(j))
}
else {
img.src = 'images/o.png';
o.push(String(i) + String(j))
}
newElement.append(img)
console.log("here")
checkWinOrDraw(xTurn)
xTurn = !xTurn
}
})
}
}
and my checkWinOrDraw function is:
let winPat = [['00', '10', '20'], ['01', '11', '21'], ['02', '12', '22'], ['00', '01', '02'], ['10', '11', '12'], ['20', '21', '22'], ['00', '11', '22'], ['02', '11', '20']];
function checkWinOrDraw(xTurn) {
for (let i = 0; i < winPat.length; i++) {
if (xTurn) {
if (winPat[i].every(element => x.includes(element))) {
alert('X wins')
reset()
return
}
}
else {
if (winPat[i].every(element => o.includes(element))) {
alert('O wins')
reset()
return
}
}
}
for (let item of td) {
if (elementIsEmpty(item))
return
}
alert('Draw')
reset()
}
However, when the game ends, the last image is not shown on the screen. For example, when X wins, I get an alert("x wins") but the image of x in the cell is not rendered.