connect-four icon indicating copy to clipboard operation
connect-four copied to clipboard

Getting rid of the fixed array

Open proteo opened this issue 4 years ago • 5 comments

Hi Ania, thank you very much for the JS course!

In this game though I think that rather than using a fixed array to find winning combinations it would be better to calculate the position of the selected cell, then look for the three adjacent cells in the available directions for matching cells dynamically.

These functions do that with basic arithmetics. You'll need to invoke checkWinner() with the position of the clicked cell (its index in the squares array) and the player that is performing the play (so invoke the function before changing currentPlayer, or store it for later use).

Best, Proteo.

function checkCandidates(index, cssName, callbackId) {
    // Look for the three adjacent cells, as defined by callbackId().
    for (let i = 1; i <= 3; i++) {
      let id = callbackId(index, i);
      if (!squares[id].classList.contains(cssName)) {
        return false;
      }
    }
    return true;
  }

  function checkWinner(index, player) {
    const cssName = (player == 2) ? 'player-two' : 'player-one';
    const cellPos = (index + 1);
    const cellRow = Math.ceil(cellPos / 7);
    const cellCol = Math.ceil(cellPos - ((cellRow - 1) * 7));

    // Check bottom cells (after, in the same column).
    if (cellRow < 4 && checkCandidates(index, cssName, (index, i) => index + (7 * i))) {
      return true;
    }
    // Check left cells (before, in the same row).
    if (cellCol >= 4 && checkCandidates(index, cssName, (index, i) => index - i)) {
      return true;
    }
    //  Check top cells (before, in the same column).
    if (cellRow >= 4 && checkCandidates(index, cssName, (index, i) => index - (7 * i))) {
      return true;
    }
    //  Check right cells (after, in the same column).
    if (cellCol <= 4 && checkCandidates(index, cssName, (index, i) => index + i)) {
      return true;
    }

    // No winner yet!
    return false;
  }

proteo avatar May 13 '20 07:05 proteo

Hi Ania, thank you for your tutorials.

I used a different approach from Proteo (above) and used conditional statements to check for a win in the checkBoard function.


function checkBoard () {
    for (let i = 0; i < squares.length; i++) {
      if (
        (squares[i].classList.contains('player-one') &&
        squares[i + 7].classList.contains('player-one') &&
        squares[i + 14].classList.contains('player-one') &&
        squares[i + 21].classList.contains('player-one')) ||
        (
          squares[i].classList.contains('player-one') &&
          squares[i + 8].classList.contains('player-one') &&
          squares[i + 16].classList.contains('player-one') &&
          squares[i + 24].classList.contains('player-one')) ||
        (
          squares[i].classList.contains('player-one') &&
          squares[i + 6].classList.contains('player-one') &&
          squares[i + 12].classList.contains('player-one') &&
          squares[i + 18].classList.contains('player-one')) ||
        (
          squares[i].classList.contains('player-one') &&
          squares[i + 1].classList.contains('player-one') &&
          squares[i + 2].classList.contains('player-one') &&
          squares[i + 3].classList.contains('player-one')
        )
      ) {
        result.innerHTML = 'Player One Wins!'
      }
      if (
        (squares[i].classList.contains('player-two') &&
        squares[i + 7].classList.contains('player-two') &&
        squares[i + 14].classList.contains('player-two') &&
        squares[i + 21].classList.contains('player-two')) ||
        (
          squares[i].classList.contains('player-two') &&
          squares[i + 8].classList.contains('player-two') &&
          squares[i + 16].classList.contains('player-two') &&
          squares[i + 24].classList.contains('player-two')) ||
        (
          squares[i].classList.contains('player-two') &&
          squares[i + 6].classList.contains('player-two') &&
          squares[i + 12].classList.contains('player-two') &&
          squares[i + 18].classList.contains('player-two')) ||
        (
          squares[i].classList.contains('player-two') &&
          squares[i + 1].classList.contains('player-two') &&
          squares[i + 2].classList.contains('player-two') &&
          squares[i + 3].classList.contains('player-two')
        )
      ) {
        result.innerHTML = 'Player Two Wins!'
        console.log(result.innerHTML)
      }
    }
  }

