Created
July 31, 2023 11:33
-
-
Save carefree-ladka/dee4d5236dae713fcf3f4a6512f10567 to your computer and use it in GitHub Desktop.
TicTacToe in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class TicTacToe { | |
| constructor() { | |
| this.board = Array(3) | |
| .fill(null) | |
| .map(() => Array(3).fill(null)); | |
| this.gameOver = false; | |
| this.winner = null; | |
| this.currentPlayer = "X"; | |
| this.winningPositions = [ | |
| [0, 1, 2], | |
| [3, 4, 5], | |
| [6, 7, 8], | |
| [0, 3, 6], | |
| [1, 4, 7], | |
| [2, 5, 8], | |
| [0, 4, 8], | |
| [2, 4, 6], | |
| ]; | |
| } | |
| makeMove(row, col) { | |
| if (this.gameOver || this.board[row][col] !== null) return; | |
| this.board[row][col] = this.currentPlayer; | |
| if (this.checkWin(row, col)) { | |
| this.winner = this.currentPlayer; | |
| this.gameOver = true; | |
| } else { | |
| this.currentPlayer = this.currentPlayer === "X" ? "O" : "X"; | |
| } | |
| } | |
| checkWin(row, col) { | |
| const player = this.board[row][col]; | |
| for (const [a, b, c] of this.winningPositions) { | |
| if ( | |
| this.board[Math.floor(a / 3)][a % 3] === player && | |
| this.board[Math.floor(b / 3)][b % 3] === player && | |
| this.board[Math.floor(c / 3)][c % 3] === player | |
| ) { | |
| return true; | |
| } | |
| } | |
| } | |
| isDraw() { | |
| if (!this.gameOver) return false; | |
| for (let row = 0; row < 3; row++) { | |
| for (let col = 0; col < 3; col++) { | |
| if (this.board[row][col] === null) return false; | |
| } | |
| } | |
| return true; | |
| } | |
| getWinner() { | |
| return this.winner; | |
| } | |
| getCurrentPlayer() { | |
| return this.currentPlayer; | |
| } | |
| isGameOver() { | |
| return this.gameOver; | |
| } | |
| } | |
| const game = new TicTacToe(); | |
| game.makeMove(0, 0); | |
| game.makeMove(1, 1); | |
| game.makeMove(2, 2); | |
| console.log(game.getCurrentPlayer()); | |
| console.log("Winner: ", game.getWinner()); | |
| console.log(game.isDraw()); | |
| console.log(game.board); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment