From e59b39cb9e82f78500f4143fc5fb8e0916b82884 Mon Sep 17 00:00:00 2001 From: mrdcvlsc Date: Sat, 1 Jul 2023 03:06:12 +0800 Subject: [PATCH] fix(checkWinner): testing semantic version --- public/TicTacToe.js | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/public/TicTacToe.js b/public/TicTacToe.js index bb6492d..59802ad 100644 --- a/public/TicTacToe.js +++ b/public/TicTacToe.js @@ -30,6 +30,8 @@ class TicTacToe { } this.pieceWinCount = pieceWinCount; + console.log('this.grid = ', this.grid); + console.log('this.pieceWinCount = ', this.pieceWinCount); this.player = (options?.player) ? (options.player === P1 || options.player === P2) ? options.player : P1 : P1; this.winner = 0; @@ -163,12 +165,14 @@ class TicTacToe { checkWinner() { // check row - for (let i = 0; i < this.grid; ++i) { + let samePiece = 1; for (let j = 1; j < this.grid; ++j) { if ( this.board[i * this.grid + (j - 1)] === this.board[i * this.grid + j] && this.board[i * this.grid + j] !== NA ) { - if (j === this.grid - 1) { + samePiece++; + if (samePiece === this.pieceWinCount) { this.winner = this.board[i * this.grid + j]; return this.board[i * this.grid + j]; } @@ -180,12 +184,14 @@ class TicTacToe { // check columns | for (let j = 0; j < this.grid; ++j) { + let samePiece = 1; for (let i = 1; i < this.grid; ++i) { if ( this.board[(i - 1) * this.grid + j] === this.board[i * this.grid + j] && this.board[i * this.grid + j] !== NA ) { - if (i === this.grid - 1) { + samePiece++; + if (samePiece === this.pieceWinCount) { this.winner = this.board[i * this.grid + j]; return this.board[i * this.grid + j]; } @@ -196,12 +202,14 @@ class TicTacToe { } // check diag \ + let samePieceSecondLastDiag = 1; for (let i = 1; i < this.grid; ++i) { if ( this.board[(i - 1) * this.grid + (i - 1)] === this.board[i * this.grid + i] && this.board[i * this.grid + i] !== NA ) { - if (i === this.grid - 1) { + samePieceSecondLastDiag++; + if (samePieceSecondLastDiag === this.pieceWinCount) { this.winner = this.board[i * this.grid + i]; return this.board[i * this.grid + i]; } @@ -212,9 +220,11 @@ class TicTacToe { // check diag / const diagStep = this.grid - 1; + let samePieceLastDiag = 1; for (let i = 1; i < this.grid; ++i) { if (this.board[(i + 1) * diagStep] === this.board[i * diagStep] && this.board[i * diagStep] !== NA) { - if (i === this.grid - 1) { + samePieceLastDiag++; + if (samePieceLastDiag === this.pieceWinCount) { this.winner = this.board[i * diagStep]; return this.board[i * diagStep]; }