Skip to content

Commit

Permalink
refactor(checkWinner): test test test
Browse files Browse the repository at this point in the history
  • Loading branch information
mrdcvlsc committed Jun 30, 2023
1 parent e0f32a6 commit d048fb2
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions public/TicTacToe.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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];
}
Expand All @@ -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];
}
Expand All @@ -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];
}
Expand All @@ -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];
}
Expand Down

0 comments on commit d048fb2

Please sign in to comment.