0

need to detect a diagonal win, have acheived this horizontally with the hScore part of the detwct win function but it can not detect a horizontal winner, ive tried to make the function so it uses the indexs of the arrays to trigger the win when each one has a o or x placed on it, but it doesnt work, is there a better way for me to achieve this ?

The game is o's and x's, with out the function working correctly it wont detect the winner for diagonal wins

 players = ['o', 'x'];
    currentPlayerIndex = 0;
    
    board = [
      [' ', ' ', ' '],
      [' ', ' ', ' '],
      [' ', ' ', ' '],
    ];
    
    
    
    play = (x, y) => {
      let message = 'current player wins';
      if (getSquare(x, y) === ' ') {
        setSquare(x, y, currentPlayer());
        document.getElementById('square' + x + y).innerHTML = currentPlayer();
        if (detectWinner()) {
          alert(currentPlayer() + message);
          console.log('winner');
        }
        changePlayer();
      }
    };
    
  detectWinner = () => {

for (let i = 0; i < board.length; i++) {
    let hScore = board[i];
    let dScore = [...board[i]];
    let hScoreString = JSON.stringify(hScore);
    
    console.log(board[i]);
    let matches = [
      JSON.stringify(['x', 'x', 'x']),
      JSON.stringify(['o', 'o', 'o']),
    ];

    if (matches.includes(hScoreString)) {
      return true;
    
    } else if ( dScore[(0, 0), (0, 1), (0, 1)].every()  === 'o'  )                {
      return true;
    }
   }
 return false;
   };

        
    currentPlayer = () => {
      console.log(players[currentPlayerIndex]);
      return players[currentPlayerIndex];
    };
    
    changePlayer = () => {
      currentPlayerIndex = (currentPlayerIndex + 1) % 2;
    };
    getSquare = (x, y) => {
      return board[x][y];
    };
    
    setSquare = (x, y, value) => {
      board[x][y] = value;
    };
    
    reset = () => {
      ////refresh page
    };
dcode
  • 11
  • 2

2 Answers2

1

You are getting the wrong return values because of the way you are comparing arrays and variables.

  • We have to first convert arrays to strings to compare them. We can use JSON.stringify to do so.
let cScoreString = JSON.stringify(cScore)
    
let matches = [
  JSON.stringify(["x", "x", "x"]),
  JSON.stringify(["o", "o", "o"])
]
  • Then we can check if our variable is found in the array.
if (matches.includes(cScoreString)) return true

or

if (matches[0] === cScoreString || matches[1] === cScoreString) return true

Full code:

let example = [
  ["x", "x", "o"],
  ["o", "o", "o"], // Winning line
  ["x", "o", "x"]
]

detectWinner = (board) => { 
  for (let i = 0; i < board.length; i++) {
    let cScore = board[i];
    let cScoreString = JSON.stringify(cScore)
    
    let matches = [
      JSON.stringify(["x", "x", "x"]),
      JSON.stringify(["o", "o", "o"])
    ]
    
    if (matches.includes(cScoreString)) return true
  }
  return false;
};

console.log(detectWinner(example))
lejlun
  • 4,140
  • 2
  • 15
  • 31
  • this has worked thank you, could it be used to check diagonal conditions as well ? – dcode Aug 04 '21 at 15:54
  • @dcode You'll have to take a different approach to check diagonal conditions, take a look at this article [Algorithm to detect a tic tac toe winner](https://jayeshkawli.ghost.io/tic-tac-toe/). – lejlun Aug 04 '21 at 16:07
0

In order to compare both arrays, you can use the every() function, which will return true if all elements of an array pass a condition.

detectWinner = () => {
 
  for (let i = 0; i < board.length; i++) {

    var cScore = [...board[i]];   // this is the correct way of copy an array into another variable

    for (let j = 0; j < cScore.length; j++) console.log(board[i][j]);

    console.log(cScore);

    // I would compare the array using the every function
    if (cScore[i].every(e => e === 'x') || cScore[i].every(e => e === 'o')) {
      return true;
    }
  }
  return false;
};
AlexSp3
  • 2,201
  • 2
  • 7
  • 24