Tic Tac Toe

How to detect wins

Remember 2d arrays?

const ticTacToe = [
  [ '', '', '' ],
  [ '', '', '' ],
  [ '', '', '' ],
];

This can represent an empty tic tac toe board.

As moves are made we can update the elements of this 2d array with 'X' and 'O' to record where moves have been made.

Let’s change how we build our cells

Change our loop to a nested loop:

for (let r = 0; r < 3; r++) {
  for (let c = 0; c < 3; c++) {
    const cell = document.createElement('cell');
    cell.onclick = (e) => {
      // same stuff as before

      // Update our board array when a move is made
      ticTacToe[r][c] = cell.innerText;
    }
    board.append(cell);
  }
}

A bit of magic

Remember when I said variables only exist within the body where they are defined?

for (let r = 0; r < 3; r++) {
  // r is only meaningful in here
}
// r doesn't exist here, outside the body of the loop

Let’s look more closely

for (let r = 0; r < 3; r++) {
  for (let c = 0; c < 3; c++) {
    const cell = document.createElement('cell');
    cell.onclick = (e) => {
      // stuff
      ticTacToe[r][c] = cell.innerText;
    }
    board.append(cell);
  }
}

The line ticTacToe[r][c] = ... is inside the the loops where r and c are meaningful, so that seems fine.

But ..

for (let r = 0; r < 3; r++) {
  for (let c = 0; c < 3; c++) {
    const cell = document.createElement('div');
    cell.onclick = (e) => {
      // stuff
      ticTacToe[r][c] = cell.innerText;
    }
    board.append(cell);
  }
}

On the other hand, the code in the function isn’t going to run until after the loops have finished, when the user actually clicks a cell.

Will this work? What does it mean to refer to variables that won’t exist any more when the code runs?

Turns out it’s fine.

The function we create in the loop “captures” or “closes over” the variables r and c.

Each cell will have a slightly different onclick function, that differs in the values of r and c that have been captured.

Check for a winner

const checkForWinner = () => {
}

Fill out this function to check whether there are three in a row in any row, column, or diagonal.

May want to break it down into some smaller functions, e.g. one that checks a single row, or a single column, etc.

Some hints

You will probably need to use some loops.

Though if you get stuck on that, do it without loops and then we’ll see if we can remove some duplication with some loops.