Move initialization code to Game class

This commit is contained in:
Manuel Thalmann 2022-12-13 11:00:26 +01:00
parent 5b46328d37
commit f542319b43
No known key found for this signature in database
GPG key ID: 5FD9AD3CCDDBD27B
3 changed files with 59 additions and 54 deletions

View file

@ -1,3 +1,5 @@
import { Constants } from "./Constants.js";
import { elt } from "./elt.js";
import { State } from "./State.js";
/**
@ -27,4 +29,60 @@ export class Game
{
return this.#state;
}
/**
* Gets the board of the game.
*/
get board()
{
return this.state.board;
}
/**
* Initializes the game.
*
* @param {string} id
* The id of the element to add the board to.
*/
initialize(id)
{
let board = document.getElementById(id);
board.innerHTML = "";
for (let i = 0; i < 6; i++)
{
for (let j = 0; j < 7; j++)
{
/** @type {Node[]} */
let children = [];
let playerId = this.board[i][j];
if (playerId !== "")
{
children.push(
elt(
"div",
{
class: `piece ${Constants.PLAYER_NAMES[playerId]}`
}));
}
let field = elt(
"div",
{
class: "field"
},
...children);
field.onclick = () =>
{
this.board[i][j] = this.state.currentPlayer;
this.state.turnCount++;
this.initialize(id);
};
board.appendChild(field);
}
}
}
}

View file

@ -1,52 +0,0 @@
import { Constants } from "./Constants.js";
import { elt } from "./elt.js";
/**
* Initializes the game board.
*
* @param {string} id
* The id of the element to add the board to.
*
* @param {import("./Game.js").Game} game
* The game that is being played.
*/
export function initializeBoard(id, game)
{
let board = document.getElementById(id);
board.innerHTML = "";
for (let i = 0; i < 6; i++)
{
for (let j = 0; j < 7; j++)
{
/** @type {Node[]} */
let children = [];
let playerId = game.state.board[i][j];
if (playerId !== "")
{
children.push(elt(
"div",
{
class: `piece ${Constants.PLAYER_NAMES[playerId]}`
}));
}
let field = elt(
"div",
{
class: "field"
},
...children);
field.onclick = () =>
{
game.state.board[i][j] = game.state.currentPlayer;
game.state.turnCount++;
initializeBoard("board", game);
};
board.appendChild(field);
}
}
}

View file

@ -1,4 +1,3 @@
import { initializeBoard } from "./board.js";
import { Game } from "./Game.js";
/**
@ -14,7 +13,7 @@ let game;
function initialize()
{
game = new Game();
initializeBoard("board", game);
game.initialize("board");
}
initialize();