OK, fine, draw the map

This commit is contained in:
2025-02-01 22:04:40 -08:00
parent 501d0e4dff
commit 46a249352d
8 changed files with 227 additions and 71 deletions

View File

@ -66,6 +66,10 @@ export class Point {
negate() {
return new Point(-this.x, -this.y);
}
equals(other: Point): boolean {
return this.x == other.x && this.y == other.y;
}
}
export class Size {
@ -79,17 +83,19 @@ export class Size {
}
export class Grid<T> {
data: T[][];
readonly size: Size;
#data: T[][];
constructor({size, cbDefault}: {size: Size, cbDefault: (xy: Point) => T}) {
this.data = [];
constructor(size: Size, cbDefault: (xy: Point) => T) {
this.size = size;
this.#data = [];
for (let y = 0; y < size.h; y++) {
let row = [];
for (let x = 0; x < size.w; x++) {
row.push(cbDefault(new Point(x, y)))
}
this.data.push(row);
this.#data.push(row);
}
}
@ -105,12 +111,12 @@ export class Grid<T> {
w = w1;
}
return new Grid({
size: new Size(w, h),
cbDefault: (xy) => {
return new Grid(
new Size(w, h),
(xy) => {
return ary[xy.y].charAt(xy.x);
}
})
)
}
static createGridFromJaggedArray<T>(ary: Array<Array<T>>): Grid<T> {
@ -125,12 +131,35 @@ export class Grid<T> {
w = w1;
}
return new Grid({
size: new Size(w, h),
cbDefault: (xy) => {
return new Grid(
new Size(w, h),
(xy) => {
return ary[xy.y][xy.x];
}
})
)
}
map<T2>(cbCell: (content: T, position: Point) => T2) {
return new Grid(this.size, (xy) => cbCell(this.get(xy), xy));
}
#checkPosition(position: Point) {
if (
(position.x < 0 || position.x >= this.size.w || Math.floor(position.x) != position.x) ||
(position.y < 0 || position.y >= this.size.h || Math.floor(position.y) != position.y)
) {
throw `invalid position for ${this.size}: ${position}`
}
}
get(position: Point): T {
this.#checkPosition(position);
return this.#data[position.y][position.x];
}
set(position: Point, value: T) {
this.#checkPosition(position);
this.#data[position.y][position.x] = value;
}
}

View File

@ -41,7 +41,6 @@ export class Sprite {
let srcCy = Math.floor(ix / this.cellsPerSheet.w);
let srcPx = srcCx * this.pixelsPerSubimage.w;
let srcPy = srcCy * this.pixelsPerSubimage.h;
console.log(`src px and py ${srcPx} ${srcPy}`)
ctx.drawImage(me, srcPx, srcPy, this.pixelsPerSubimage.w, this.pixelsPerSubimage.h, 0, 0, this.pixelsPerSubimage.w, this.pixelsPerSubimage.h);
}
}