Skip to content

Instantly share code, notes, and snippets.

@chowryan
Created June 19, 2017 22:43
Show Gist options
  • Save chowryan/06d864fa9c05dc7e0684e36806381cdb to your computer and use it in GitHub Desktop.
Save chowryan/06d864fa9c05dc7e0684e36806381cdb to your computer and use it in GitHub Desktop.
const prompt = require('prompt');
class TicTacToe {
constructor() {
this.winner = null;
this.board = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' '],
];
this.turn = 'X';
}
checkWinner() {
const board = this.board;
if (board[0][1] === board[0][0] && board[0][2] === board[0][0]) {
this.winner = board[0][0];
} else if (board[1][1] === board[1][0] && board[1][2] === board[1][0]) {
this.winner = board[1][0];
} else if (board[2][1] === board[2][0] && board[2][2] === board[2][0]) {
this.winner = board[2][0];
} else if (board[0][0] === board[1][0] && board[0][0] === board[2][0]) {
this.winner = board[0][0];
} else if (board[0][1] === board[1][1] && board[0][1] === board[2][1]) {
this.winner = board[0][1];
} else if (board[0][2] === board[1][2] && board[0][2] === board[2][2]) {
this.winner = board[0][2];
} else if (board[0][0] === board[1][1] && board[0][0] === board[2][2]) {
this.winner = board[0][0];
} else if (board[0][2] === board[1][1] && board[0][2] === board[2][0]) {
this.winner = board[0][2];
}
return this.winner;
}
mark() {
console.log(`Current Turn: ${this.turn}`);
prompt.get(['Row', 'Col'], (err, result) => {
if (err) { return onErr(err); }
this.board[result.Row][result.Col] = this.turn;
this.display();
const currentWinner = this.checkWinner();
if (currentWinner !== ' ') {
console.log(`${this.winner} is the winner!`);
return;
}
this.turn = (this.turn === 'X') ? 'O' : 'X';
this.mark();
});
}
display() {
console.log(`${this.board[0][0]} | ${this.board[0][1]} | ${this.board[0][2]}`);
console.log('--- --- ---');
console.log(`${this.board[1][0]} | ${this.board[1][1]} | ${this.board[1][2]}`);
console.log('--- --- ---');
console.log(`${this.board[2][0]} | ${this.board[2][1]} | ${this.board[2][2]}`);
}
};
prompt.start();
const game = new TicTacToe();
game.display();
game.mark();
function onErr(err) {
console.log(err);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment