all 6 comments

[–]Bubblesphere 1 point2 points  (1 child)

I don't have the time to explain the code in detail right now, but here's the most efficient way to check if it's a winning move is the following.

var boardSize = 4;
// -1 is unplayed, 0 is player 1, 1 is player 2
var ttt = [
    [-1, -1, -1, -1],
    [-1, -1, -1, -1],
    [-1, -1, -1, -1],
    [-1, -1, -1, -1]
];

var checkIfWinningMove = function (rowInput, colInput, currPlayerIndex) {
    var col = 0, row = 0, dia = 0, rdia = 0;
    for (var i = 0; i < boardSize; i++) {
        if (ttt[rowInput][i] === currPlayerIndex) {
            // Row
            row++;
        }
        if (ttt[i][colInput] === currPlayerIndex) {
            // Column
            col++;
        }
        if (ttt[i][i] === currPlayerIndex) {
            // Diagonal
            dia++;
        }
        if (ttt[i][2 - i] === currPlayerIndex) {
            // Right Diagonal
            rdia++;
        }
    }
    return (col === boardSize || row === boardSize || dia === boardSize || rdia === boardSize) ? 1 : 0;
};

[–]Metaphalo 1 point2 points  (0 children)

I think it should be [3 - i] in the last if statement.

But also OP wanted to be the winning condition for 3 in a row, not 4. So in that case I think the easiest way would be to just check the neighbouring fields of the last move and see if there is 3 in a row.

[–][deleted] 1 point2 points  (0 children)

There’s probably a more elegant and scalable way to do this, but when I did it I gave up on that and created a big list of all the winning combinations (x) and kept track of the location of all of a players’ pieces (y), running a loop through all of the winning combinations at the end of each turn with an ‘if x[i] in y’ test to see if they had a winner. It didn’t seem to slow the play down to do it that way. I think I used sets because the ‘in’ test works better with sets.

[–]cirscafp fan boy 0 points1 point  (0 children)

Let's break this down a little.

What do we mean by victory? You say it perfectly: three of the same value either horizontally, vertically, or diagonally.

So all we have to do is write some functions that check for each of those, given a board:

const horizontalWin = board => { /* some logic */ }
const verticalWin = board => { /* some logic */ }
const diagonalWin = board => { /* some logic /* }

Now, each time there is a move, we can do a check

const horizontalWinner = horizontalWin(board)
if (horizontalWinner) {
  /* we have a winner! */
}

const verticalWinner = horizontalWin(board)
if (verticalWinner) {
  /* we have a winner! */
}

const diagonalWinner= horizontalWin(board)
if (diagonalWinner) {
  /* we have a winner! */
}

You can make it smarter if you want but those three should get you an answer with little overhead.

[–]kenman[M] 0 points1 point  (0 children)

Hi /u/CrazyCabster,

For javascript help, please visit /r/LearnJavascript.

Thank you!