Facebook Pixel

How do you highlight winning cells in tic-tac-toe?

When a win is detected, store the winning pattern (the three indices). Add a CSS class (e.g., 'winning') to those cells in the render function. Style .winning with a different background color.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How to Build a Tic-Tac-Toe Game in an Interview

Create a 3x3 grid. Use an array of 9 elements for the board. Alternate players (X/O). After each move, check 8 win patterns (3 rows, 3 columns, 2 diagonals). Detect draw when all cells are filled. Add reset and score tracking.

Check 8 win patterns: [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]. For each pattern, if board[a] === board[b] === board[c] and board[a] is not null, that player wins.

Check if all cells are filled (board.every(cell => cell !== null)) and no winner was detected. If so, it is a draw. Check for a win first, then check for a draw.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.