SandGame/state.js

74 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2026-10-22 14:05:51 +00:00
export const canvas = document.getElementById('gameCanvas');
export const ctx = canvas.getContext('2d', { alpha: false });
2026-10-22 14:05:51 +00:00
export const cellSize = 5;
export let cols = 0;
export let rows = 0;
export let grid = [];
export let selectedType = 'sand';
export let brushSize = 4;
export let currentFrame = 1;
export let cursor = { x: -1, y: -1, visible: false };
export function incrementFrame() {
currentFrame++;
if (currentFrame > 2000000000) currentFrame = 1;
}
2026-10-22 14:05:51 +00:00
export function setSelectedType(type) {
selectedType = type;
}
export function setBrushSize(size) {
brushSize = Math.max(1, Math.min(30, Math.round(size)));
}
2026-10-22 14:05:51 +00:00
export function setGrid(newGrid) {
grid = newGrid;
}
export function createEmptyGrid(newCols, newRows) {
const newGrid = new Array(newCols);
for (let x = 0; x < newCols; x++) {
newGrid[x] = new Array(newRows).fill(null);
}
return newGrid;
}
export function clearGrid() {
grid = createEmptyGrid(cols, rows);
}
2026-10-22 14:05:51 +00:00
export function resize() {
const newWidth = window.innerWidth;
const newHeight = window.innerHeight;
canvas.width = newWidth;
canvas.height = newHeight;
const newCols = Math.floor(newWidth / cellSize);
const newRows = Math.floor(newHeight / cellSize);
if (newCols === cols && newRows === rows && grid.length > 0) {
return;
}
const oldGrid = grid;
const oldCols = cols;
const oldRows = rows;
2026-10-22 14:05:51 +00:00
cols = newCols;
rows = newRows;
grid = createEmptyGrid(cols, rows);
2026-10-22 14:05:51 +00:00
// Non-destructive resize: preserve existing particles
if (oldGrid && oldCols > 0 && oldRows > 0) {
const copyCols = Math.min(oldCols, cols);
const copyRows = Math.min(oldRows, rows);
for (let x = 0; x < copyCols; x++) {
for (let y = 0; y < copyRows; y++) {
grid[x][y] = oldGrid[x][y];
}
}
}
2026-10-22 14:05:51 +00:00
}