vendredi 7 mai 2021

Both parts of "if statement" are executing (javascript)

I know that I must be missing something straightforward here, but I can't seem to get the move() method to work properly.

For some reason, whenever the computer has a winningSquare it not only executes the content inside of the "if statement" to add the winningSquare to the board, but also executes the "else" part of the statement and overrides the winning move with a random move.

Any ideas why this could be happening?

lass Computer extends Player {
  constructor() {
    super();
  }

  static COMPUTER_MOVE = 'O';

  move(board) {
    let winningSquare = this.winningSquare(board);
    let atRiskSquare = this.atRiskSquare(board);
    let randomSquare = this.randomMove(board);

    if (winningSquare) {
      board.addMove(winningSquare, Computer.COMPUTER_MOVE);
      this.moves.push(winningSquare);
    } else if (atRiskSquare) {
      board.addMove(atRiskSquare, Computer.COMPUTER_MOVE);
      this.moves.push(atRiskSquare);
    } else {
      board.addMove(randomSquare, Computer.COMPUTER_MOVE);
      this.moves.push(randomSquare);
    }
  }

  winningSquare(board) {
    let humanMoves = board.findSpaces('X');
    let computerMoves = board.findSpaces('O');

    for (let winningCombo of Game.WINNING_COMBOS) {
      let winningSquare;
      let count = 0;

      for (let square of winningCombo) {
        if (computerMoves.includes(square)) {
          count += 1;
        } else {
          winningSquare = square;
        }
      }

      if (count === 2 && !humanMoves.includes(winningSquare)) {
        console.log(winningSquare);
      }
    }
    return null;
  }

  atRiskSquare(board) {

    let humanMoves = board.findSpaces('X');
    let computerMoves = board.findSpaces('O');

    for (let winningCombo of Game.WINNING_COMBOS) {
      let atRiskSquare;
      let count = 0;

      for (let square of winningCombo) {
        if (humanMoves.includes(square)) {
          count += 1;
        } else {
          atRiskSquare = square;
        }
      }

      if (count === 2 && !computerMoves.includes(atRiskSquare)) {
        return atRiskSquare;
      }

    }
    return null;
  }

  randomMove(board) { // This doesn't work when it's undefined
    let openSpaces = board.findSpaces(' ');
    let randomSpace = Math.floor(Math.random() * openSpaces.length);
    return openSpaces[randomSpace].toString(); // this doesn't work when undefined
  }
}

Aucun commentaire:

Enregistrer un commentaire