Refactor adjacent-tile checks

This commit is contained in:
Tangent Wantwight 2024-01-13 15:19:58 -05:00
parent 2b37385439
commit 4d2596fe33
1 changed files with 22 additions and 21 deletions

View File

@ -105,10 +105,7 @@ export class IslandGrid {
// try to roll in cardinal directions
check((pos - this.width) % this.data.length);
check((pos - 1) % this.data.length);
check((pos + 1) % this.data.length);
check((pos + this.width) % this.data.length);
this.forCardinals(pos, check);
if (lowerNeighbors.length > 0) {
const downhill = lowerNeighbors[this.rng() % lowerNeighbors.length];
@ -117,10 +114,7 @@ export class IslandGrid {
// try to roll in diagonal directions
check((pos - this.width - 1) % this.data.length);
check((pos - this.width + 1) % this.data.length);
check((pos + this.width - 1) % this.data.length);
check((pos + this.width + 1) % this.data.length);
this.forDiagonals(pos, check);
if (lowerNeighbors.length > 0) {
const downhill = lowerNeighbors[this.rng() % lowerNeighbors.length];
@ -134,22 +128,13 @@ export class IslandGrid {
public sinkhole(pos: number): void {
const higherNeighbors: number[] = [];
const check = (adjPos: number) => {
// try to pull from neighbors
this.forNeighbors(pos, (adjPos: number) => {
if (this.data[adjPos] > this.data[pos]) {
higherNeighbors.push(adjPos);
}
};
// try to pull from neighbors
check((pos - this.width - 1) % this.data.length);
check((pos - this.width) % this.data.length);
check((pos - this.width + 1) % this.data.length);
check((pos - 1) % this.data.length);
check((pos + 1) % this.data.length);
check((pos + this.width - 1) % this.data.length);
check((pos + this.width) % this.data.length);
check((pos + this.width + 1) % this.data.length);
});
if (higherNeighbors.length > 0) {
const uphill = higherNeighbors[this.rng() % higherNeighbors.length];
@ -160,6 +145,22 @@ export class IslandGrid {
this.data[pos] = Math.max(this.data[pos] - 1, -3);
}
public forCardinals(pos: number, action: (adjPos: number) => void) {
action((pos - this.width) % this.data.length);
action((pos - 1) % this.data.length);
action((pos + 1) % this.data.length);
action((pos + this.width) % this.data.length);
}
public forDiagonals(pos: number, action: (adjPos: number) => void) {
action((pos - this.width - 1) % this.data.length);
action((pos - this.width + 1) % this.data.length);
action((pos + this.width - 1) % this.data.length);
action((pos + this.width + 1) % this.data.length);
}
public forNeighbors(pos: number, action: (adjPos: number) => void) {
this.forCardinals(pos, action);
this.forDiagonals(pos, action);
}
public choose<T>(list: T[]) {
if (list.length == 0) {
throw new Error("Picking from empty list");