From b28dcba597588d9869cbf3786f87e79c92a4e89b Mon Sep 17 00:00:00 2001 From: HyperOnion <> Date: Sat, 24 Jun 2023 19:16:16 +0200 Subject: [PATCH] refactor graphics code. separate tile drawing from box/world drawing, and simplify some of the math. --- js/graphics.mjs | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/js/graphics.mjs b/js/graphics.mjs index 7406eee..6ede0e8 100644 --- a/js/graphics.mjs +++ b/js/graphics.mjs @@ -13,7 +13,7 @@ graphics.set_size(canvas.width, canvas.height); const BASE_SCALE = 81; -export function draw_tile (x, y, size = BASE_SCALE) { +export function draw_rect (x, y, size = BASE_SCALE) { graphics.fill_rect(x, y, size, size); } @@ -28,8 +28,7 @@ export function draw_floor (start_x, start_y, scale, invert = false) { } 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); + draw_rect(x * scale + start_x, y * scale + start_y, scale); }); } @@ -38,29 +37,32 @@ export function draw_world (box, start_x = 0, start_y = 0, scale = BASE_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; - } - case "paint": { - graphics.set_color(tile.color); - draw_tile(start_x + visual_x, start_y + visual_y, scale); - break; - } - } + draw_tile(tile, x * scale + start_x, y * scale + start_y, scale); }); 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); + draw_rect(start_x + visual_x, start_y + visual_y, scale); }); } +function draw_tile (tile, x, y, scale) { + switch (tile.type) { + case "box": { + // recursively draw box contents. + draw_world(tile.box, x, y, scale / world.BOX_SIZE); + break; + } + case "paint": { + graphics.set_color(tile.color); + draw_rect(x, y, scale); + break; + } + } +} + function project_pos (x, y, scale) { return [x, y].map(a => a * scale); }