Skip to content

Instantly share code, notes, and snippets.

@deepakshrma
Created April 4, 2020 03:50
Show Gist options
  • Save deepakshrma/9c3fde35d809b25ca2f15d27d1df4124 to your computer and use it in GitHub Desktop.
Save deepakshrma/9c3fde35d809b25ca2f15d27d1df4124 to your computer and use it in GitHub Desktop.
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");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment