diff --git a/island.ts b/island.ts index c140b4b..bf03ab1 100644 --- a/island.ts +++ b/island.ts @@ -35,6 +35,38 @@ class IslandGrid { this.data[this.xy(x, y)] = tile; console.log(x, y, this.xy(x, y), this.data[this.xy(x, y)]); } + + public floodSearch( + startPos: number, + shouldExpand: (tile: number) => boolean + ): number[] { + const len = this.data.length; + const width = this.width; + const seen = new Uint8Array(len); + + const hitPositions: number[] = []; + + function enqueue(pos: number) { + if (!seen[pos]) { + hitPositions.push(pos); + seen[pos] = 1; + } + } + + enqueue(startPos); + + for (let i = 0; i < hitPositions.length; i++) { + const pos = hitPositions[i]; + if (shouldExpand(this.data[pos])) { + enqueue((pos - width) % len); + enqueue((pos - 1) % len); + enqueue((pos + 1) % len); + enqueue((pos + width) % len); + } + } + + return hitPositions; + } } function renderIslands(islands: IslandGrid, cx: CanvasRenderingContext2D) { @@ -75,6 +107,9 @@ export function IslandApplet() { const y = islands.rng(); islands.set(x, y, 1); + islands + .floodSearch(islands.xy(x, y), (tile) => tile > 0) + .forEach((pos) => islands.data[pos]++); renderIslands(islands, cx);