Jowardhar avatar Mar 11 '22 14:03 Jowardhar

Hi Ania, thank you very much for the JS course!

In this game though I think that rather than using a fixed array to find winning combinations it would be better to calculate the position of the selected cell, then look for the three adjacent cells in the available directions for matching cells dynamically.

These functions do that with basic arithmetics. You'll need to invoke checkWinner() with the position of the clicked cell (its index in the squares array) and the player that is performing the play (so invoke the function before changing currentPlayer, or store it for later use).

Best, Proteo.

function checkCandidates(index, cssName, callbackId) {
    // Look for the three adjacent cells, as defined by callbackId().
    for (let i = 1; i <= 3; i++) {
      let id = callbackId(index, i);
      if (!squares[id].classList.contains(cssName)) {
        return false;
      }
    }
    return true;
  }

  function checkWinner(index, player) {
    const cssName = (player == 2) ? 'player-two' : 'player-one';
    const cellPos = (index + 1);
    const cellRow = Math.ceil(cellPos / 7);
    const cellCol = Math.ceil(cellPos - ((cellRow - 1) * 7));

    // Check bottom cells (after, in the same column).
    if (cellRow < 4 && checkCandidates(index, cssName, (index, i) => index + (7 * i))) {
      return true;
    }
    // Check left cells (before, in the same row).
    if (cellCol >= 4 && checkCandidates(index, cssName, (index, i) => index - i)) {
      return true;
    }
    //  Check top cells (before, in the same column).
    if (cellRow >= 4 && checkCandidates(index, cssName, (index, i) => index - (7 * i))) {
      return true;
    }
    //  Check right cells (after, in the same column).
    if (cellCol <= 4 && checkCandidates(index, cssName, (index, i) => index + i)) {
      return true;
    }

    // No winner yet!
    return false;
  }

What about diagonal wins? like 15, 23,31,39?

kingltj avatar Oct 16 '22 02:10 kingltj

does this check diagonal wins as well?

kingltj avatar Oct 16 '22 02:10 kingltj

const maxSquare = 48; const maxPlayable = 41; const minPlayable = 0; const tk = "taken"; let currentSquare = 0; let won = false;

const players = [ "player-one", "player-two"]; let player = 1; let currentPlayer = players[player-1];

const grid = document.querySelector('.grid'); const squares = createDivs(); const resultDisplay = document.querySelector('#result'); const currentPlayerDisplay = document.getElementById('current-player');

squares.forEach((square, i) => { const invalid = "Can't play in square # " + i;

square.onclick = () => {
    if(won) return true;
    if(!square.classList.contains(tk)){
        if(squares[i+7].classList.contains(tk)){
            currentPlayerDisplay.classList.remove(currentPlayer);
            currentSquare = i;
            if(addClass(square, tk, true)) return true;
            currentPlayerDisplay.textContent =  player;
            currentPlayerDisplay.classList.add(currentPlayer);
        }
        else
            alert(invalid + " yet!");
    }
    else
        alert(invalid);
}

})

function addClass(div, tk, aP = false){ div.classList.add(tk);

if(aP){
    div.classList.add(currentPlayer);
     if(checkForWin()) return true;
    if(player > players.length-1){player=0;}
    currentPlayer = players[++player-1];
}

}

function createDivs(){

for(let i = minPlayable; i <= maxSquare; i++){    
    const div = document.createElement('div');
    
    if(i > maxPlayable && i <= maxSquare){ addClass(div, tk); }

// else div.textContent = i;

    grid.appendChild(div);
}

return document.querySelectorAll('.grid div');

}

function checkForWin(){ if(won) return true;

console.clear()
if(won = checkSouth());
else if(won = checkEastWest());
else if(won = checkNESW());
else if(won = checkNWSE());
else { return false;}

resultDisplay.textContent = "Player " + player + " Wins!";

}

