Skip to content

Instantly share code, notes, and snippets.

@lior-amsalem
Created October 17, 2021 18:38
Show Gist options
  • Save lior-amsalem/e1b3e4e8d347a150e553005be1df2d39 to your computer and use it in GitHub Desktop.
Save lior-amsalem/e1b3e4e8d347a150e553005be1df2d39 to your computer and use it in GitHub Desktop.
Connect Four is a game in which two players take turns dropping red or yellow colored discs into a vertically suspended 7 x 6 grid. Discs fall to the bottom of the grid, occupying the next available space. in this function we'll resolve if the game is done/won given array
/**
array of game for example:
[['-','-','-','-','-','-','-'],
['-','-','-','-','-','-','-'],
['-','-','-','R','R','R','R'],
['-','-','-','Y','Y','R','Y'],
['-','-','-','Y','R','Y','Y'],
['-','-','Y','Y','R','R','R']];
**/
function checkList(list = []) {
return list.map((k,i) => (k === list[i+1] && k === list[i+2] && k === list[i+3]) && k !== '-' ? k : null).filter(k => k)[0] || null;
}
function connectFour(board) {
let winner = null;
let horizontalList = [];
let diagonallyBottomRight = [];
let diagonallyBottomLeft = [];
let firstLineIsEmpty = board[0].filter(value => value === '-').length >= 7;
let nextRow = [];
let currentRow = []
let horizontal = '';
for(let a=0; a<=board.length;a++) {
currentRow = board[a] || [];
winner = checkList(currentRow);
horizontalList = [];
if(winner) {
break;
}
for(let b=0;b<7;b++) {
horizontal = board[b] ? board[b][a] : null;
if(horizontal) {
horizontalList.push(horizontal);
}
let cell = currentRow[b];
diagonallyBottomRight = [];
diagonallyBottomLeft = [];
if(cell != '-') {
for(let c=0;c<6;c++) {
nextRow = board[a+c] || null;
if(!nextRow) {
continue;
}
diagonallyBottomRight.push(nextRow[b+c]);
diagonallyBottomLeft.push(nextRow[b-c]);
}
winner = checkList(diagonallyBottomLeft) || checkList(diagonallyBottomRight);
if(winner) {
break;
}
}
}
if(winner) {
break;
}
winner = checkList(horizontalList);
if(winner) {
break;
}
}
if(winner) {
return winner;
}
if(!winner && firstLineIsEmpty) {
return 'in progress';
}
return winner || 'draw';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment