diff --git a/packages/game/src/js/connect4-winner.js b/packages/game/src/js/connect4-winner.js new file mode 100644 index 0000000..87b8d0f --- /dev/null +++ b/packages/game/src/js/connect4-winner.js @@ -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));