Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Created February 1, 2025 18:14
Show Gist options
  • Select an option

  • Save carefree-ladka/7f85ec53cd5be80d6970c91c7c60f808 to your computer and use it in GitHub Desktop.

Select an option

Save carefree-ladka/7f85ec53cd5be80d6970c91c7c60f808 to your computer and use it in GitHub Desktop.
TicTacToe Game Based on OOPS
class Board {
constructor() {
this.grid = [
["", "", ""],
["", "", ""],
["", "", ""]
];
}
printBoard() {
console.clear();
this.grid.forEach(row => console.log(row.join(" | ")));
console.log("\n");
}
isCellEmpty(row, col) {
return this.grid[row][col] === "";
}
placeMark(row, col, mark) {
if (this.isCellEmpty(row, col)) {
this.grid[row][col] = mark;
return true;
}
return false;
}
checkWin(mark) {
const winPatterns = [
// Rows
[[0, 0], [0, 1], [0, 2]],
[[1, 0], [1, 1], [1, 2]],
[[2, 0], [2, 1], [2, 2]],
// Columns
[[0, 0], [1, 0], [2, 0]],
[[0, 1], [1, 1], [2, 1]],
[[0, 2], [1, 2], [2, 2]],
// Diagonals
[[0, 0], [1, 1], [2, 2]],
[[0, 2], [1, 1], [2, 0]]
];
return winPatterns.some(pattern =>
pattern.every(([r, c]) => this.grid[r][c] === mark)
);
}
isFull() {
return this.grid.every(row => row.every(cell => cell !== ""));
}
}
class Player {
constructor(name, mark) {
this.name = name;
this.mark = mark;
}
}
class Game {
constructor(player1, player2) {
this.board = new Board();
this.players = [player1, player2];
this.currentPlayerIndex = 0;
this.isGameOver = false;
}
playTurn(row, col) {
if (this.isGameOver) {
console.log("Game is over. Restart to play again.");
return;
}
let currentPlayer = this.players[this.currentPlayerIndex];
if (this.board.placeMark(row, col, currentPlayer.mark)) {
this.board.printBoard();
if (this.board.checkWin(currentPlayer.mark)) {
console.log(`πŸŽ‰ ${currentPlayer.name} (${currentPlayer.mark}) wins!`);
this.isGameOver = true;
return;
}
if (this.board.isFull()) {
console.log("It's a draw! 🀝");
this.isGameOver = true;
return;
}
this.currentPlayerIndex = 1 - this.currentPlayerIndex; // Switch turn
} else {
console.log("Invalid move! Cell is already occupied.");
}
}
restart() {
console.log("πŸ”„ Restarting game...");
this.board = new Board();
this.currentPlayerIndex = 0;
this.isGameOver = false;
this.board.printBoard();
}
}
// Create Players
const player1 = new Player("Alice", "X");
const player2 = new Player("Bob", "O");
// Start Game
const game = new Game(player1, player2);
game.board.printBoard();
// Simulate Game
game.playTurn(0, 0); // Alice (X)
game.playTurn(0, 1); // Bob (O)
game.playTurn(1, 1); // Alice (X)
game.playTurn(0, 2); // Bob (O)
game.playTurn(2, 2); // Alice (X) - Wins
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment