Compare commits

...

3 commits

Author SHA1 Message Date
8020d30d6b
Add a message if someone wins
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-12-15 01:16:28 +01:00
05c935d3fa
Only allow moves if there is no winner 2022-12-15 01:13:49 +01:00
de2884c16d
Add a method for checking whether there is a winner 2022-12-15 01:13:18 +01:00

View file

@ -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.
*
@ -189,7 +238,9 @@ export class Game
{
className: this.state.currentPlayer
},
`It's player "${Constants.PLAYER_NAMES[this.state.currentPlayer]}"s turn`
this.winner ?
`Player ${Constants.PLAYER_NAMES[this.winner]} wins!` :
`It's player "${Constants.PLAYER_NAMES[this.state.currentPlayer]}"s turn`
],
this.#log);
}
@ -208,12 +259,15 @@ export class Game
*/
addChip(x, y)
{
for (let i = Game.#height - 1; i >= 0; i--)
if (!this.winner)
{
if (this.board[i][x] === "")
for (let i = Game.#height - 1; i >= 0; i--)
{
this.board[i][x] = this.state.currentPlayer;
return true;
if (this.board[i][x] === "")
{
this.board[i][x] = this.state.currentPlayer;
return true;
}
}
}