JavaScript Object-Oriented JavaScript: Challenge Adding the Game Logic Build the checkForWin() Method

George Roberts
George Roberts
Full Stack JavaScript Techdegree Student 6,681 Points

My attempt at a solution for the checkForWin() method

Hi there,

I would really appreciate any feedback on how I approached this - please see my code below. It's not complete but I think maybe repeating the last section for the different directions (with the right adjustments each time) might lead to a functioning solution?


   * Checks if there is a winner on the board after each token drop.
   * @param {array} spaces the 2D array of all spaces @ this.board.spaces
   * @param {Object} activePlayer the active player
  checkForWin(spaces, activePlayer) {

    // flatten 2D array spaces into a 1D array of all spaces:
    const arrayOfAllSpaces = spaces.reduce((accArray, column) => {
      return [...accArray, ...column];
    }, []);

    // filter 1D array of spaces by activePlayer ownership:
    const spacesOwnedByActivePlayer = arrayOfAllSpaces.filter(space => space.owner === activePlayer);

    // use space x and y properties to check for victory streaks in each possible direction:
    // check for vertical down victory:
    const verticalDown = [];
    let incrementor = 1;
    for (space of spacesOwnedByActivePlayer) {
      if (space.y === activeSpace.y + incrementor) {
    //check if direction array contains at least 4 in a row:
    if (verticalDown.length >= 4) {
      // call gameover method / winner alert

    // repeat above code (from 'const verticalDown = []' onwards) for the different directions.

1 Answer

Steven Parker
Steven Parker
163,416 Points

It's not clear what "activeSpace" refers to, but it looks like consecutive pairs of owned spaces will all be added to the "verticalDown" array. So basing the determination on length alone may mean several isolated pairs could be misinterpreted as "win".

Otherwise, the basic idea seems viable.

George Roberts
George Roberts
Full Stack JavaScript Techdegree Student 6,681 Points

Oh I see what you mean about misinterpreting isolated pairs. Thank you for the feedback!