Skip to content

Instantly share code, notes, and snippets.

@FermiDirak
Created April 11, 2018 21:23
Show Gist options
  • Save FermiDirak/df894ea8f2ac638af7d96eb5a02c12bc to your computer and use it in GitHub Desktop.
Save FermiDirak/df894ea8f2ac638af7d96eb5a02c12bc to your computer and use it in GitHub Desktop.
class TicTacToe {
constructor() {
this.board = [
['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-'],
];
this.currentPlayer = 'x';
}
placePiece(i, j) {
// piece within bounds
if (!(i >= 0 && i < 3 && j >= 0 && j < 3)) {
console.log('invalid move');
return;
}
if (this.board[i][j] === '-') {
this.board[i][j] = this.currentPlayer;
this.currentPlayer = this.currentPlayer === 'x' ? 'o' : 'x';
this.renderBoard();
let victor = this.checkVictory();
if (victor) {
console.log(victor + ' wins!!!!');
this.currentPlayer = 'x';
this.board = [
['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-'],
];
}
}
}
checkVictory() {
let victor = undefined;
// check rows for victories HORIZONTAL CHECK
for (let i = 0; i < this.board.length; ++i) {
let row = this.board[i];
victor = this.checkCrossSectionVictory(row);
if (victor) {
return victor;
}
}
// check columns for victories VERTICAL CHECK
for (let i = 0; i < this.board.length; i++) {
let column = this.board.map((row) => {
return row[i];
});
victor = this.checkCrossSectionVictory(column);
if (victor) {
return victor;
}
}
// checks top left diagonal for vicotries TOP-LEFT DIAGONAL
let topLeftDiag = [this.board[0][0], this.board[1][1], this.board[2][2]];
victor = this.checkCrossSectionVictory(topLeftDiag);
if (victor) {
return victor;
}
// checks top right diagonal for vicotries TOP-RIGHT DIAGONAL
let topRightDiag = [this.board[0][2], this.board[1][1], this.board[2][0]];
victor = this.checkCrossSectionVictory(topRightDiag);
if (victor) {
return victor;
}
return victor;
}
checkCrossSectionVictory(crossSection) {
let victory = crossSection.every((element) => {
return element !== '-' && element === crossSection[0];
});
if (victory) {
return crossSection[0];
}
}
renderBoard() {
console.log(this.board[0]);
console.log(this.board[1]);
console.log(this.board[2]);
console.log(this.currentPlayer + '\'s turn')
}
}
let t = new TicTacToe();
t.placePiece(0, 0);
t.placePiece(0, 1);
t.placePiece(1, 0);
t.placePiece(0, 2);
t.placePiece(2, 0);
t.renderBoard();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment