boxes/js/graphics.mjs

66 lines
1.7 KiB
JavaScript

import * as graphics from "./graphics_core.mjs";
export * from "./graphics_core.mjs";
import { range, iter_2d } from "./utils/range.mjs";
import * as entity from "./entity.mjs";
import * as world from "./world.mjs";
const canvas = document.getElementById("canvas");
const canvas_context = canvas.getContext("2d");
graphics.set_size(canvas.width, canvas.height);
const BASE_SCALE = 81;
export function draw_tile (x, y, size = BASE_SCALE) {
graphics.fill_rect(x, y, size, size);
}
function checkerboard (x, y) {
return ((x ^ y) & 1) === 0;
}
export function draw_floor (start_x, start_y, scale) {
iter_2d(range(0, world.BOX_SIZE - 1), (x, y) => {
if (checkerboard(x, y)) {
graphics.set_color("#aaa");
} else {
graphics.set_color("#888");
}
const [visual_x, visual_y] = project_pos(x, y, scale);
draw_tile(start_x + visual_x, start_y + visual_y, scale);
});
}
export function draw_world (box, start_x = 0, start_y = 0, scale = BASE_SCALE) {
draw_floor(start_x, start_y, scale);
iter_2d(range(0, world.BOX_SIZE - 1), (x, y) => {
const tile = world.get_tile(box, x, y);
const [visual_x, visual_y] = project_pos(x, y, scale);
switch (tile.type) {
case "box": {
draw_world(tile.box, start_x + visual_x, start_y + visual_y, scale / world.BOX_SIZE);
break;
}
}
});
entity.for_each((entity, id) => {
if (entity.box !== box) return;
graphics.set_color(entity.color);
const [visual_x, visual_y] = project_pos(entity.x, entity.y, scale);
draw_tile(start_x + visual_x, start_y + visual_y, scale);
});
}
function project_pos (x, y, scale) {
return [x, y].map(a => a * scale);
}
export function render () {
graphics.render(canvas_context);
}