Files
Reactor-Proto/src/main.js
T
2026-11-20 19:59:44 +01:00

67 lines
2.3 KiB
JavaScript

import { state, newGame, load, hasSave, save } from './state.js';
import { update } from './sim.js';
import { loadBuildings } from './data/buildings.js';
import { render } from './render.js';
import { camera, setMap, resizeView, centerCamera } from './camera.js';
import { initUI, showGame, showMenu, updateHud, setTool } from './ui.js';
import { initInput } from './input.js';
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const AUTOSAVE_EVERY = 5; // secondes
// Le canvas remplit sa zone d'affichage : sa résolution suit sa taille à l'écran (1 pixel = 1 pixel CSS).
function fitCanvas() {
const w = Math.floor(canvas.clientWidth), h = Math.floor(canvas.clientHeight);
if (w < 1 || h < 1) return;
if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
resizeView(w, h);
}
let running = false;
let last = 0;
let untilSave = AUTOSAVE_EVERY;
function frame(now) {
if (!running) return;
const dt = Math.min((now - last) / 1000, 0.1); // plafonné si l'onglet était en pause
last = now;
update(state, dt);
render(ctx, state);
const cursor = state.tool ? 'crosshair' : (camera.dragging ? 'grabbing' : 'grab');
if (canvas.style.cursor !== cursor) canvas.style.cursor = cursor;
updateHud(state);
if ((untilSave -= dt) <= 0) { save(); untilSave = AUTOSAVE_EVERY; }
requestAnimationFrame(frame);
}
function start() {
showGame(); // la zone doit être visible avant de mesurer le canvas
setMap(state.grid[0].length, state.grid.length);
fitCanvas();
centerCamera();
running = true;
untilSave = AUTOSAVE_EVERY;
last = performance.now();
requestAnimationFrame(frame);
}
await loadBuildings();
initInput(canvas, { onCancel: () => setTool(null) });
new ResizeObserver(() => { if (running) fitCanvas(); }).observe(canvas.parentElement);
initUI({
onNew: () => {
if (hasSave() && !confirm('Une sauvegarde existe déjà. La remplacer ?')) return;
newGame();
start();
},
onContinue: () => { if (load()) start(); },
onMenu: () => { running = false; save(); showMenu(); },
});
// L'argent évolue en continu : on sauvegarde aussi quand la page est cachée ou fermée.
window.addEventListener('pagehide', () => { if (running) save(); });
document.addEventListener('visibilitychange', () => { if (document.hidden && running) save(); });