class TicTacToe { constructor() { this.boardState = [['', '', ''], ['', '', ''], ['', '', '']]; this.currentPlayer = "X"; this.winner = "NONE"; } implementTurn(e) { let [r, c] = this.getIndex(e); if (this.boardState[r][c] !== '') { return; } else { this.changePlayer(e, r, c); this.checkEndGame(); } } getIndex(e) { return [parseInt((e.id - 1) / 3), parseInt((e.id - 1) % 3)]; } changePlayer(e, r, c) { this.boardState[r][c] = this.currentPlayer; let currentBlock = document.getElementById(e.id); currentBlock.innerText = this.currentPlayer; if (this.currentPlayer === "X") { currentBlock.style.backgroundColor = "#ed3f32"; } else { currentBlock.style.backgroundColor = "#44d362"; } if (this.checkEndGame()) { this.showWinner(); } let currentPlayerDisplay = document.getElementById("currentPlayer"); this.currentPlayer = this.currentPlayer === "X" ? "O" : "X"; currentPlayerDisplay.innerText = this.currentPlayer; // console.log(this.boardState); } checkEndGame() { const bs = this.boardState; let result = true; //row check for (let i = 0; i < 3; i++) { result = true; for (let j = 1; j < 3; j++) { if (bs[i][j - 1] != bs[i][j] || bs[i][j] === "") result = false; } if (result) { this.winner = bs[i][0]; return true; } } for (let j = 0; j < 3; j++) { result = true; for (let i = 1; i < 3; i++) { if (bs[i - 1][j] != bs[i][j] || bs[i][j] === "") result = false; } if (result) { this.winner = bs[0][j]; return true; } } if (bs[0][0] == bs[1][1] && bs[1][1] == bs[2][2]) { if (bs[1][1] != "") { this.winner = bs[1][1]; return true; } } if (bs[0][2] == bs[1][1] && bs[1][1] == bs[2][0]) { if (bs[1][1] != "") { this.winner = bs[1][1]; return true; } } let draw = true; for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (bs[i][j] === "") { draw = false; } } } if (draw) { this.winner = "DRAW"; return true; } return false; } showWinner() { for (let i = 1; i < 10; i++) { // document.getElementById(i).style.cursor="not-allowed"; document.getElementById(i).style.pointerEvents = "none"; } if (this.winner != "DRAW") alert(this.winner + " is the winner"); else { alert("Match is tie"); } } reset() { this.boardState = [['', '', ''], ['', '', ''], ['', '', '']]; this.winner = "NONE"; let currentPlayerDisplay = document.getElementById("currentPlayer"); this.currentPlayer = "X"; currentPlayerDisplay.innerText = this.currentPlayer; for (let i = 1; i < 10; i++) { document.getElementById(i).innerText = ''; document.getElementById(i).style.backgroundColor = "rgb(228, 225, 225)"; document.getElementById(i).style.cursor = "pointer"; document.getElementById(i).style.pointerEvents = "all"; this.currentPlayer = "X"; } } } let currentGame = new TicTacToe(); function implementTurn(e) { currentGame.implementTurn(e); } function reset() { currentGame.reset(); }