Skip to content

Instantly share code, notes, and snippets.

@railsstudent
Created July 27, 2018 10:32
Show Gist options
  • Save railsstudent/3b54927152de1f2de0792c59515e09c5 to your computer and use it in GitHub Desktop.
Save railsstudent/3b54927152de1f2de0792c59515e09c5 to your computer and use it in GitHub Desktop.
check if a piece can win a connect 4 game
const COLUMNS = 7;
const ROWS = 6;
const grid = [];
const height = []; // next available row at column j
for (let j = 0; j < COLUMNS; j++) {
height.push(0);
for (let i = 0; i < ROWS; i++) {
grid.push('-');
}
}
const convertRowColToIdx = (row, col) => {
if (row >= 0 && row < ROWS && col >= 0 && col < COLUMNS) {
return row * COLUMNS + col;
}
return -1;
}
const canPlay = (column) => {
if (column < 0 || column >= COLUMNS) {
return false;
}
return height[column] < ROWS;
}
const play = (column, player) => {
const idx = convertRowColToIdx(height[column], column);
grid[idx] = player;
height[column]++;
}
// console.log(grid);
console.log(canPlay(0));
console.log(canPlay(1));
console.log(canPlay(2));
console.log(canPlay(3));
console.log(canPlay(4));
console.log(canPlay(5));
grid[3] = grid[10] = grid[17] = grid[24] = grid[31] = grid[35] = '1';
console.log(canPlay(3));
const isWinningPiece = (col, player) => {
if (!canPlay(col)) {
return false;
}
// check vertical
if (height[col] >= 3) {
if (height[col - 1] === player || height[col - 2] === player || height[col - 3] === player) {
return true;
}
}
// check horizontal
for (let x = 3; x >= 0; x--) {
let pieces = 0;
for (let delta = -3; delta <= 0; delta++) {
if (delta !== x) {
let colIdx = col + delta + x;
if (colIdx >= 0 && colIdx < COLUMNS) {
let idx = convertRowColToIdx(height[col], colIdx);
if (grid[idx] === player) {
pieces += 1;
}
}
}
}
if (pieces === 3) {
return true;
}
}
// check left diagonal
for (let x = 3; x >= 0; x--) {
let pieces = 0;
for (let delta = -3; delta <= 0; delta++) {
if (delta !== x) {
let colIdx = col + delta + x;
let rowIdx = height[col] - (delta + x);
if (colIdx >= 0 && colIdx < COLUMNS) {
let idx = convertRowColToIdx(height[col] - colIdx, colIdx);
if (grid[idx] === player) {
pieces += 1;
}
}
}
}
if (pieces === 3) {
return true;
}
}
// check right diagonal
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment