wasm-game-of-life-www/index.js

87 lines
1.9 KiB
JavaScript
Raw Normal View History

2021-05-11 21:43:24 +02:00
import { Universe, Cell } from "wasm-game-of-life";
// Import wasm memory
import { memory } from "wasm-game-of-life/wasm_game_of_life_bg";
2021-05-11 21:52:01 +02:00
const CELL_SIZE = 5; // px
2021-05-11 22:39:07 +02:00
const GRID_COLOR = "#444444";
const DEAD_COLOR = "#000000";
const ALIVE_COLOR = "#FFFFFF";
2021-05-11 00:02:50 +02:00
2021-05-13 01:00:01 +02:00
const universe = Universe.new_space_ship();
2021-05-11 21:43:24 +02:00
const width = universe.width();
const height = universe.height();
const canvas = document.getElementById("game-of-life-canvas");
canvas.height = (CELL_SIZE + 1) * height + 1;
canvas.width = (CELL_SIZE + 1) * width + 1;
const ctx = canvas.getContext('2d');
2021-05-11 17:31:39 +02:00
2021-05-11 21:52:01 +02:00
const PERIODE = 100; // ms
let start;
const renderLoop = (timestamp) => {
2021-05-11 21:43:24 +02:00
drawGrid();
drawCells();
2021-05-11 21:52:01 +02:00
if (start === undefined)
start = timestamp;
const elapsed = timestamp - start;
if (elapsed > PERIODE) {
universe.tick();
start = timestamp;
}
2021-05-11 21:43:24 +02:00
2021-05-11 17:31:39 +02:00
requestAnimationFrame(renderLoop);
};
2021-05-11 21:43:24 +02:00
const drawGrid = () => {
ctx.beginPath();
ctx.strokeStyle = GRID_COLOR;
for (let i = 0; i <= width; i++) {
ctx.moveTo(i * (CELL_SIZE + 1) + 1, 0);
ctx.lineTo(i * (CELL_SIZE + 1) + 1, (CELL_SIZE + 1) * height + 1);
}
for (let j = 0; j <= height; j++) {
ctx.moveTo(0, j * (CELL_SIZE + 1) + 1);
ctx.lineTo((CELL_SIZE + 1) * width + 1, j * (CELL_SIZE + 1) + 1);
}
ctx.stroke();
}
const getIndex = (row, column) => {
return row * width + column;
}
const drawCells = () => {
const cellsPtr = universe.cells();
const cells = new Uint8Array(memory.buffer, cellsPtr, width * height);
ctx.beginPath();
for (let row = 0; row < height; row++) {
for (let col = 0; col < width; col++) {
const i = getIndex(row, col);
ctx.fillStyle = cells[i] === Cell.Dead
? DEAD_COLOR
: ALIVE_COLOR;
ctx.fillRect(
col * (CELL_SIZE + 1) + 1,
row * (CELL_SIZE + 1) + 1,
CELL_SIZE,
CELL_SIZE
);
}
}
ctx.stroke();
}
2021-05-11 17:31:39 +02:00
requestAnimationFrame(renderLoop);