function checkSouth(){ const connectFour = [currentPlayer + " has " + currentSquare]; console.log("South"); return check(south = 7, connectFour, left = false, southOnly = true) ? true : false; }

function checkEastWest(){ const connectFour = [currentPlayer + " has " + currentSquare]; console.log("EastWest"); return check(east = 1, connectFour, left = false) ? true : check(west = -1, connectFour); }

function checkNESW(){ const connectFour = [currentPlayer + " has " + currentSquare]; console.log("NESW"); return check(nE = -6, connectFour, left = false) ? true : check(sW = 6, connectFour); }

function checkNWSE(){ const connectFour = [currentPlayer + " has " + currentSquare]; console.log("NWSE"); return check(sE = 8, connectFour, left = false) ? true : check(nW = -8, connectFour); }

function check(direction, connectFour, left = true, southOnly = false){ for(let c = 1, higher = 1; c <= 4; c++, higher++){ if((next = currentSquare+(direction*higher)) > maxPlayable || next < minPlayable) return false;

    if( !southOnly && next % 7 == (left ? 6 : 0) ) return false;

    if(!squares[next].classList.contains(currentPlayer)) return false;

    connectFour.push(say = currentPlayer + " has " + next);

    console.log(connectFour);

    if(connectFour.length >= 4) return true;
}

}

kingltj avatar Oct 16 '22 02:10 kingltj

Hi Ania, thank you for your tutorials.

I used a different approach from Proteo (above) and used conditional statements to check for a win in the checkBoard function.


function checkBoard () {
    for (let i = 0; i < squares.length; i++) {
      if (
        (squares[i].classList.contains('player-one') &&
        squares[i + 7].classList.contains('player-one') &&
        squares[i + 14].classList.contains('player-one') &&
        squares[i + 21].classList.contains('player-one')) ||
        (
          squares[i].classList.contains('player-one') &&
          squares[i + 8].classList.contains('player-one') &&
          squares[i + 16].classList.contains('player-one') &&
          squares[i + 24].classList.contains('player-one')) ||
        (
          squares[i].classList.contains('player-one') &&
          squares[i + 6].classList.contains('player-one') &&
          squares[i + 12].classList.contains('player-one') &&
          squares[i + 18].classList.contains('player-one')) ||
        (
          squares[i].classList.contains('player-one') &&
          squares[i + 1].classList.contains('player-one') &&
          squares[i + 2].classList.contains('player-one') &&
          squares[i + 3].classList.contains('player-one')
        )
      ) {
        result.innerHTML = 'Player One Wins!'
      }
      if (
        (squares[i].classList.contains('player-two') &&
        squares[i + 7].classList.contains('player-two') &&
        squares[i + 14].classList.contains('player-two') &&
        squares[i + 21].classList.contains('player-two')) ||
        (
          squares[i].classList.contains('player-two') &&
          squares[i + 8].classList.contains('player-two') &&
          squares[i + 16].classList.contains('player-two') &&
          squares[i + 24].classList.contains('player-two')) ||
        (
          squares[i].classList.contains('player-two') &&
          squares[i + 6].classList.contains('player-two') &&
          squares[i + 12].classList.contains('player-two') &&
          squares[i + 18].classList.contains('player-two')) ||
        (
          squares[i].classList.contains('player-two') &&
          squares[i + 1].classList.contains('player-two') &&
          squares[i + 2].classList.contains('player-two') &&
          squares[i + 3].classList.contains('player-two')
        )
      ) {
        result.innerHTML = 'Player Two Wins!'
        console.log(result.innerHTML)
      }
    }
  }

It doesn't work. If you see this code squares[i].classList.contains('player-two') && squares[i + 1].classList.contains('player-two') && squares[i + 2].classList.contains('player-two') && squares[i + 3].classList.contains('player-two') What if player two starts the game like this, he clicks on position i-1, i-2, i+1 and then i, in your code your reading the positions only after i. So please reconsider this.

MohammedAslam106 avatar Jun 01 '23 10:06 MohammedAslam106