Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
making a tic tac toe game in JS

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!