#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)
š¤ forget the very last part. Can look into it again when I'm at a computer. Unless someone else can help first
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
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"));
}
}
});
}
};
s === s?
mb fixed
Sorry to fuss, was interested in this and got lost there. š
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])) {