From c8bdf121d04c4cbf765d1b88ec7858a4d8c40b64 Mon Sep 17 00:00:00 2001 From: "Eevee (Evelyn Woods)" Date: Tue, 1 Sep 2020 05:51:26 -0600 Subject: [PATCH] Auto-size the game to fit the browser window --- js/main.js | 32 ++++++++++++++++++++++++++++++++ style.css | 10 +++++----- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/js/main.js b/js/main.js index 9f1071d..10faa88 100644 --- a/js/main.js +++ b/js/main.js @@ -977,6 +977,12 @@ class Game { this.demo_el.style.display = 'none'; } + // Auto-size the level canvas, both now and on resize + this.adjust_scale(); + window.addEventListener('resize', ev => { + this.adjust_scale(); + }); + this.frame = 0; this.tic = 0; requestAnimationFrame(this.do_frame.bind(this)); @@ -1215,6 +1221,32 @@ class Game { } } } + + // Auto-size the game canvas to fit the screen, if possible + adjust_scale() { + // TODO make this optional + // The base size is the size of the canvas, i.e. the viewport size + // times the tile size + let base_x = this.tileset.size_x * this.viewport_size_x; + let base_y = this.tileset.size_y * this.viewport_size_y; + // The main UI is centered in a flex item with auto margins, so the + // extra space available is the size of those margins + let style = window.getComputedStyle(this.container); + let extra_x = parseFloat(style['margin-left']) + parseFloat(style['margin-right']); + let extra_y = parseFloat(style['margin-top']) + parseFloat(style['margin-bottom']); + // The total available space, then, is the current size of the + // canvas plus the size of the margins + let total_x = extra_x + this.level_canvas.offsetWidth; + let total_y = extra_y + this.level_canvas.offsetHeight; + // Divide to find the biggest scale that still fits. But don't + // exceed 90% of the available space, or it'll feel cramped. + let scale = Math.floor(0.9 * Math.min(total_x / base_x, total_y / base_y)); + if (scale <= 0) { + scale = 1; + } + // FIXME this doesn't take into account the inventory, which is also affected by scale + this.container.style.setProperty('--scale', scale); + } } async function main() { diff --git a/style.css b/style.css index fc96404..68e8bea 100644 --- a/style.css +++ b/style.css @@ -91,7 +91,7 @@ main { --tile-width: 32px; --tile-height: 32px; - --scale: 2; + --scale: 1; } main > header { @@ -233,12 +233,12 @@ dl.score-chart .-sum { flex-wrap: wrap; align-items: start; - background-size: calc(2 * var(--tile-width)) calc(2 * var(--tile-height)); - width: calc(4 * var(--tile-width) * 2); - min-height: calc(2 * var(--tile-height) * 2); + background-size: calc(var(--tile-width) * var(--scale)) calc(var(--tile-height) * var(--scale)); + width: calc(4 * var(--tile-width) * var(--scale)); + min-height: calc(2 * var(--tile-height) * var(--scale)); } .inventory img { - width: calc(2 * var(--tile-width)); + width: calc(var(--tile-width) * var(--scale)); } .controls { grid-area: controls;