From 338fefc601cceae68af7adbb47f7a67ec610f440 Mon Sep 17 00:00:00 2001 From: Kacper Wyczawski Date: Sun, 21 Jul 2024 17:09:22 +0200 Subject: [PATCH] feat: load maps from .txt file --- src/board.ts | 21 ++++++++++++++------- src/game.ts | 12 +----------- src/maps.txt | 22 ++++++++++++++++++++++ 3 files changed, 37 insertions(+), 18 deletions(-) create mode 100644 src/maps.txt diff --git a/src/board.ts b/src/board.ts index 79c3631..302a14b 100644 --- a/src/board.ts +++ b/src/board.ts @@ -1,5 +1,6 @@ import { Cell } from "./cell"; import { Pawn } from "./pieces/pawn"; +import maps from "./maps.txt?raw"; export class Board { #cells: Cell[][] = []; @@ -10,16 +11,22 @@ export class Board { constructor( HTMLTable: HTMLTableElement, - template: string, + mapName: string, onCellClick: (clickedCell: Cell) => void, onCastleClick: (clickedCell: Cell) => void, ) { + const map = maps + .split("\n\n") + .find((s) => s.startsWith(mapName)) + ?.replace(/^.*\n/, "") + ?.split("\n") + + if (!map) { + throw new Error("there is no map with this name"); + } + const HTMLBody = HTMLTable.createTBody(); - template - .replace(/ /g, "") - .split("\n") - .filter((row) => row.length > 0) - .forEach((row, y) => { + map.forEach((row, y) => { const HTMLRow = HTMLBody.insertRow(); this.#cells[y] = []; for (const symbol of row.split("")) { @@ -32,7 +39,7 @@ export class Board { }; this.#cells[y].push(cell); - if (symbol === "-") { + if (symbol === ".") { } else if (symbol === "1") { cell.placePiece(new Pawn("white"), true); cell.setBuilding("castle"); diff --git a/src/game.ts b/src/game.ts index b26a75b..2825ce6 100644 --- a/src/game.ts +++ b/src/game.ts @@ -13,17 +13,7 @@ export class Game { constructor(HTMLTable: HTMLTableElement) { this.#board = new Board( HTMLTable, - ` - --------- - -1--c--c- - ----w---- - ---w----- - -cw-c-wc- - -----w--- - ----w---- - -c--c--2- - --------- - `, + "canyon", (clickedCell) => { // place piece if (this.#selectedCell?.piece) { diff --git a/src/maps.txt b/src/maps.txt new file mode 100644 index 0000000..eb77aac --- /dev/null +++ b/src/maps.txt @@ -0,0 +1,22 @@ +canyon +......... +.1..c..c. +....w.... +...w..... +.cw.c.wc. +.....w... +....w.... +.c..c..2. +......... + +trenches +......... +.1..1..1. +.w..w..w. +......... +......... +......... +......... +.w..w..w. +.2..2..2. +.........