Store state as an object

This commit is contained in:
Manuel Thalmann 2022-12-15 11:51:59 +01:00
parent c94dc1cb8f
commit e6cea57d65
No known key found for this signature in database
GPG key ID: 5FD9AD3CCDDBD27B
2 changed files with 20 additions and 49 deletions

View file

@ -25,7 +25,7 @@ export class Game
/**
* The state of the game.
*
* @type {State}
* @type {IState}
*/
#state;
@ -45,7 +45,7 @@ export class Game
constructor(id)
{
this.id = id;
this.#state = new State(Game.#width, Game.#height);
this.#state = State.create(Game.#width, Game.#height);
}
/**
@ -66,10 +66,12 @@ export class Game
/**
* Gets the current player.
*
* @type {CellOwner}
*/
get currentPlayer()
{
return this.state.currentPlayer;
return this.state.turnCount % 2 === 0 ? "r" : "b";
}
/**
@ -126,9 +128,7 @@ export class Game
{
return {
turnCount: this.state.turnCount,
board: {
...this.state.board
}
board: this.state.board
};
}
@ -140,10 +140,7 @@ export class Game
*/
load(data)
{
this.state.turnCount = data.turnCount;
this.state.board.splice(0);
this.#state = new State(Game.#width, Game.#height);
Object.assign(this.state.board, data.board);
this.#state = data;
this.draw();
}
@ -160,7 +157,7 @@ export class Game
*/
reset()
{
this.#state = new State(Game.#width, Game.#height);
this.#state = State.create(Game.#width, Game.#height);
this.draw();
}
@ -194,7 +191,7 @@ export class Game
{
if (this.board[i][x] === "")
{
this.board[i][x] = this.state.currentPlayer;
this.board[i][x] = this.currentPlayer;
return true;
}
}

View file

@ -4,52 +4,26 @@
export class State
{
/**
* The board of the game.
*
* @type {Board}
*/
#board;
/**
* The number of turns that have been played.
*/
turnCount = 0;
/**
* Initializes a new instance of the {@link State `State`} class.
* Creates a new state.
*
* @param {number} width
* The width of the board.
*
* @param {number} height
* The height of the board.
*
* @returns {IState}
* The newly created state.
*/
constructor(width, height)
static create(width, height)
{
this.#board = /** @type {Board} */ (
Array(height).fill("").map(
return {
turnCount: 0,
board: Array(height).fill("").map(
() =>
{
return Array(width).fill(
/** @type {CellOwner} */ (""));
}));
}
/**
* Gets the id of the current player.
*
* @type {CellOwner}
*/
get currentPlayer()
{
return this.turnCount % 2 === 0 ? "r" : "b";
}
/**
* Gets the board of the game.
*/
get board()
{
return this.#board;
return Array(width).fill("");
})
};
}
}