Вы можете создать матрицу выигрышных комбинаций.
winningCombination = [
[
[0, 0],
[0, 1],
[0, 2],
],
[
[1, 0],
[1, 1],
[1, 2],
],
[
[2, 0],
[2, 1],
[2, 2],
],
[
[0, 0],
[1, 0],
[2, 0],
],
[
[0, 1],
[1, 1],
[2, 1],
],
[
[0, 2],
[1, 2],
[2, 2],
],
[
[0, 0],
[1, 1],
[2, 2],
],
[
[2, 2],
[1, 1],
[0, 0],
],
];
Где каждая строка определяет, [i,j]
Положение хода.
class TicTac {
constructor() {
this.mat = [
[-1, -1, -1],
[-1, -1, -1],
[-1, -1, -1],
];
}
move(i, j, m) {
m ? this.moveX([i, j]) : moveO([i, j]);
}
moveX([i, j]) {
this.mat[i][j] = 1;
}
moveO([i, j]) {
this.mat[i][j] = 0;
}
winner(move) {
const mat = this.mat;
for (let i = 0; i < TicTac.winningCombination.length; i++) {
const [[x11, x12], [x21, x22], [x31, x32]] = TicTac.winningCombination[i];
if (
move == mat[x11][x12] &&
mat[x11][x12] == mat[x21][x22] &&
mat[x11][x12] == mat[x31][x32]
) {
return move;
}
}
return -1;
}
}
TicTac.winningCombination = [
[
[0, 0],
[0, 1],
[0, 2],
],
[
[1, 0],
[1, 1],
[1, 2],
],
[
[2, 0],
[2, 1],
[2, 2],
],
[
[0, 0],
[1, 0],
[2, 0],
],
[
[0, 1],
[1, 1],
[2, 1],
],
[
[0, 2],
[1, 2],
[2, 2],
],
[
[0, 0],
[1, 1],
[2, 2],
],
[
[2, 2],
[1, 1],
[0, 0],
],
];
const ticTac = new TicTac();
ticTac.moveO([0, 0]);
ticTac.moveX([1, 1]);
console.log(ticTac.mat);
let hasWinner = ticTac.winner(1);
console.log(hasWinner !== -1 ? (hasWinner ? "X Wins" : "O Wins") : "NO Winner");
ticTac.moveO([0, 2]);
ticTac.moveX([1, 0]);
console.log(ticTac.mat);
ticTac.moveO([2, 1]);
ticTac.moveX([2, 2]);
console.log(ticTac.mat);
ticTac.moveO([0, 1]);
hasWinner = ticTac.winner(0);
console.log(hasWinner !== -1 ? (hasWinner ? "X Wins" : "O Wins") : "NO Winner");
.as-console {
min-height: 100% !important;
}
.as-console-row {
color: blue !important;
}