From de2884c16d659751a205b4b2d941aacd471a4b6a Mon Sep 17 00:00:00 2001 From: Manuel Thalmann Date: Thu, 15 Dec 2022 01:13:18 +0100 Subject: [PATCH] Add a method for checking whether there is a winner --- src/js/Game.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/src/js/Game.js b/src/js/Game.js index 588cdd9..1ea794d 100644 --- a/src/js/Game.js +++ b/src/js/Game.js @@ -8,6 +8,11 @@ import { State } from "./State.js"; */ export class Game { + /** + * The number of chips required for a win. + */ + static #count = 4; + /** * The width of the board. */ @@ -74,6 +79,50 @@ export class Game return this.state.board; } + /** + * Gets the id of the player that is winning. + * + * @type {CellOwner} + */ + get winner() + { + for (let yOffset = 0; yOffset <= 1; yOffset++) + { + for (let xOffset = (yOffset === 1) ? -1 : 1; xOffset <= 1; xOffset++) + { + let lowerBound = Math.max(0, xOffset * (Game.#count - 1) * -1); + let upperBound = Math.min(Game.#width, Game.#width - (xOffset * (Game.#count - 1))); + + for (let y = 0; y < (Game.#height - yOffset * (Game.#count - 1)); y++) + { + for (let x = lowerBound; x < upperBound; x++) + { + /** + * @type {CellOwner[]} + */ + let tokens = []; + + for (let i = 0; i < Game.#count; i++) + { + tokens.push(this.board[y + i * yOffset][x + i * xOffset]); + } + + let player = tokens[0]; + + if ( + player !== "" && + tokens.every((token) => token === player)) + { + return player; + } + } + } + } + } + + return null; + } + /** * Dumps the state of the game. *