connect4-winner.js implemented

This commit is contained in:
leobr 2022-11-24 13:14:45 +01:00
parent c4968cedda
commit d1263e57e0
1 changed files with 76 additions and 0 deletions

76
code/connect4-winner.js Normal file
View File

@ -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))