#Is there a way to encapsulate all win conditions for tic-tac-toe without manually typing them in?

10 messages Ā· Page 1 of 1 (latest)

coral path
#

Yes. You want all coordinates where either all x-, or all y-components are the same. The diagonals are the one where each x-component equals the y-component. The second diagonal is the one where the difference of the components is 2

#

šŸ¤” forget the very last part. Can look into it again when I'm at a computer. Unless someone else can help first

coral path
#

That's information I would store in the respective cells. But you can also calculate it from the index:

x = i % 3
y = Math.floor(i / 3)

But honestly, I think it's cleaner to just store the few indices you're checking out for your use case

coral path
#

Glad it worked out for you. I took the liberty of adding some refactorings, which I forgot to document due to tiredness. Good night

const setWinner = () => {
    const winnerCombinations = [
        [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 (const cell of gameBoard.boardArray) {
        cell.addEventListener("click", () => {
            for (const row of winnerCombinations) {
                if (row.every(s => s && s === row[0])) {  // assuming row contains exactly the three elements a,b,c
                    winnerHeading.textContent = "Player 1 won!";
                    gameBoard.boardArray.forEach((e) => e.removeEventListener("click"));
                }
            }
        });
    }
};
coral path
wraith anvil
#

Sorry to fuss, was interested in this and got lost there. šŸ’ž

coral path
#

why not? 😮

#

oh, right. Needs a mapping to actually retrieve the innerHTML before checking for equality. I was dead tired when I wrote that yesterday.

#
for (const row of winnerCombinations) {
  const values = row.map(i => gameBoard.boardArray[i].innerHTML) // ←
  if (values.every(s => s && s === values[0])) {