From f6fa2759a6dce5379554d7294f00487bb1565004 Mon Sep 17 00:00:00 2001 From: Jean-Marie Mineau Date: Fri, 14 May 2021 00:10:37 +0200 Subject: [PATCH] use a more compact memory rep --- index.js | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 090aeef..0d5f7cc 100644 --- a/index.js +++ b/index.js @@ -7,7 +7,13 @@ const GRID_COLOR = "#444444"; const DEAD_COLOR = "#000000"; const ALIVE_COLOR = "#FFFFFF"; -const universe = Universe.new_space_ship(); +const seed = Math.random(); +const universe = ((seed) => { + if (seed < 1/3) return Universe.new(); + else if (seed < 2/3) return Universe.new_random(); + else return Universe.new_space_ship(); +})(seed); + const width = universe.width(); const height = universe.height(); @@ -59,7 +65,7 @@ const getIndex = (row, column) => { const drawCells = () => { const cellsPtr = universe.cells(); - const cells = new Uint8Array(memory.buffer, cellsPtr, width * height); + const cells = new Uint8Array(memory.buffer, cellsPtr, width * height / 8); ctx.beginPath(); @@ -67,9 +73,9 @@ const drawCells = () => { for (let col = 0; col < width; col++) { const i = getIndex(row, col); - ctx.fillStyle = cells[i] === Cell.Dead - ? DEAD_COLOR - : ALIVE_COLOR; + ctx.fillStyle = bitIsSet(i, cells) + ? ALIVE_COLOR + : DEAD_COLOR; ctx.fillRect( col * (CELL_SIZE + 1) + 1, @@ -83,4 +89,10 @@ const drawCells = () => { ctx.stroke(); } +const bitIsSet = (n, arr) => { + const byte = Math.floor(n / 8); + const mask = 1 << (n % 8); + return (arr[byte] & mask) === mask; +} + requestAnimationFrame(renderLoop);