Skip to content

Instantly share code, notes, and snippets.

@DipanshKhandelwal
Created April 6, 2019 02:35
Show Gist options
  • Save DipanshKhandelwal/a489edd4929cce3528067d5fd165b0ad to your computer and use it in GitHub Desktop.
Save DipanshKhandelwal/a489edd4929cce3528067d5fd165b0ad to your computer and use it in GitHub Desktop.
An efficient win check for connect four game !!
checkWinner = ({ column, row, board }) => {
// ROW CHECK
for (var i = 0; i < 4; i++) {
if (column - 3 + i >= 0 && column + i < 7) {
if (this.checkLine(
board[column - 3 + i][row],
board[column - 2 + i][row],
board[column - 1 + i][row],
board[column - 0 + i][row],
)) {
return (board[column + i][row])
}
}
// COLUMN CHECK
if (row - 3 + i >= 0 && row + i < 6) {
if (this.checkLine(
board[column][row - 3 + i],
board[column][row - 2 + i],
board[column][row - 1 + i],
board[column][row - 0 + i],
)) {
return (board[column][row + i])
}
}
// DIAGONALS CHECK
if (row - 3 + i >= 0 && row + i < 6 && column - 3 + i >= 0 && column + i < 7) {
if (this.checkLine(
board[column - 3 + i][row - 3 + i],
board[column - 2 + i][row - 2 + i],
board[column - 1 + i][row - 1 + i],
board[column - 0 + i][row - 0 + i],
)) {
return (board[column + i][row + i])
}
}
if (row + 3 - i < 6 && row - i >= 0 && column - 3 + i >= 0 && column + i < 7) {
if (this.checkLine(
board[column - 3 + i][row + 3 - i],
board[column - 2 + i][row + 2 - i],
board[column - 1 + i][row + 1 - i],
board[column - 0 + i][row + 0 - i],
)) {
return (board[column + i][row - i])
}
}
}
return 0;
}
checkLine = (a, b, c, d) => {
// Check first cell non-zero and all cells match
return ((a != 0) && (a == b) && (a == c) && (a == d));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment