0

I'm not seeing where the code goes wrong here , I hope someone can help.

these are my constructors :

class Game {
  constructor(p1, p2, column = 6, row = 7) {
    this.column = column;
    this.players = [p1, p2];
    this.row = row;
    this.board = [];
    this.currPlayer = p1;
    this.makeBoard();
    this.makeHtmlBoard();
    this.gameOver = false;
  }

then I created this method to handle the clicks , but when it calls the checkForWin method , console gives me an error inside checkForWin().

handleClick(evt) {
    const x = +evt.target.id;

    const y = this.findSpotForCol(x);
    if (y === null) {
      return;
    }

    this.board[y][x] = this.currPlayer;
    this.placeInTable(y, x);

    if (this.checkForWin()) {
      this.gameOver = true;
      return this.endGame(`Player with color : ${this.currPlayer.color} won!`);
    }

    if (this.board.every((row) => row.every((cell) => cell))) {
      return this.endGame("Tie!");
    }

    this.currPlayer =
      this.currPlayer === this.players[0] ? this.players[1] : this.players[0];
  }

checkForWin() {
    function _win(cells) {
      return cells.every(
        ([y, x]) =>
          y >= 0 &&
          y < this.column &&
          x >= 0 &&
          x < this.row &&
          this.board[y][x] === this.currPlayer
      );
    }

    for (let y = 0; y < this.column; y++) {
      for (let x = 0; x < this.row; x++) {
        const horiz = [
          [y, x],
          [y, x + 1],
          [y, x + 2],
          [y, x + 3],
        ];
        const vert = [
          [y, x],
          [y + 1, x],
          [y + 2, x],
          [y + 3, x],
        ];
        const diagDR = [
          [y, x],
          [y + 1, x + 1],
          [y + 2, x + 2],
          [y + 3, x + 3],
        ];
        const diagDL = [
          [y, x],
          [y + 1, x - 1],
          [y + 2, x - 2],
          [y + 3, x - 3],
        ];

        if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {
          return true;
        }
      }
    }

Error : TypeError in the y < this.column, at the _win() func, saying that cannot read property 'column' of undefined.

but why? I have a feeling that this.column in the func is not calling the Game object , but I don't know exactly why

  • 1
    Basically, the `this` inside of `_win` is not the same as the `this` inside of `checkForWin`. Define a variable to cache `this` (e.g. `const me = this;`) and use that within `_win`, or use an arrow function (e.g., `const _win = (cells) => cells.every(...);`). – Heretic Monkey May 14 '21 at 13:34
  • Perfect! when i Used the arrow function it worked! Also for some reason on the HandleClick method , the like to check for Win is not working. i console.logged it it does not give me anything when it supposed to return a boolean – lucasluize May 14 '21 at 13:38

0 Answers0