2024.js/island.ts

85 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-01-12 20:46:09 -05:00
import { canvas2d } from "./lib/html";
2024-01-12 21:36:45 -05:00
import { Prng, mulberry32 } from "./lib/prng";
2024-01-12 20:46:09 -05:00
2024-01-12 20:21:58 -05:00
const BLOWUP = 4;
const WIDTH = 240;
const HEIGHT = 135;
2024-01-12 21:21:09 -05:00
type Lookup2d = (x: number, y: number) => number;
function dim(width: number, height: number): Lookup2d {
return function xy(x: number, y: number) {
return (
(((x % width) + width) % width) +
width * (((y % height) + height) % height)
);
};
}
class IslandGrid {
data: number[];
2024-01-12 21:36:45 -05:00
rng: Prng;
2024-01-12 21:21:09 -05:00
xy: Lookup2d;
2024-01-12 21:36:45 -05:00
constructor(public width: number, public height: number, seed: number) {
2024-01-12 21:21:09 -05:00
this.data = Array(width * height).fill(0);
2024-01-12 21:36:45 -05:00
this.rng = mulberry32(seed);
2024-01-12 21:21:09 -05:00
this.xy = dim(width, height);
}
2024-01-12 21:36:00 -05:00
public get(x: number, y: number): number {
return this.data[this.xy(x, y)];
}
public set(x: number, y: number, tile: number) {
this.data[this.xy(x, y)] = tile;
console.log(x, y, this.xy(x, y), this.data[this.xy(x, y)]);
}
2024-01-12 21:21:09 -05:00
}
function renderIslands(islands: IslandGrid, cx: CanvasRenderingContext2D) {
for (let y = 0; y < islands.height; y++) {
for (let x = 0; x < islands.width; x++) {
const tile = islands.data[islands.xy(x, y)];
switch (tile) {
case 0:
cx.fillStyle = "blue";
break;
case 1:
cx.fillStyle = "yellow";
break;
case 2:
cx.fillStyle = "#00ff00";
break;
case 3:
cx.fillStyle = "#008800";
break;
default:
cx.fillStyle = "#666666";
break;
}
cx.fillRect(x, y, 1, 1);
}
}
}
2024-01-12 20:21:58 -05:00
export function IslandApplet() {
2024-01-12 20:46:09 -05:00
const [canvas, cx] = canvas2d({
2024-01-12 20:21:58 -05:00
width: WIDTH * BLOWUP,
height: HEIGHT * BLOWUP,
2024-01-12 20:46:09 -05:00
});
2024-01-12 20:21:58 -05:00
cx.scale(BLOWUP, BLOWUP);
2024-01-12 21:36:45 -05:00
const islands = new IslandGrid(WIDTH, HEIGHT, 128);
const x = islands.rng();
const y = islands.rng();
islands.set(x, y, 1);
2024-01-12 21:21:09 -05:00
renderIslands(islands, cx);
2024-01-12 20:21:58 -05:00
return [canvas];
}
(globalThis as any).IslandApplet = IslandApplet;