diff --git a/code/connect4-winner.js b/code/connect4-winner.js new file mode 100644 index 0000000..7ce9d27 --- /dev/null +++ b/code/connect4-winner.js @@ -0,0 +1,76 @@ +let testBoard = [ + [ '_', '_', '_', '_', '_', '_', '_' ], + [ '_', '_', '_', '_', '_', '_', '_' ], + [ '_', '_', '_', 'r', 'r', 'r', '' ], + [ '_', '_', '_', 'r', 'r', 'b', 'b' ], + [ '_', '_', 'r', 'b', 'r', '', 'b' ], + [ 'b', 'r', 'b', 'r', 'r', 'b', 'r' ] +] + +let checkLine = function (color, board, y, x, length){ + if (length === 4){ + return true; + } else if(y === board.length || x === board[1].length){ + return false + } + else if(board[y][x+1] === color){ + return checkLine(color, board,y, x+1, length + 1) + } else { + return false; + } +} +let checkDownRight = function (color,board, y, x, length){ + if (length === 4){ + return true; + } else if((y + 1) === board.length || (x + 1) === board[1].length){ + return false + } + else if(board[y+1][x+1] === color){ + return checkDownRight(color,board,y + 1, x + 1, length + 1) + } else { + return false; + } +} +let checkDownLeft = function (color,board, y, x, length){ + if (length === 4){ + return true; + } else if((y + 1) === board.length || (x - 1)< 0){ + return false + } + else if(board[y+1][x-1] === color){ + return checkDownLeft(color,board,y + 1, x - 1, length + 1) + } else { + return false; + } +} + +let checkDown = function (color,board, y, x, length){ + if (length === 4){ + return true; + } else if((y + 1)=== board.length){ + return false + } + else if(board[y + 1][x] === color){ + return checkDown(color,board,y + 1, x, length + 1) + } else { + return false; + } +} + + +let connect4Winner = function (color, board) { + for(let y = 0; y < board.length; y++){ + for(let x = 0; x < board[y].length; x++){ + if(board[y][x] === color){ + if (checkLine(color,board,y,x,1) || checkDown(color,board,y,x,1) || checkDownRight(color,board,y,x,1) || checkDownLeft(color,board,y,x,1)){ + console.log('win') + return true; + } + } + } + } + return false; +} + + +console.log(connect4Winner('r', testBoard)) \ No newline at end of file