Add a script for checking for a winner
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed

This commit is contained in:
Manuel Thalmann 2022-12-14 22:01:08 +01:00
parent fd172a48ed
commit 2d0b47f603
No known key found for this signature in database
GPG key ID: 5FD9AD3CCDDBD27B

View file

@ -0,0 +1,69 @@
let testBoard = [
["_", "_", "_", "_", "_", "_", "_"],
["_", "_", "_", "_", "_", "_", "_"],
["_", "_", "_", "_", "r", "_", "_"],
["_", "_", "_", "r", "r", "b", "b"],
["_", "_", "r", "b", "r", "r", "b"],
["b", "b", "b", "r", "r", "b", "b"]
];
/**
* Checks whether the specified {@link player `player`} is a winner according to the specified {@link board `board`}.
*
* @param {string} player
* The player to check for.
*
* @param {string[][]} board
* The board to check.
*
* @param {number} count
* The number of chips which need to be set in a row.
*
* @param {number} width
* The width of the board.
*
* @param {number} height
* The height of the board.
*
* @returns {boolean}
* A value indicating whether the specified {@link player `player`} did win.
*/
function connect4Winner(player, board, count = 4, width = 7, height = 6)
{
for (let yOffset = 0; yOffset <= 1; yOffset++)
{
for (let xOffset = (-1 * yOffset) + (1 - yOffset); xOffset <= 1; xOffset++)
{
let lowerBound = Math.max(0, xOffset * (count - 1) * -1);
let upperBound = Math.min(width, width - (xOffset * (count - 1)));
for (let y = 0; y < (height - yOffset * (count - 1)); y++)
{
for (let x = lowerBound; x < upperBound; x++)
{
/**
* @type {string[]}
*/
let tokens = [];
for (let index = 0; index < count; index++)
{
tokens.push(board[y + index * yOffset][x + index * xOffset]);
}
if (tokens.every((token) => token === player))
{
return true;
}
}
}
}
}
return false;
}
module.exports = { connect4Winner };
console.log(connect4Winner("r", testBoard));
console.log(connect4Winner("b", testBoard));