diff --git a/assets/scripts/nethack/dungeon.js b/assets/scripts/nethack/dungeon.js index 0886cd2..f11131b 100644 --- a/assets/scripts/nethack/dungeon.js +++ b/assets/scripts/nethack/dungeon.js @@ -81,58 +81,98 @@ class Rect { } class Grid { - #width; - #height; - cells = []; + #size; + #cells = []; + + #rooms = []; constructor(width, height) { - this.#width = width; - this.#height = height; + this.#size = new Size(width, height); - this.cells = new Array(width * height); - for (let i = 0; i < this.cells.length; i++) { - this.cells[i] = new Cell(" "); + this.#cells = new Array(width * height); + for (let i = 0; i < this.#cells.length; i++) { + this.#cells[i] = new Cell(" "); } } get width() { - return this.#width; + return this.#size.width; } get height() { - return this.#height; + return this.#size.height; + } + + generate(p, roomGenerator) { + this.#generateRooms(p, roomGenerator); + this.#placeStairs(); + } + + #generateRooms(p, generator) { + this.#rooms = generator.rooms; + + for (let room of this.#rooms) { + for (let y = room.minY; y <= room.maxY; y++) { + for (let x = room.minX; x <= room.maxX; x++) { + let charAtXY = room.charAt(x, y); + if (!charAtXY) { + continue; + } + + let cell = this.cellAt(x, y); + cell.character = charAtXY; + cell.characterColor = p.color(255); + } + } + } + } + + #placeStairs() { + const indexOfRoomWithUpStairs = randomInt(this.#rooms.length); + const coordinateOfUpStair = this.#rooms[indexOfRoomWithUpStairs].randomPoint(); + this.cellAt(coordinateOfUpStair.x, coordinateOfUpStair.y).upStair(); + + while (true) { + let indexOfRoomForDownStair = randomInt(this.#rooms.length); + if (indexOfRoomForDownStair == indexOfRoomWithUpStairs) { + continue; + } + + const coordinateOfDownStair = this.#rooms[indexOfRoomForDownStair].randomPoint(); + this.cellAt(coordinateOfDownStair.x, coordinateOfDownStair.y).downStair(); + + break; + } } cellAt(x, y) { - return this.cells[y * this.#width + x]; + return this.#cells[y * this.width + x]; } } class Room { - x = 0; - y = 0; - width = 0; - height = 0; + #rect; - constructor(x, y, w, h) { - this.x = x; - this.y = y; - this.width = w; - this.height = h; + constructor(rect) { + this.#rect = rect; } - get maxX() { - return this.x + this.width; - } + get minX() { return this.#rect.minX; } + get minY() { return this.#rect.minY; } + get maxX() { return this.#rect.maxX; } + get maxY() { return this.#rect.maxY; } - get maxY() { - return this.y + this.height; + randomPoint() { + return new Point( + this.#rect.minX + 1 + randomInt(this.#rect.size.width - 2), + this.#rect.minY + 1 + randomInt(this.#rect.size.height - 2) + ); } charAt(x, y) { - const minX = this.x; - const minY = this.y; - const maxX = this.maxX + const minX = this.minX; + const minY = this.minY; + const maxX = this.maxX; const maxY = this.maxY; if (y == minY && x == minX) { return "┌"; }