Initial commit
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "Centrale à charbon",
|
||||
"sprite": "sprite.png",
|
||||
"anim": { "type": "frames", "frames": 2, "fps": 2 },
|
||||
"cost": 800,
|
||||
"requiresOffice": true,
|
||||
"consumes": { "water": 4 },
|
||||
"produces": { "steam": 4 },
|
||||
"maintenance": { "every": 90, "duration": 12, "cost": 150 },
|
||||
"fallback": { "color": "#555555", "label": "C" }
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 315 B |
@@ -0,0 +1 @@
|
||||
["office", "wind", "coal", "pump", "turbine"]
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "Bureaux",
|
||||
"sprite": "sprite.png",
|
||||
"cost": 200,
|
||||
"office": { "capacity": 5 },
|
||||
"maintenance": { "every": 60, "duration": 0, "cost": 20 },
|
||||
"fallback": { "color": "#4a6fa5", "label": "B" }
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 273 B |
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "Pompe",
|
||||
"sprite": "sprite.png",
|
||||
"cost": 150,
|
||||
"anim": { "type": "frames", "frames": 6, "fps": 2 },
|
||||
"requiresOffice": true,
|
||||
"placement": { "adjacentWater": true },
|
||||
"produces": { "water": 6 },
|
||||
"maintenance": { "every": 80, "duration": 0, "cost": 25 },
|
||||
"fallback": { "color": "#2f6fb3", "label": "P" }
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 459 B |
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "Turbine",
|
||||
"sprite": "sprite.png",
|
||||
"cost": 400,
|
||||
"anim": { "type": "frames", "frames": 4, "fps": 2 },
|
||||
"requiresOffice": true,
|
||||
"consumes": { "steam": 4 },
|
||||
"power": { "output": 12 },
|
||||
"maintenance": { "every": 100, "duration": 8, "cost": 60 },
|
||||
"fallback": { "color": "#9aa3ab", "label": "T" }
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 882 B |
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "Éolienne",
|
||||
"sprite": "sprite.png",
|
||||
"anim": { "type": "rotate", "speed": 1.5, "pivot": [16, 12] },
|
||||
"cost": 300,
|
||||
"maintenance": { "every": 60, "duration": 0, "cost": 30 },
|
||||
"requiresOffice": true,
|
||||
"power": { "output": 2, "scalesWithWind": true },
|
||||
"fallback": { "color": "#d8b020", "label": "W" }
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 342 B |
+60
@@ -0,0 +1,60 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Reactor</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<main id="menu" class="screen">
|
||||
<h1>Reactor</h1>
|
||||
<button id="btn-new" type="button">Nouveau</button>
|
||||
<button id="btn-continue" type="button">Continuer</button>
|
||||
</main>
|
||||
|
||||
<main id="game" class="screen hidden">
|
||||
<div class="topbar">
|
||||
<button id="btn-menu" type="button">Menu</button>
|
||||
<div class="hud">
|
||||
<span id="hud-money"></span>
|
||||
<span id="hud-power"></span>
|
||||
<span id="hud-slots"></span>
|
||||
<span id="hud-wind"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stage">
|
||||
<nav class="sidebar" aria-label="Menus de construction">
|
||||
<div class="side-item">
|
||||
<button id="btn-build" class="icon-btn" type="button"
|
||||
aria-label="Construire" title="Construire" aria-expanded="false" aria-controls="build-list">
|
||||
<svg viewBox="0 0 12 12" shape-rendering="crispEdges" aria-hidden="true">
|
||||
<rect x="1" y="1" width="10" height="4"/>
|
||||
<rect x="5" y="5" width="2" height="6"/>
|
||||
</svg>
|
||||
</button>
|
||||
<ul id="build-list" class="dropdown hidden"></ul>
|
||||
</div>
|
||||
<div class="side-item">
|
||||
<button id="btn-layer" class="icon-btn" type="button"
|
||||
aria-label="Sous-terre (U)" title="Sous-terre (U)" aria-expanded="false" aria-controls="pipe-list">
|
||||
<svg viewBox="0 0 12 12" shape-rendering="crispEdges" aria-hidden="true">
|
||||
<rect x="0" y="2" width="12" height="1"/>
|
||||
<rect x="0" y="5" width="5" height="2"/>
|
||||
<rect x="4" y="5" width="2" height="6"/>
|
||||
<rect x="4" y="9" width="8" height="2"/>
|
||||
</svg>
|
||||
</button>
|
||||
<ul id="pipe-list" class="dropdown hidden"></ul>
|
||||
</div>
|
||||
</nav>
|
||||
<div class="viewport">
|
||||
<canvas id="canvas" aria-label="Grille de la centrale"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
<p id="hud-cell" class="info"></p>
|
||||
</main>
|
||||
|
||||
<script type="module" src="src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Serveur de dev : comme `python3 -m http.server`, mais sans cache navigateur,
|
||||
pour que les JSON, JS et PNG modifiés soient toujours rechargés.
|
||||
Usage : python3 serve.py [port] (port 8000 par défaut)"""
|
||||
import sys
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
|
||||
class NoCache(SimpleHTTPRequestHandler):
|
||||
def end_headers(self):
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
super().end_headers()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
|
||||
print(f'http://localhost:{port} (Ctrl+C pour arrêter)')
|
||||
ThreadingHTTPServer(('', port), NoCache).serve_forever()
|
||||
@@ -0,0 +1,83 @@
|
||||
// Caméra : position et zoom de la vue sur la grille. Aucun accès au DOM.
|
||||
// écran = monde * zoom + (ox, oy), avec « monde » en pixels de sprite (une case = TILE).
|
||||
// Les niveaux de zoom donnent une taille de case entière en pixels : pas de coutures entre les cases.
|
||||
export const TILE = 32;
|
||||
export const ZOOMS = [0.5, 0.75, 1, 1.5, 2, 3, 4];
|
||||
const START_ZOOM = 1.5;
|
||||
const MARGIN = 64; // px de vide qu'on peut tirer au-delà des bords de la carte
|
||||
|
||||
export const camera = {
|
||||
ox: 0, oy: 0, // position à l'écran de l'angle haut-gauche de la carte (entiers)
|
||||
zoom: START_ZOOM,
|
||||
w: 0, h: 0, // taille de la vue (px)
|
||||
cols: 1, rows: 1, // taille de la carte (cases)
|
||||
dragging: false, // vue en cours de déplacement (curseur « main fermée »)
|
||||
};
|
||||
|
||||
const tilePx = () => TILE * camera.zoom;
|
||||
|
||||
// Carte plus petite que la vue : centrée. Sinon : on peut tirer de MARGIN px au-delà du bord.
|
||||
function clampAxis(o, view, size) {
|
||||
if (size + 2 * MARGIN <= view) return (view - size) / 2;
|
||||
return Math.min(MARGIN, Math.max(view - size - MARGIN, o));
|
||||
}
|
||||
|
||||
function clampCamera() {
|
||||
camera.ox = Math.round(clampAxis(camera.ox, camera.w, camera.cols * tilePx()));
|
||||
camera.oy = Math.round(clampAxis(camera.oy, camera.h, camera.rows * tilePx()));
|
||||
}
|
||||
|
||||
export function setMap(cols, rows) {
|
||||
camera.cols = cols;
|
||||
camera.rows = rows;
|
||||
}
|
||||
|
||||
export function resizeView(w, h) {
|
||||
camera.w = w;
|
||||
camera.h = h;
|
||||
clampCamera();
|
||||
}
|
||||
|
||||
// Carte centrée dans la vue, zoom de départ.
|
||||
export function centerCamera() {
|
||||
camera.zoom = START_ZOOM;
|
||||
camera.ox = (camera.w - camera.cols * tilePx()) / 2;
|
||||
camera.oy = (camera.h - camera.rows * tilePx()) / 2;
|
||||
clampCamera();
|
||||
}
|
||||
|
||||
export function panBy(dx, dy) {
|
||||
camera.ox += dx;
|
||||
camera.oy += dy;
|
||||
clampCamera();
|
||||
}
|
||||
|
||||
// Zoom d'un cran (dir = +1 / -1) en gardant fixe le point (sx, sy) de l'écran.
|
||||
export function zoomStep(dir, sx = camera.w / 2, sy = camera.h / 2) {
|
||||
const i = ZOOMS.indexOf(camera.zoom);
|
||||
const next = ZOOMS[Math.min(ZOOMS.length - 1, Math.max(0, i + dir))];
|
||||
if (next === camera.zoom) return;
|
||||
const wx = (sx - camera.ox) / camera.zoom, wy = (sy - camera.oy) / camera.zoom; // point du monde sous le curseur
|
||||
camera.zoom = next;
|
||||
camera.ox = sx - wx * next;
|
||||
camera.oy = sy - wy * next;
|
||||
clampCamera();
|
||||
}
|
||||
|
||||
// Case sous un point de l'écran, ou null hors de la carte.
|
||||
export function screenToCell(sx, sy) {
|
||||
const x = Math.floor((sx - camera.ox) / tilePx());
|
||||
const y = Math.floor((sy - camera.oy) / tilePx());
|
||||
return x >= 0 && x < camera.cols && y >= 0 && y < camera.rows ? { x, y } : null;
|
||||
}
|
||||
|
||||
// Cases visibles (bornes incluses) : on ne dessine que celles-là.
|
||||
export function visibleRange() {
|
||||
const s = tilePx();
|
||||
return {
|
||||
x0: Math.max(0, Math.floor(-camera.ox / s)),
|
||||
x1: Math.min(camera.cols - 1, Math.floor((camera.w - camera.ox) / s)),
|
||||
y0: Math.max(0, Math.floor(-camera.oy / s)),
|
||||
y1: Math.min(camera.rows - 1, Math.floor((camera.h - camera.oy) / s)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// Registre des bâtiments, chargé depuis assets/buildings/<id>/building.json + sprite.
|
||||
// Le nom du dossier est l'id du bâtiment (c'est lui qui est sauvegardé dans la grille).
|
||||
// Les clés inconnues du JSON sont conservées telles quelles (électricité, coût…),
|
||||
// donc de nouveaux champs n'exigent aucun changement ici.
|
||||
//
|
||||
// building.json :
|
||||
// name : nom affiché dans la liste du marteau
|
||||
// sprite : nom du PNG dans le dossier (défaut : sprite.png)
|
||||
// anim : (optionnel) comment il s'anime
|
||||
// rotate : PNG 32x64, rotor en haut (tourne autour de pivot), base + moyeu en bas
|
||||
// { "type": "rotate", "speed": rad/s, "pivot": [x, y] }
|
||||
// frames : PNG 32 x (32 * frames), images empilées, jouées en boucle
|
||||
// { "type": "frames", "frames": N, "fps": images/s }
|
||||
// (sans anim : PNG 32x32 statique)
|
||||
// fallback : { "color", "label" } affichés si le PNG est introuvable
|
||||
export const BUILDINGS = {};
|
||||
|
||||
const DIR = 'assets/buildings/';
|
||||
const TILE = 32; // doit rester égal à TILE de render.js
|
||||
|
||||
// Dimensions attendues du PNG selon le type d'animation.
|
||||
const SIZES = {
|
||||
none: () => [TILE, TILE],
|
||||
rotate: () => [TILE, TILE * 2],
|
||||
frames: a => [TILE, TILE * a.frames],
|
||||
};
|
||||
|
||||
function loadImage(url) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.onload = () => resolve(img);
|
||||
img.onerror = () => reject(new Error(`image introuvable : ${url}`));
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
// Valeurs par défaut + suppression des animations invalides (le bâtiment reste affichable).
|
||||
function normalizeAnim(id, def) {
|
||||
const a = def.anim;
|
||||
if (!a) return;
|
||||
if (a.type === 'rotate') {
|
||||
a.speed ??= 1;
|
||||
a.pivot ??= [16, 16];
|
||||
} else if (a.type === 'frames') {
|
||||
a.fps ??= 4;
|
||||
if (!Number.isInteger(a.frames) || a.frames < 1) {
|
||||
console.warn(`[${id}] anim "frames" : "frames" doit être un entier >= 1, animation ignorée`);
|
||||
delete def.anim;
|
||||
}
|
||||
} else {
|
||||
console.warn(`[${id}] type d'animation inconnu « ${a.type} », animation ignorée`);
|
||||
delete def.anim;
|
||||
}
|
||||
}
|
||||
|
||||
function checkSize(id, def) {
|
||||
if (!def.img) return;
|
||||
const type = def.anim?.type ?? 'none';
|
||||
const [w, h] = SIZES[type](def.anim);
|
||||
if (def.img.width !== w || def.img.height !== h) {
|
||||
console.warn(`[${id}] sprite ${def.img.width}x${def.img.height}, attendu ${w}x${h} (${type})`);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadOne(id) {
|
||||
try {
|
||||
const res = await fetch(`${DIR}${id}/building.json`);
|
||||
if (!res.ok) throw new Error(`building.json : HTTP ${res.status}`);
|
||||
const def = await res.json();
|
||||
def.id = id;
|
||||
def.name ??= id;
|
||||
normalizeAnim(id, def);
|
||||
def.img = await loadImage(`${DIR}${id}/${def.sprite ?? 'sprite.png'}`)
|
||||
.catch(e => { console.warn(`[${id}] ${e.message}`); return null; });
|
||||
checkSize(id, def);
|
||||
return def;
|
||||
} catch (e) {
|
||||
console.warn(`Bâtiment « ${id} » ignoré : ${e.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadBuildings() {
|
||||
let ids = [];
|
||||
try {
|
||||
ids = await (await fetch(`${DIR}index.json`)).json();
|
||||
} catch (e) {
|
||||
console.error(`Impossible de lire ${DIR}index.json :`, e);
|
||||
}
|
||||
const defs = await Promise.all(ids.map(loadOne)); // l'ordre d'index.json est conservé
|
||||
for (const def of defs) if (def) BUILDINGS[def.id] = def;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
// Lieux et modificateurs (à venir)
|
||||
@@ -0,0 +1,27 @@
|
||||
// Ressources transportées sous terre par des tuyaux. Tout se règle ici.
|
||||
// L'ordre des clés est l'ordre de calcul : l'eau d'abord (elle devient de la vapeur), puis la vapeur.
|
||||
//
|
||||
// Dans building.json, un bâtiment les utilise ainsi (débits nominaux en unités/s) :
|
||||
// "produces": { "water": 6 } ce qu'il envoie dans les tuyaux (pompe : eau, centrale : vapeur)
|
||||
// "consumes": { "steam": 4 } ce qu'il puise dans les tuyaux (centrale : eau, turbine : vapeur)
|
||||
// "placement": { "adjacentWater": true } à construire au bord de l'eau (pompe)
|
||||
// Un bâtiment est relié aux tuyaux du bon type posés sur les cases voisines (haut, bas, gauche, droite).
|
||||
// Un bâtiment qui manque de ressource tourne au prorata (rendement réduit) ; sans rien, il s'arrête.
|
||||
export const RESOURCES = {
|
||||
water: {
|
||||
label: 'eau',
|
||||
lack: "manque d'eau",
|
||||
pipe: "Tuyau d'eau",
|
||||
cost: 10, // € par case de tuyau
|
||||
live: '#3d8bd9', dry: '#27496b', // couleur avec / sans débit
|
||||
},
|
||||
steam: {
|
||||
label: 'vapeur',
|
||||
lack: 'manque de vapeur',
|
||||
pipe: 'Conduite de vapeur',
|
||||
cost: 15,
|
||||
live: '#dfe4e8', dry: '#6a7075',
|
||||
},
|
||||
};
|
||||
|
||||
export const RESOURCE_IDS = Object.keys(RESOURCES);
|
||||
@@ -0,0 +1 @@
|
||||
// Centrales : règles + forme de grille (à venir)
|
||||
@@ -0,0 +1,64 @@
|
||||
// Constantes du monde : relief et vent. Tout se règle ici.
|
||||
|
||||
export const MAX_HEIGHT = 4; // altitudes 0 .. MAX_HEIGHT
|
||||
|
||||
// Collines : une pour `cellsPerHill` cases (au moins `minHills`), de rayon (en cases) entre min et max.
|
||||
// Plus la carte est grande, plus il y en a ; plus le rayon est grand, plus les reliefs sont larges.
|
||||
export const TERRAIN = {
|
||||
cellsPerHill: 90,
|
||||
minHills: 3,
|
||||
radius: { min: 1.3, max: 3.2 },
|
||||
};
|
||||
|
||||
// Direction de DÉPLACEMENT du vent (dx, dy) ; y augmente vers le bas.
|
||||
// Un « vent d'ouest » vient de l'ouest et va vers l'est.
|
||||
export const WIND_DIRS = [
|
||||
{ id: 'N', label: 'du nord', arrow: '↓', dx: 0, dy: 1 },
|
||||
{ id: 'E', label: "d'est", arrow: '←', dx: -1, dy: 0 },
|
||||
{ id: 'S', label: 'du sud', arrow: '↑', dx: 0, dy: -1 },
|
||||
{ id: 'W', label: "d'ouest", arrow: '→', dx: 1, dy: 0 },
|
||||
];
|
||||
|
||||
// Rendement d'une éolienne selon le relief :
|
||||
// pente face au vent (le vent monte vers elle) : bonus de perRise par niveau
|
||||
// pente sous le vent (le vent descend vers elle) : malus de perRise par niveau
|
||||
// sommet : le résultat est multiplié par summit
|
||||
// (aucune case voisine plus haute, au moins une plus basse, altitude >= summitMinHeight)
|
||||
export const WIND_RULES = {
|
||||
perRise: 0.3,
|
||||
summit: 0.5,
|
||||
summitMinHeight: 3,
|
||||
min: 0.2,
|
||||
max: 2,
|
||||
};
|
||||
|
||||
// Eau : lacs et mares, uniquement dans les basses terres (altitude 0), formes organiques (bruit lissé).
|
||||
// coverage : part de la carte couverte, tirée au hasard entre min et max
|
||||
// noiseScale : taille des taches (en cases) : petit = mares, grand = lacs
|
||||
// maxShare : part maximale des cases d'altitude 0 qui peuvent devenir de l'eau
|
||||
export const WATER = {
|
||||
coverage: { min: 0.07, max: 0.13 },
|
||||
noiseScale: 6,
|
||||
maxShare: 0.6,
|
||||
};
|
||||
|
||||
// Le vent change de direction toutes les min..max secondes (max = 0 : jamais).
|
||||
// Pour tester : { min: 8, max: 15 }.
|
||||
export const WIND_CHANGE = { min: 90, max: 180 };
|
||||
|
||||
// Couleurs des cases selon l'altitude : fond et petits points.
|
||||
export const TERRAIN_COLORS = [
|
||||
{ bg: '#262829', dot: '#3a3d3f' },
|
||||
{ bg: '#2e3133', dot: '#444a4d' },
|
||||
{ bg: '#373b3e', dot: '#50565a' },
|
||||
{ bg: '#42474b', dot: '#5d646a' },
|
||||
{ bg: '#4e545a', dot: '#6a727a' },
|
||||
];
|
||||
|
||||
// Couleurs de l'eau : fond, berge (liseré côté terre) et reflets animés (r, g, b).
|
||||
export const WATER_COLORS = { deep: '#1d3a55', shore: '#3a6a8c', ripple: '150, 200, 240' };
|
||||
|
||||
// Économie.
|
||||
export const START_MONEY = 600; // argent au début d'une nouvelle partie (€)
|
||||
export const ELECTRICITY_PRICE = 1; // € gagnés par MW produit et par seconde
|
||||
export const REFUND = 0.5; // part du coût de construction rendue à la démolition
|
||||
@@ -0,0 +1 @@
|
||||
// Export / import de designs (à venir)
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import { state, applyTool, pipeOfTool } from './state.js';
|
||||
import { camera, screenToCell, panBy, zoomStep } from './camera.js';
|
||||
|
||||
// Cases d'une ligne entre deux cases (Bresenham) : un glissé rapide ne saute aucune case.
|
||||
function* line(a, b) {
|
||||
let { x, y } = a;
|
||||
const dx = Math.abs(b.x - x), dy = -Math.abs(b.y - y);
|
||||
const sx = x < b.x ? 1 : -1, sy = y < b.y ? 1 : -1;
|
||||
let err = dx + dy;
|
||||
for (;;) {
|
||||
yield { x, y };
|
||||
if (x === b.x && y === b.y) return;
|
||||
const e2 = 2 * err;
|
||||
if (e2 >= dy) { err += dy; x += sx; }
|
||||
if (e2 <= dx) { err += dx; y += sy; }
|
||||
}
|
||||
}
|
||||
|
||||
// Seuls les tuyaux (et leur retrait sous terre) se posent en glissant : jamais les bâtiments,
|
||||
// pour qu'un geste un peu large ne construise ou ne démolisse pas dix bâtiments d'un coup.
|
||||
function draggable() {
|
||||
return Boolean(pipeOfTool(state.tool)) || (state.tool === 'demolish' && state.mode === 'underground');
|
||||
}
|
||||
|
||||
// Commandes :
|
||||
// outil sélectionné : clic = construire / démolir (glisser = tuyaux)
|
||||
// aucun outil : clic gauche maintenu = déplacer la vue
|
||||
// clic milieu : déplace la vue même avec un outil
|
||||
// molette : zoom (autour du curseur) clic droit : désélectionne l'outil
|
||||
// tactile : un doigt comme la souris, deux doigts = déplacer + pincer pour zoomer
|
||||
export function initInput(canvas, { onCancel } = {}) {
|
||||
const pointers = new Map(); // pointerId -> position à l'écran, pour les pointeurs enfoncés
|
||||
let mode = null; // null | 'pan' | 'build'
|
||||
let last = null; // dernière case traitée pendant un glissé de pose
|
||||
let pinch = null; // { mx, my, dist } : état du geste à deux doigts
|
||||
let wheelAcc = 0;
|
||||
|
||||
// Position du pointeur dans le canvas (en pixels du canvas).
|
||||
function screen(e) {
|
||||
const r = canvas.getBoundingClientRect();
|
||||
return { x: (e.clientX - r.left) * canvas.width / r.width, y: (e.clientY - r.top) * canvas.height / r.height };
|
||||
}
|
||||
const cellAt = e => { const p = screen(e); return screenToCell(p.x, p.y); };
|
||||
|
||||
function begin(m) {
|
||||
mode = m;
|
||||
camera.dragging = m === 'pan';
|
||||
}
|
||||
|
||||
function pinchState() {
|
||||
const [a, b] = [...pointers.values()];
|
||||
return { mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2, dist: Math.hypot(a.x - b.x, a.y - b.y) || 1 };
|
||||
}
|
||||
|
||||
canvas.addEventListener('pointerdown', e => {
|
||||
pointers.set(e.pointerId, screen(e));
|
||||
canvas.setPointerCapture?.(e.pointerId);
|
||||
|
||||
if (pointers.size === 2) { begin(null); last = null; pinch = pinchState(); return; }
|
||||
if (pointers.size > 2) return;
|
||||
|
||||
if (e.button === 1) { begin('pan'); return; }
|
||||
if (e.button !== 0) return;
|
||||
if (!state.tool) { begin('pan'); return; }
|
||||
|
||||
begin('build');
|
||||
state.hover = cellAt(e);
|
||||
last = state.hover;
|
||||
if (state.hover) applyTool(state.hover.x, state.hover.y);
|
||||
});
|
||||
|
||||
canvas.addEventListener('pointermove', e => {
|
||||
const prev = pointers.get(e.pointerId);
|
||||
const p = screen(e);
|
||||
if (prev) pointers.set(e.pointerId, p);
|
||||
|
||||
if (pinch && pointers.size === 2) {
|
||||
const now = pinchState();
|
||||
panBy(now.mx - pinch.mx, now.my - pinch.my);
|
||||
const ratio = now.dist / pinch.dist;
|
||||
if (ratio > 1.3 || ratio < 0.77) { zoomStep(ratio > 1 ? 1 : -1, now.mx, now.my); pinch.dist = now.dist; }
|
||||
pinch.mx = now.mx;
|
||||
pinch.my = now.my;
|
||||
} else if (mode === 'pan' && prev) {
|
||||
panBy(p.x - prev.x, p.y - prev.y);
|
||||
}
|
||||
|
||||
state.hover = screenToCell(p.x, p.y);
|
||||
|
||||
if (mode === 'build' && state.hover && draggable()) {
|
||||
const from = last ?? state.hover;
|
||||
if (from.x === state.hover.x && from.y === state.hover.y) return;
|
||||
for (const c of line(from, state.hover)) {
|
||||
if (c.x === from.x && c.y === from.y) continue; // déjà traitée
|
||||
applyTool(c.x, c.y);
|
||||
}
|
||||
last = state.hover;
|
||||
}
|
||||
});
|
||||
|
||||
function release(e) {
|
||||
pointers.delete(e.pointerId);
|
||||
if (pointers.size < 2) pinch = null;
|
||||
if (pointers.size === 0) { begin(null); last = null; }
|
||||
}
|
||||
canvas.addEventListener('pointerup', release);
|
||||
canvas.addEventListener('pointercancel', release);
|
||||
canvas.addEventListener('pointerleave', () => { if (pointers.size === 0) state.hover = null; });
|
||||
|
||||
// Molette : un cran de zoom par « clic » de molette (cumul pour les pavés tactiles).
|
||||
canvas.addEventListener('wheel', e => {
|
||||
e.preventDefault();
|
||||
wheelAcc += e.deltaY * (e.deltaMode === 1 ? 16 : 1);
|
||||
if (Math.abs(wheelAcc) < 40) return;
|
||||
const p = screen(e);
|
||||
zoomStep(wheelAcc < 0 ? 1 : -1, p.x, p.y);
|
||||
wheelAcc = 0;
|
||||
state.hover = screenToCell(p.x, p.y);
|
||||
}, { passive: false });
|
||||
|
||||
canvas.addEventListener('mousedown', e => { if (e.button === 1) e.preventDefault(); }); // pas de défilement automatique
|
||||
canvas.addEventListener('contextmenu', e => {
|
||||
e.preventDefault();
|
||||
if (state.tool) onCancel?.();
|
||||
});
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
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(); });
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
import { BUILDINGS } from './data/buildings.js';
|
||||
import { TERRAIN_COLORS, WATER_COLORS } from './data/world.js';
|
||||
import { RESOURCES } from './data/pipes.js';
|
||||
import { windAt } from './terrain.js';
|
||||
import { placeCheck, pipeOfTool, nearWater } from './state.js';
|
||||
import { TILE, camera, visibleRange } from './camera.js';
|
||||
|
||||
export { TILE };
|
||||
|
||||
// Le relief ne change pas pendant une partie : on le dessine une fois dans une image hors écran
|
||||
// (recréée quand la carte change), puis chaque image n'en fait qu'un seul drawImage.
|
||||
let terrainCache = null; // { terrain, water, canvas }
|
||||
|
||||
function makeCanvas(w, h) {
|
||||
if (typeof OffscreenCanvas !== 'undefined') return new OffscreenCanvas(w, h);
|
||||
const c = document.createElement('canvas');
|
||||
c.width = w;
|
||||
c.height = h;
|
||||
return c;
|
||||
}
|
||||
|
||||
function terrainLayer(state) {
|
||||
if (terrainCache?.terrain === state.terrain && terrainCache.water === state.water) return terrainCache.canvas;
|
||||
const rows = state.terrain.length, cols = state.terrain[0].length;
|
||||
const canvas = makeCanvas(cols * TILE, rows * TILE);
|
||||
const c = canvas.getContext('2d');
|
||||
for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) drawTerrain(c, state.terrain, x, y);
|
||||
terrainCache = { terrain: state.terrain, water: state.water, canvas };
|
||||
return canvas;
|
||||
}
|
||||
|
||||
// Case de terrain : couleur selon l'altitude, points, liserés de relief.
|
||||
function drawTerrain(ctx, terrain, x, y) {
|
||||
const px = x * TILE, py = y * TILE;
|
||||
const h = terrain[y][x];
|
||||
const { bg, dot } = TERRAIN_COLORS[Math.min(h, TERRAIN_COLORS.length - 1)];
|
||||
|
||||
ctx.fillStyle = bg;
|
||||
ctx.fillRect(px, py, TILE, TILE);
|
||||
|
||||
// quelques points, positions fixes dérivées des coordonnées (pas de scintillement)
|
||||
const k = (Math.imul(x + 1, 73856093) ^ Math.imul(y + 1, 19349663)) >>> 0;
|
||||
ctx.fillStyle = dot;
|
||||
ctx.fillRect(px + 4 + (k % 24), py + 4 + ((k >>> 5) % 24), 2, 2);
|
||||
ctx.fillRect(px + 4 + ((k >>> 10) % 24), py + 4 + ((k >>> 15) % 24), 2, 2);
|
||||
|
||||
// relief : liseré clair au nord/ouest, sombre au sud/est, là où la case voisine est plus basse
|
||||
const lower = (dx, dy) => (terrain[y + dy]?.[x + dx] ?? h) < h;
|
||||
ctx.fillStyle = 'rgba(255, 255, 255, 0.12)';
|
||||
if (lower(0, -1)) ctx.fillRect(px, py, TILE, 2);
|
||||
if (lower(-1, 0)) ctx.fillRect(px, py, 2, TILE);
|
||||
ctx.fillStyle = 'rgba(0, 0, 0, 0.35)';
|
||||
if (lower(0, 1)) ctx.fillRect(px, py + TILE - 2, TILE, 2);
|
||||
if (lower(1, 0)) ctx.fillRect(px + TILE - 2, py, 2, TILE);
|
||||
|
||||
ctx.strokeStyle = '#1c1c1c';
|
||||
ctx.strokeRect(px + 0.5, py + 0.5, TILE - 1, TILE - 1);
|
||||
}
|
||||
|
||||
// Eau : forme arrondie aux angles « convexes » (là où deux côtés touchent la terre), berge claire côté terre,
|
||||
// reflets qui scintillent doucement. Les bords de la carte comptent comme de l'eau (le lac continue au-delà).
|
||||
const WATER_R = 10; // rayon des angles arrondis
|
||||
const BANK = 2; // largeur de la berge (px)
|
||||
|
||||
function drawWater(ctx, water, x, y, t) {
|
||||
const isWater = (dx, dy) => water[y + dy]?.[x + dx] ?? true;
|
||||
const l = !isWater(-1, 0), r = !isWater(1, 0), u = !isWater(0, -1), d = !isWater(0, 1);
|
||||
const px = x * TILE, py = y * TILE;
|
||||
|
||||
const shape = inset => {
|
||||
const x0 = px + (l ? inset : 0), x1 = px + TILE - (r ? inset : 0);
|
||||
const y0 = py + (u ? inset : 0), y1 = py + TILE - (d ? inset : 0);
|
||||
const rad = Math.max(0, WATER_R - inset);
|
||||
const tl = u && l ? rad : 0, tr = u && r ? rad : 0, br = d && r ? rad : 0, bl = d && l ? rad : 0;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x0 + tl, y0);
|
||||
ctx.lineTo(x1 - tr, y0); if (tr) ctx.arcTo(x1, y0, x1, y0 + tr, tr);
|
||||
ctx.lineTo(x1, y1 - br); if (br) ctx.arcTo(x1, y1, x1 - br, y1, br);
|
||||
ctx.lineTo(x0 + bl, y1); if (bl) ctx.arcTo(x0, y1, x0, y1 - bl, bl);
|
||||
ctx.lineTo(x0, y0 + tl); if (tl) ctx.arcTo(x0, y0, x0 + tl, y0, tl);
|
||||
ctx.closePath();
|
||||
};
|
||||
|
||||
ctx.fillStyle = WATER_COLORS.shore;
|
||||
shape(0); ctx.fill();
|
||||
ctx.fillStyle = WATER_COLORS.deep;
|
||||
shape(BANK); ctx.fill();
|
||||
|
||||
// reflets : positions fixes par case, intensité qui pulse (légèrement déphasée d'une case à l'autre)
|
||||
const k = (Math.imul(x + 7, 83492791) ^ Math.imul(y + 3, 2654435761)) >>> 0;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const a = 0.08 + 0.14 * (0.5 + 0.5 * Math.sin(t * 1.6 + (k >>> (i * 7)) % 628 / 100));
|
||||
ctx.fillStyle = `rgba(${WATER_COLORS.ripple}, ${a})`;
|
||||
ctx.fillRect(px + 8 + ((k >>> (i * 9)) % 11), py + 8 + ((k >>> (i * 9 + 4)) % 15), 6, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Affiché quand le PNG du bâtiment est introuvable.
|
||||
function drawFallback(ctx, def, px, py) {
|
||||
const { color = '#888888', label = def.name[0] } = def.fallback ?? {};
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(px, py, TILE, TILE);
|
||||
ctx.fillStyle = '#000';
|
||||
ctx.font = 'bold 16px monospace';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(label, px + TILE / 2, py + TILE / 2 + 6);
|
||||
}
|
||||
|
||||
function drawStatic(ctx, img, px, py) {
|
||||
ctx.drawImage(img, 0, 0, TILE, TILE, px, py, TILE, TILE);
|
||||
}
|
||||
|
||||
// rotate : PNG 32x64, rotor en haut (pivot au moyeu), base + moyeu en bas.
|
||||
function drawRotor(ctx, img, px, py, cell, anim) {
|
||||
const [cx, cy] = anim.pivot;
|
||||
ctx.drawImage(img, 0, TILE, TILE, TILE, px, py, TILE, TILE); // base
|
||||
ctx.save();
|
||||
ctx.translate(px + cx, py + cy);
|
||||
ctx.rotate(cell.angle || 0);
|
||||
ctx.drawImage(img, 0, 0, TILE, TILE, -cx, -cy, TILE, TILE); // rotor
|
||||
ctx.restore();
|
||||
ctx.drawImage(img, cx - 1, TILE + cy - 1, 2, 2, px + cx - 1, py + cy - 1, 2, 2); // moyeu par-dessus
|
||||
}
|
||||
|
||||
// frames : images 32x32 empilées verticalement, une par valeur entière de cell.phase.
|
||||
function drawFrames(ctx, img, px, py, cell, anim) {
|
||||
const f = Math.floor(cell.phase || 0) % anim.frames;
|
||||
ctx.drawImage(img, 0, f * TILE, TILE, TILE, px, py, TILE, TILE);
|
||||
}
|
||||
|
||||
const DRAWERS = { rotate: drawRotor, frames: drawFrames };
|
||||
|
||||
// cell = case de la grille ({ type, angle, phase }), ou {} pour un aperçu / une icône.
|
||||
function drawBuilding(ctx, id, px, py, cell) {
|
||||
const def = BUILDINGS[id];
|
||||
if (!def) return; // type inconnu (ancienne sauvegarde)
|
||||
if (!def.img) return drawFallback(ctx, def, px, py);
|
||||
const draw = DRAWERS[def.anim?.type] || drawStatic;
|
||||
draw(ctx, def.img, px, py, cell, def.anim);
|
||||
}
|
||||
|
||||
// Icône 32x32 d'un bâtiment (pour la liste du marteau), sans transformation.
|
||||
export function drawBuildingIcon(ctx, id) {
|
||||
ctx.clearRect(0, 0, TILE, TILE);
|
||||
ctx.imageSmoothingEnabled = false;
|
||||
drawBuilding(ctx, id, 0, 0, {});
|
||||
}
|
||||
|
||||
// Pastille d'état (en haut à droite) + barre de temps avant l'entretien (en bas).
|
||||
function drawStatus(ctx, cell, def, px, py) {
|
||||
const bx = px + TILE - 10, by = py + 2;
|
||||
if (cell.status === 'unmanaged') { // « ! » rouge : pas assez de bureaux
|
||||
ctx.fillStyle = '#c03030';
|
||||
ctx.fillRect(bx, by, 8, 8);
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fillRect(bx + 3, by + 1, 2, 4);
|
||||
ctx.fillRect(bx + 3, by + 6, 2, 1);
|
||||
} else if (cell.status === 'running' && cell.starved) { // « ! » à la couleur de la ressource qui manque
|
||||
ctx.fillStyle = RESOURCES[cell.starved].live;
|
||||
ctx.fillRect(bx, by, 8, 8);
|
||||
ctx.fillStyle = '#10151a';
|
||||
ctx.fillRect(bx + 3, by + 1, 2, 4);
|
||||
ctx.fillRect(bx + 3, by + 6, 2, 1);
|
||||
} else if (cell.status === 'maintenance') { // clé orange : en entretien
|
||||
ctx.fillStyle = '#d98a1f';
|
||||
ctx.fillRect(bx, by, 8, 8);
|
||||
ctx.fillStyle = '#fff';
|
||||
for (let i = 0; i < 5; i++) ctx.fillRect(bx + 1 + i, by + 6 - i, 1, 1);
|
||||
ctx.fillRect(bx + 5, by + 1, 2, 2);
|
||||
}
|
||||
|
||||
const m = def.maintenance;
|
||||
if (!m?.every || cell.status === 'unmanaged') return;
|
||||
const maint = cell.status === 'maintenance';
|
||||
const frac = Math.max(0, Math.min(1, maint ? cell.maint / m.duration : (cell.mt ?? m.every) / m.every));
|
||||
const w = TILE - 4;
|
||||
ctx.fillStyle = 'rgba(0, 0, 0, 0.55)';
|
||||
ctx.fillRect(px + 2, py + TILE - 2, w, 2);
|
||||
ctx.fillStyle = maint || frac < 0.25 ? '#d98a1f' : '#4caf50';
|
||||
ctx.fillRect(px + 2, py + TILE - 2, w * frac, 2);
|
||||
}
|
||||
|
||||
// Outil dépendant du vent : cases vertes = bon rendement, rouges = mauvais.
|
||||
function drawWindOverlay(ctx, state) {
|
||||
if (!BUILDINGS[state.tool]?.power?.scalesWithWind) return;
|
||||
const { x0, x1, y0, y1 } = visibleRange();
|
||||
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {
|
||||
if (state.grid[y][x] || state.water[y][x]) continue;
|
||||
const f = windAt(state.terrain, x, y, state.wind.dir).factor;
|
||||
if (f >= 1.15) ctx.fillStyle = 'rgba(80, 200, 90, 0.30)';
|
||||
else if (f <= 0.85) ctx.fillStyle = 'rgba(220, 60, 50, 0.30)';
|
||||
else continue;
|
||||
ctx.fillRect(x * TILE, y * TILE, TILE, TILE);
|
||||
}
|
||||
}
|
||||
|
||||
// Outil à construire au bord de l'eau (pompe) : cases possibles en bleu.
|
||||
function drawPlacementOverlay(ctx, state) {
|
||||
if (!BUILDINGS[state.tool]?.placement?.adjacentWater) return;
|
||||
const { x0, x1, y0, y1 } = visibleRange();
|
||||
ctx.fillStyle = 'rgba(61, 139, 217, 0.30)';
|
||||
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {
|
||||
if (!state.grid[y][x] && !state.water[y][x] && nearWater(x, y)) ctx.fillRect(x * TILE, y * TILE, TILE, TILE);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Tuyaux (vue sous-terre) ----------
|
||||
|
||||
const NEIGHBORS = [[0, -1], [0, 1], [-1, 0], [1, 0]]; // haut, bas, gauche, droite
|
||||
const PW = 6; // épaisseur d'un tuyau (px)
|
||||
const PO = (TILE - PW) / 2;
|
||||
|
||||
// Rectangles d'un tuyau de type `res` en (x, y) : le centre + un bras vers chaque voisin relié
|
||||
// (autre tuyau du même type, ou bâtiment qui produit / consomme cette ressource).
|
||||
function pipeRects(state, x, y, res) {
|
||||
const [u, d, l, r] = NEIGHBORS.map(([dx, dy]) => {
|
||||
const nx = x + dx, ny = y + dy;
|
||||
if (state.pipes[ny]?.[nx] === res) return true;
|
||||
const def = BUILDINGS[state.grid[ny]?.[nx]?.type];
|
||||
return def?.produces?.[res] != null || def?.consumes?.[res] != null;
|
||||
});
|
||||
const rects = [[PO, PO, PW, PW]];
|
||||
if (u) rects.push([PO, 0, PW, PO]);
|
||||
if (d) rects.push([PO, PO + PW, PW, PO]);
|
||||
if (l) rects.push([0, PO, PO, PW]);
|
||||
if (r) rects.push([PO + PW, PO, PO, PW]);
|
||||
return rects;
|
||||
}
|
||||
|
||||
function strokeRects(ctx, px, py, rects) { // contour sombre, sans déborder de la case
|
||||
ctx.fillStyle = '#0b0f14';
|
||||
for (const [rx, ry, rw, rh] of rects) {
|
||||
const x0 = Math.max(0, rx - 1), y0 = Math.max(0, ry - 1);
|
||||
const x1 = Math.min(TILE, rx + rw + 1), y1 = Math.min(TILE, ry + rh + 1);
|
||||
ctx.fillRect(px + x0, py + y0, x1 - x0, y1 - y0);
|
||||
}
|
||||
}
|
||||
|
||||
function fillRects(ctx, px, py, rects, color) {
|
||||
ctx.fillStyle = color;
|
||||
for (const [rx, ry, rw, rh] of rects) ctx.fillRect(px + rx, py + ry, rw, rh);
|
||||
}
|
||||
|
||||
// Deux passes (contours puis remplissage) pour que les jonctions entre cases restent propres.
|
||||
function drawPipes(ctx, state, t) {
|
||||
const tiles = [];
|
||||
const { x0, x1, y0, y1 } = visibleRange();
|
||||
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {
|
||||
const res = state.pipes[y][x];
|
||||
if (res) tiles.push({ x, y, res, rects: pipeRects(state, x, y, res) });
|
||||
}
|
||||
for (const { x, y, rects } of tiles) strokeRects(ctx, x * TILE, y * TILE, rects);
|
||||
for (const { x, y, res, rects } of tiles) {
|
||||
const live = (state.pipeNet[y]?.[x]?.supply ?? 0) > 0;
|
||||
fillRects(ctx, x * TILE, y * TILE, rects, live ? RESOURCES[res].live : RESOURCES[res].dry);
|
||||
if (live && Math.floor(t * 4 + x + y) % 3 === 0) { // reflet qui court le long du réseau
|
||||
ctx.fillStyle = 'rgba(255, 255, 255, 0.45)';
|
||||
ctx.fillRect(x * TILE + PO + 2, y * TILE + PO + 2, 2, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Icône 32x32 d'un type de tuyau (liste des outils).
|
||||
export function drawPipeIcon(ctx, res) {
|
||||
ctx.clearRect(0, 0, TILE, TILE);
|
||||
const rects = [[0, PO, TILE, PW], [PO, PO, PW, TILE - PO]]; // un « T » : horizontal + branche vers le bas
|
||||
strokeRects(ctx, 0, 0, rects);
|
||||
fillRects(ctx, 0, 0, rects, RESOURCES[res].live);
|
||||
}
|
||||
|
||||
// Case survolée : aperçu translucide + contour (orange = valide, rouge = impossible).
|
||||
function drawHover(ctx, state) {
|
||||
const { hover, tool } = state;
|
||||
if (!hover || !tool) return;
|
||||
const px = hover.x * TILE, py = hover.y * TILE;
|
||||
const ok = !placeCheck(tool, hover.x, hover.y);
|
||||
const demolish = tool === 'demolish';
|
||||
const res = pipeOfTool(tool);
|
||||
|
||||
if (!demolish && ok) {
|
||||
ctx.globalAlpha = 0.5;
|
||||
if (res) {
|
||||
const rects = pipeRects(state, hover.x, hover.y, res);
|
||||
strokeRects(ctx, px, py, rects);
|
||||
fillRects(ctx, px, py, rects, RESOURCES[res].live);
|
||||
} else {
|
||||
drawBuilding(ctx, tool, px, py, {});
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
}
|
||||
ctx.strokeStyle = demolish ? (ok ? '#c03030' : '#555') : (ok ? '#e0603a' : '#c03030');
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeRect(px + 1, py + 1, TILE - 2, TILE - 2);
|
||||
}
|
||||
|
||||
export function render(ctx, state) {
|
||||
const { zoom, ox, oy } = camera;
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
|
||||
ctx.setTransform(zoom, 0, 0, zoom, ox, oy);
|
||||
ctx.imageSmoothingEnabled = false;
|
||||
|
||||
const t = performance.now() / 1000;
|
||||
const under = state.mode === 'underground'; // vue sous-terre : sol assombri, bâtiments en filigrane, tuyaux visibles
|
||||
const { x0, x1, y0, y1 } = visibleRange();
|
||||
|
||||
ctx.drawImage(terrainLayer(state), 0, 0);
|
||||
if (under) {
|
||||
ctx.fillStyle = 'rgba(52, 33, 18, 0.58)';
|
||||
ctx.fillRect(0, 0, state.grid[0].length * TILE, state.grid.length * TILE);
|
||||
}
|
||||
|
||||
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {
|
||||
if (state.water[y][x]) { // on ne construit pas sur l'eau
|
||||
drawWater(ctx, state.water, x, y, t);
|
||||
if (under) { ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'; ctx.fillRect(x * TILE, y * TILE, TILE, TILE); }
|
||||
continue;
|
||||
}
|
||||
const cell = state.grid[y][x];
|
||||
if (!cell) continue;
|
||||
const idle = cell.status === 'unmanaged' || cell.status === 'maintenance';
|
||||
if (under) ctx.globalAlpha = 0.35;
|
||||
else if (idle) ctx.globalAlpha = 0.45;
|
||||
drawBuilding(ctx, cell.type, x * TILE, y * TILE, cell);
|
||||
ctx.globalAlpha = 1;
|
||||
const def = BUILDINGS[cell.type];
|
||||
if (def) drawStatus(ctx, cell, def, x * TILE, y * TILE);
|
||||
}
|
||||
|
||||
if (under) drawPipes(ctx, state, t);
|
||||
else {
|
||||
drawWindOverlay(ctx, state);
|
||||
drawPlacementOverlay(ctx, state);
|
||||
}
|
||||
drawHover(ctx, state);
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
// Simulation : aucun accès au DOM ni au canvas.
|
||||
import { BUILDINGS } from './data/buildings.js';
|
||||
import { WIND_CHANGE, ELECTRICITY_PRICE } from './data/world.js';
|
||||
import { RESOURCE_IDS } from './data/pipes.js';
|
||||
import { windAt, pickWindDir, nextWindDelay } from './terrain.js';
|
||||
|
||||
const TAU = Math.PI * 2;
|
||||
const NEIGHBORS = [[0, -1], [0, 1], [-1, 0], [1, 0]];
|
||||
|
||||
// Un animateur par type d'animation. cell.eff = rendement de la case, il module la vitesse.
|
||||
// rotate → cell.angle (radians) frames → cell.phase (0 .. frames, partie entière = image)
|
||||
const ANIMATORS = {
|
||||
rotate: (cell, a, dt) => { cell.angle = ((cell.angle || 0) + a.speed * (cell.eff ?? 1) * dt) % TAU; },
|
||||
frames: (cell, a, dt) => { cell.phase = ((cell.phase || 0) + a.fps * (cell.eff ?? 1) * dt) % a.frames; },
|
||||
};
|
||||
|
||||
function updateWind(state, dt) {
|
||||
if (!(WIND_CHANGE.max > 0)) return;
|
||||
state.wind.timer -= dt;
|
||||
if (state.wind.timer <= 0) {
|
||||
state.wind.dir = pickWindDir(state.wind.dir);
|
||||
state.wind.timer = nextWindDelay();
|
||||
}
|
||||
}
|
||||
|
||||
function tickNotice(state, dt) {
|
||||
if (state.notice && (state.notice.ttl -= dt) <= 0) state.notice = null;
|
||||
}
|
||||
|
||||
// Tout bâtiment occupe un poste de bureau, sauf les bureaux eux-mêmes ou ceux qui déclarent
|
||||
// "requiresOffice": false dans leur building.json.
|
||||
function needsOffice(def) {
|
||||
return def.requiresOffice ?? !def.office;
|
||||
}
|
||||
|
||||
// Entretien : le coût est payé tout de suite (l'argent peut passer sous zéro),
|
||||
// puis le bâtiment s'arrête `duration` secondes. duration 0 : le coût seul (ex. salaires).
|
||||
function startMaintenance(state, cell, m) {
|
||||
state.money -= m.cost ?? 0;
|
||||
cell.mt = m.every;
|
||||
cell.maint = m.duration > 0 ? m.duration : null;
|
||||
if (cell.maint != null) { cell.status = 'maintenance'; cell.eff = 0; }
|
||||
}
|
||||
|
||||
// Une ressource (eau, vapeur) : on regroupe les tuyaux de ce type en réseaux (cases voisines) ;
|
||||
// un bâtiment qui produit ou consomme cette ressource se relie aux tuyaux posés sur ses cases voisines.
|
||||
// Dans chaque réseau, l'offre (producteurs) est répartie entre les demandes (consommateurs) :
|
||||
// satisfaction = min(1, offre / demande). Un consommateur voit son rendement multiplié par sa satisfaction.
|
||||
// Les producteurs fournissent selon leur rendement actuel : une centrale privée d'eau ne fait pas de vapeur.
|
||||
function flowStage(state, active, res) {
|
||||
const rows = state.grid.length, cols = state.grid[0].length, N = rows * cols;
|
||||
const pipeAt = (x, y) => state.pipes[y]?.[x] === res;
|
||||
|
||||
// Union-find : nœuds 0..N-1 = tuyaux (par case), N..2N-1 = bâtiments (par case).
|
||||
const parent = Int32Array.from({ length: 2 * N }, (_, i) => i);
|
||||
const find = i => { while (parent[i] !== i) { parent[i] = parent[parent[i]]; i = parent[i]; } return i; };
|
||||
const union = (a, b) => { parent[find(a)] = find(b); };
|
||||
|
||||
for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
|
||||
if (!pipeAt(x, y)) continue;
|
||||
const i = y * cols + x;
|
||||
if (pipeAt(x + 1, y)) union(i, i + 1);
|
||||
if (pipeAt(x, y + 1)) union(i, i + cols);
|
||||
}
|
||||
|
||||
const users = active.filter(({ def }) => def.produces?.[res] != null || def.consumes?.[res] != null);
|
||||
for (const { x, y } of users) {
|
||||
for (const [dx, dy] of NEIGHBORS) if (pipeAt(x + dx, y + dy)) union(N + y * cols + x, (y + dy) * cols + x + dx);
|
||||
}
|
||||
|
||||
const nets = new Map();
|
||||
const netOf = node => {
|
||||
const root = find(node);
|
||||
if (!nets.has(root)) nets.set(root, { supply: 0, demand: 0 });
|
||||
return nets.get(root);
|
||||
};
|
||||
|
||||
for (const { cell, def, x, y } of users) {
|
||||
const net = netOf(N + y * cols + x);
|
||||
net.supply += (def.produces?.[res] ?? 0) * cell.eff;
|
||||
net.demand += (def.consumes?.[res] ?? 0) * cell.eff;
|
||||
}
|
||||
|
||||
for (const { cell, def, x, y } of users) {
|
||||
if (def.consumes?.[res] == null || !(cell.eff > 0)) continue;
|
||||
const { supply, demand } = netOf(N + y * cols + x);
|
||||
const sat = Math.min(1, supply / demand);
|
||||
if (sat < 1) { cell.eff *= sat; cell.starved = res; }
|
||||
}
|
||||
|
||||
for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
|
||||
if (pipeAt(x, y)) state.pipeNet[y][x] = netOf(y * cols + x);
|
||||
}
|
||||
}
|
||||
|
||||
// État d'une case (cell.status) :
|
||||
// running : produit, s'anime, son compte à rebours d'entretien avance
|
||||
// maintenance : à l'arrêt pendant l'entretien
|
||||
// unmanaged : pas assez de bureaux, à l'arrêt, ses compteurs sont gelés
|
||||
// cell.starved : ressource qui manque à une case « running » (ou null) ; cell.eff : rendement final.
|
||||
export function update(state, dt) {
|
||||
updateWind(state, dt);
|
||||
tickNotice(state, dt);
|
||||
|
||||
const items = [];
|
||||
state.grid.forEach((row, y) => row.forEach((cell, x) => {
|
||||
const def = cell && BUILDINGS[cell.type];
|
||||
if (def) items.push({ cell, def, x, y });
|
||||
}));
|
||||
items.sort((a, b) => a.cell.order - b.cell.order); // les premiers construits sont gérés en premier
|
||||
|
||||
const capacity = items.reduce((n, it) => n + (it.def.office?.capacity ?? 0), 0);
|
||||
let need = 0;
|
||||
let power = 0;
|
||||
|
||||
// 1. Qui fonctionne ? (bureaux, entretien) et rendement de départ (vent).
|
||||
const active = [];
|
||||
for (const it of items) {
|
||||
const { cell, def, x, y } = it;
|
||||
cell.starved = null;
|
||||
const managed = !needsOffice(def) || ++need <= capacity;
|
||||
|
||||
if (!managed) { cell.status = 'unmanaged'; cell.eff = 0; continue; }
|
||||
|
||||
if (cell.maint != null) {
|
||||
cell.status = 'maintenance';
|
||||
cell.eff = 0;
|
||||
cell.maint -= dt;
|
||||
if (cell.maint <= 0) cell.maint = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
cell.status = 'running';
|
||||
cell.eff = def.power?.scalesWithWind ? windAt(state.terrain, x, y, state.wind.dir).factor : 1;
|
||||
active.push(it);
|
||||
}
|
||||
|
||||
// 2. Eau, puis vapeur : le rendement des consommateurs baisse s'il manque de ressource.
|
||||
state.pipeNet = state.grid.map(row => row.map(() => null));
|
||||
for (const res of RESOURCE_IDS) flowStage(state, active, res);
|
||||
|
||||
// 3. Électricité, animations, compte à rebours d'entretien.
|
||||
for (const { cell, def } of active) {
|
||||
if (def.power) power += (def.power.output ?? 0) * cell.eff;
|
||||
if (def.anim) ANIMATORS[def.anim.type]?.(cell, def.anim, dt);
|
||||
|
||||
const m = def.maintenance;
|
||||
if (m?.every && cell.mt != null && (cell.mt -= dt) <= 0) startMaintenance(state, cell, m);
|
||||
}
|
||||
|
||||
state.power = power;
|
||||
state.income = power * ELECTRICITY_PRICE;
|
||||
state.money += state.income * dt;
|
||||
state.slots = { used: Math.min(need, capacity), capacity, need };
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
import { genTerrain, genWater, pickWindDir, nextWindDelay } from './terrain.js';
|
||||
import { BUILDINGS } from './data/buildings.js';
|
||||
import { RESOURCES } from './data/pipes.js';
|
||||
import { START_MONEY, REFUND } from './data/world.js';
|
||||
|
||||
const KEY = 'reactor.save.v1';
|
||||
const COLS = 50;
|
||||
const ROWS = 50;
|
||||
const TAU = Math.PI * 2;
|
||||
|
||||
// Sauvegardé : grid (type, order, mt, maint), terrain, water, pipes, wind.dir, money, counter.
|
||||
// Non sauvegardé : le reste (calculé par la simulation ou lié à l'interface).
|
||||
export const state = {
|
||||
grid: [],
|
||||
terrain: [],
|
||||
water: [], // water[y][x] = true : case d'eau (non constructible)
|
||||
pipes: [], // pipes[y][x] = null | 'water' | 'steam' : tuyau sous terre (un par case)
|
||||
pipeNet: [], // calculé : { supply, demand } du réseau auquel appartient chaque tuyau
|
||||
mode: 'surface', // 'surface' | 'underground' : vue affichée et outils proposés
|
||||
wind: { dir: 0, timer: 0 }, // dir = index dans WIND_DIRS, timer = secondes avant changement
|
||||
money: START_MONEY, // € (peut devenir négatif : entretien payé à crédit)
|
||||
counter: 1, // prochain numéro d'ordre de construction
|
||||
power: 0, // production totale (MW)
|
||||
income: 0, // ventes d'électricité (€/s)
|
||||
slots: { used: 0, capacity: 0, need: 0 }, // postes de gestion
|
||||
notice: null, // message temporaire { text, ttl }
|
||||
tool: null, // null | id d'un bâtiment | 'pipe:<ressource>' | 'demolish'
|
||||
hover: null, // case survolée { x, y } ou null
|
||||
};
|
||||
|
||||
function emptyGrid() {
|
||||
return Array.from({ length: ROWS }, () => Array(COLS).fill(null));
|
||||
}
|
||||
|
||||
// Délai avant le premier entretien : l'intervalle + un peu de hasard, pour désynchroniser.
|
||||
function firstMaintenance(type) {
|
||||
const every = BUILDINGS[type]?.maintenance?.every;
|
||||
return every ? every * (1 + Math.random() * 0.2) : null;
|
||||
}
|
||||
|
||||
// order = ordre de construction : les premiers construits sont les premiers gérés par les bureaux.
|
||||
// mt = secondes avant le prochain entretien, maint = secondes d'entretien restantes (ou null).
|
||||
function makeCell(type, order, mt, maint) {
|
||||
return {
|
||||
type,
|
||||
order,
|
||||
angle: Math.random() * TAU, // départ aléatoire : pas d'animations en phase
|
||||
phase: Math.random() * 1000,
|
||||
mt: mt ?? firstMaintenance(type),
|
||||
maint: maint ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function notify(text) {
|
||||
state.notice = { text, ttl: 2.5 };
|
||||
}
|
||||
|
||||
export function newGame() {
|
||||
state.grid = emptyGrid();
|
||||
state.terrain = genTerrain(COLS, ROWS);
|
||||
state.water = genWater(state.terrain, null, true); // true : peut creuser des vallées d'altitude 1
|
||||
state.pipes = emptyGrid();
|
||||
state.mode = 'surface';
|
||||
state.wind = { dir: pickWindDir(), timer: nextWindDelay() };
|
||||
state.money = START_MONEY;
|
||||
state.counter = 1;
|
||||
state.power = 0;
|
||||
state.income = 0;
|
||||
state.notice = null;
|
||||
save();
|
||||
}
|
||||
|
||||
const NEIGHBORS = [[0, -1], [0, 1], [-1, 0], [1, 0]];
|
||||
|
||||
export function nearWater(x, y) {
|
||||
return NEIGHBORS.some(([dx, dy]) => state.water[y + dy]?.[x + dx]);
|
||||
}
|
||||
|
||||
// 'pipe:water' → 'water' ; autre outil → null
|
||||
export function pipeOfTool(tool) {
|
||||
return tool?.startsWith('pipe:') ? tool.slice(5) : null;
|
||||
}
|
||||
|
||||
// L'outil peut-il s'appliquer sur cette case ? null = oui.
|
||||
// Sinon un objet : { msg } affiche un message, {} refuse sans rien dire (case déjà prise, rien à démolir).
|
||||
export function placeCheck(tool, x, y) {
|
||||
if (tool === 'demolish') {
|
||||
const target = state.mode === 'underground' ? state.pipes[y][x] : state.grid[y][x];
|
||||
return target ? null : {};
|
||||
}
|
||||
|
||||
const res = pipeOfTool(tool);
|
||||
const def = res ? null : BUILDINGS[tool];
|
||||
if (!RESOURCES[res] && !def) return {};
|
||||
|
||||
if (res) {
|
||||
if (state.water[y][x]) return { msg: "Pas de tuyau sous l'eau" };
|
||||
if (state.pipes[y][x]) return {};
|
||||
} else {
|
||||
if (state.grid[y][x]) return {};
|
||||
if (state.water[y][x]) return { msg: "Impossible de construire sur l'eau" };
|
||||
if (def.placement?.adjacentWater && !nearWater(x, y)) return { msg: `${def.name} : à construire au bord de l'eau` };
|
||||
}
|
||||
|
||||
const cost = res ? RESOURCES[res].cost : (def.cost ?? 0);
|
||||
return state.money < cost ? { msg: `Fonds insuffisants : ${cost} € requis` } : null;
|
||||
}
|
||||
|
||||
// Applique l'outil actif sur une case : construit / pose un tuyau (si assez d'argent) ou démolit (remboursement partiel).
|
||||
// En vue sous-terre, « démolir » retire les tuyaux ; en surface, les bâtiments.
|
||||
export function applyTool(x, y) {
|
||||
const tool = state.tool;
|
||||
if (!tool) return;
|
||||
|
||||
const refusal = placeCheck(tool, x, y);
|
||||
if (refusal) {
|
||||
if (refusal.msg) notify(refusal.msg);
|
||||
return;
|
||||
}
|
||||
|
||||
const res = pipeOfTool(tool);
|
||||
if (tool === 'demolish') {
|
||||
if (state.mode === 'underground') {
|
||||
state.money += Math.round(RESOURCES[state.pipes[y][x]].cost * REFUND);
|
||||
state.pipes[y][x] = null;
|
||||
} else {
|
||||
const cell = state.grid[y][x];
|
||||
state.money += Math.round((BUILDINGS[cell.type]?.cost ?? 0) * REFUND);
|
||||
state.grid[y][x] = null;
|
||||
}
|
||||
} else if (res) {
|
||||
state.money -= RESOURCES[res].cost;
|
||||
state.pipes[y][x] = res;
|
||||
} else {
|
||||
state.money -= BUILDINGS[tool].cost ?? 0;
|
||||
state.grid[y][x] = makeCell(tool, state.counter++);
|
||||
}
|
||||
save();
|
||||
}
|
||||
|
||||
export function hasSave() {
|
||||
try { return localStorage.getItem(KEY) !== null; } catch { return false; }
|
||||
}
|
||||
|
||||
export function save() {
|
||||
try {
|
||||
const r1 = v => (v == null ? null : Math.round(v * 10) / 10);
|
||||
const grid = state.grid.map(row => row.map(c => c && {
|
||||
type: c.type, order: c.order, mt: r1(c.mt), maint: r1(c.maint),
|
||||
}));
|
||||
localStorage.setItem(KEY, JSON.stringify({
|
||||
v: 5,
|
||||
grid,
|
||||
terrain: state.terrain,
|
||||
water: state.water.map(row => row.map(Number)),
|
||||
pipes: state.pipes,
|
||||
wind: { dir: state.wind.dir },
|
||||
money: Math.round(state.money * 100) / 100,
|
||||
counter: state.counter,
|
||||
}));
|
||||
} catch (e) {
|
||||
console.warn('Sauvegarde impossible :', e);
|
||||
}
|
||||
}
|
||||
|
||||
export function load() {
|
||||
try {
|
||||
const data = JSON.parse(localStorage.getItem(KEY));
|
||||
// Anciennes sauvegardes : pas de numéro d'ordre → on en attribue dans l'ordre de la grille.
|
||||
const maxOrder = Math.max(0, ...data.grid.flat().map(c => c?.order ?? 0));
|
||||
let counter = Math.max(data.counter ?? 1, maxOrder + 1);
|
||||
|
||||
state.grid = data.grid.map(row => row.map(c => c && makeCell(c.type, c.order ?? counter++, c.mt, c.maint)));
|
||||
state.counter = counter;
|
||||
state.money = data.money ?? START_MONEY;
|
||||
|
||||
const missingTerrain = !data.terrain;
|
||||
state.terrain = data.terrain ?? genTerrain(state.grid[0].length, state.grid.length);
|
||||
// Anciennes sauvegardes sans eau : on en génère, jamais sous un bâtiment existant.
|
||||
const missingWater = !data.water;
|
||||
state.water = data.water
|
||||
? data.water.map(row => row.map(Boolean))
|
||||
: genWater(state.terrain, state.grid.map(row => row.map(Boolean)));
|
||||
// Tuyaux : on ne garde que les types connus, jamais sous l'eau (anciennes sauvegardes : aucun tuyau).
|
||||
state.pipes = state.grid.map((row, y) => row.map((_, x) => {
|
||||
const p = data.pipes?.[y]?.[x];
|
||||
return RESOURCES[p] && !state.water[y][x] ? p : null;
|
||||
}));
|
||||
state.mode = 'surface';
|
||||
state.wind = { dir: data.wind?.dir ?? pickWindDir(), timer: nextWindDelay() };
|
||||
state.power = 0;
|
||||
state.income = 0;
|
||||
state.notice = null;
|
||||
if (missingTerrain || missingWater || data.v !== 5) save(); // fige le relief et l'eau générés / migre vers la v5
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
// Relief et vent : génération du terrain, rendement des éoliennes. Aucun accès DOM.
|
||||
import { MAX_HEIGHT, WIND_DIRS, WIND_RULES, WIND_CHANGE, WATER, TERRAIN } from './data/world.js';
|
||||
|
||||
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
|
||||
|
||||
// Collines gaussiennes (sommets à MAX_HEIGHT-1 .. MAX_HEIGHT), arrondies à des altitudes entières. Nombre et rayon : voir TERRAIN.
|
||||
export function genTerrain(cols, rows) {
|
||||
const count = Math.max(TERRAIN.minHills, Math.round(cols * rows / TERRAIN.cellsPerHill * (0.8 + Math.random() * 0.4)));
|
||||
const { min, max } = TERRAIN.radius;
|
||||
const hills = Array.from({ length: count }, () => ({
|
||||
x: Math.random() * cols,
|
||||
y: Math.random() * rows,
|
||||
r: min + Math.random() * (max - min),
|
||||
h: MAX_HEIGHT - 1 + Math.random(),
|
||||
}));
|
||||
return Array.from({ length: rows }, (_, y) => Array.from({ length: cols }, (_, x) => {
|
||||
let v = 0;
|
||||
for (const hl of hills) {
|
||||
const d2 = (x - hl.x) ** 2 + (y - hl.y) ** 2;
|
||||
v = Math.max(v, hl.h * Math.exp(-d2 / (2 * hl.r ** 2)));
|
||||
}
|
||||
return clamp(Math.round(v), 0, MAX_HEIGHT);
|
||||
}));
|
||||
}
|
||||
|
||||
// Bruit de valeurs lissé : treillis aléatoire interpolé (smoothstep), valeurs dans 0..1.
|
||||
function makeNoise(scale) {
|
||||
const n = 64;
|
||||
const lattice = Array.from({ length: n * n }, () => Math.random());
|
||||
const at = (i, j) => lattice[((j % n) + n) % n * n + ((i % n) + n) % n];
|
||||
const smooth = t => t * t * (3 - 2 * t);
|
||||
const ox = Math.random() * 20, oy = Math.random() * 20; // décalage : pas toujours le même coin
|
||||
return (x, y) => {
|
||||
const fx = x / scale + ox, fy = y / scale + oy;
|
||||
const i = Math.floor(fx), j = Math.floor(fy);
|
||||
const tx = smooth(fx - i), ty = smooth(fy - j);
|
||||
const top = at(i, j) * (1 - tx) + at(i + 1, j) * tx;
|
||||
const bot = at(i, j + 1) * (1 - tx) + at(i + 1, j + 1) * tx;
|
||||
return top * (1 - ty) + bot * ty;
|
||||
};
|
||||
}
|
||||
|
||||
// Eau : taches organiques dans les basses terres, jamais sur une case `blocked` (déjà construite).
|
||||
// On trie les cases candidates par bruit (légèrement pénalisé par l'altitude) et on prend les plus fortes :
|
||||
// la quantité varie d'une partie à l'autre, la forme suit le bruit (lacs, mares, golfes), et les cases d'eau
|
||||
// isolées sont retirées.
|
||||
// carve = true (nouvelle partie) : l'eau peut aussi occuper des cases d'altitude 1, aplanies à 0 (vallée),
|
||||
// ce qui garantit de l'eau même sur une carte très vallonnée. Sans carve (vieille sauvegarde), le relief
|
||||
// n'est jamais modifié : seules les cases d'altitude 0 sont possibles.
|
||||
export function genWater(terrain, blocked, carve = false) {
|
||||
const rows = terrain.length, cols = terrain[0].length;
|
||||
const coarse = makeNoise(WATER.noiseScale), fine = makeNoise(WATER.noiseScale / 2);
|
||||
const water = Array.from({ length: rows }, () => Array(cols).fill(false));
|
||||
const maxH = carve ? 1 : 0;
|
||||
|
||||
const candidates = [];
|
||||
for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
|
||||
if (terrain[y][x] > maxH || blocked?.[y]?.[x]) continue;
|
||||
candidates.push({ x, y, v: 0.7 * coarse(x, y) + 0.3 * fine(x, y) - 0.3 * terrain[y][x] });
|
||||
}
|
||||
const { min, max } = WATER.coverage;
|
||||
const target = Math.min(
|
||||
Math.round(rows * cols * (min + Math.random() * (max - min))),
|
||||
Math.floor(candidates.length * WATER.maxShare),
|
||||
);
|
||||
candidates.sort((a, b) => b.v - a.v);
|
||||
const picked = candidates.slice(0, target);
|
||||
for (const c of picked) water[c.y][c.x] = true;
|
||||
|
||||
// pas de case d'eau isolée (sauf s'il n'y en a qu'une)
|
||||
if (picked.length > 1) {
|
||||
for (const c of picked) {
|
||||
const linked = [[0, -1], [0, 1], [-1, 0], [1, 0]].some(([dx, dy]) => water[c.y + dy]?.[c.x + dx]);
|
||||
if (!linked) water[c.y][c.x] = false;
|
||||
}
|
||||
}
|
||||
if (carve) {
|
||||
for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) if (water[y][x]) terrain[y][x] = 0;
|
||||
}
|
||||
return water;
|
||||
}
|
||||
|
||||
// Sommet : assez haut, aucune case voisine plus haute et au moins une plus basse.
|
||||
function isSummit(terrain, x, y) {
|
||||
const h = terrain[y][x];
|
||||
const around = [[0, -1], [0, 1], [-1, 0], [1, 0]]
|
||||
.map(([dx, dy]) => terrain[y + dy]?.[x + dx])
|
||||
.filter(v => v !== undefined);
|
||||
return h >= WIND_RULES.summitMinHeight && around.every(v => v <= h) && around.some(v => v < h);
|
||||
}
|
||||
|
||||
// Conditions de vent sur une case. dirIndex = index dans WIND_DIRS.
|
||||
// rise > 0 : le vent arrive d'une case plus basse (pente face au vent).
|
||||
export function windAt(terrain, x, y, dirIndex) {
|
||||
const dir = WIND_DIRS[dirIndex];
|
||||
const height = terrain[y][x];
|
||||
const upwind = terrain[y - dir.dy]?.[x - dir.dx]; // case d'où vient le vent
|
||||
const rise = upwind === undefined ? 0 : height - upwind;
|
||||
const summit = isSummit(terrain, x, y);
|
||||
|
||||
let factor = 1 + WIND_RULES.perRise * rise;
|
||||
if (summit) factor *= WIND_RULES.summit;
|
||||
factor = clamp(factor, WIND_RULES.min, WIND_RULES.max);
|
||||
|
||||
const label = summit ? 'sommet' : rise > 0 ? 'pente face au vent' : rise < 0 ? 'pente sous le vent' : 'plat';
|
||||
return { height, rise, summit, factor, label };
|
||||
}
|
||||
|
||||
export function pickWindDir(previous) {
|
||||
let d;
|
||||
do { d = Math.floor(Math.random() * WIND_DIRS.length); } while (d === previous);
|
||||
return d;
|
||||
}
|
||||
|
||||
export function nextWindDelay() {
|
||||
return WIND_CHANGE.min + Math.random() * (WIND_CHANGE.max - WIND_CHANGE.min);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { state, hasSave, notify, save } from './state.js';
|
||||
import { BUILDINGS } from './data/buildings.js';
|
||||
import { drawBuildingIcon, drawPipeIcon } from './render.js';
|
||||
import { RESOURCES } from './data/pipes.js';
|
||||
import { WIND_DIRS, REFUND } from './data/world.js';
|
||||
import { windAt } from './terrain.js';
|
||||
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
export function initUI({ onNew, onContinue, onMenu }) {
|
||||
$('btn-new').onclick = onNew;
|
||||
$('btn-continue').onclick = onContinue;
|
||||
$('btn-menu').onclick = onMenu;
|
||||
for (const [name, m] of Object.entries(MENUS)) $(m.btn).onclick = () => toggleMenu(name);
|
||||
document.addEventListener('keydown', e => {
|
||||
const inGame = !$('game').classList.contains('hidden');
|
||||
if (inGame) watchDevCode(e);
|
||||
if (e.key === 'Escape') setMenu(null);
|
||||
else if ((e.key === 'u' || e.key === 'U') && inGame) toggleMenu('pipes');
|
||||
});
|
||||
buildLists();
|
||||
showMenu();
|
||||
}
|
||||
|
||||
function drawDemolishIcon(ctx) {
|
||||
ctx.fillStyle = '#c03030';
|
||||
for (let i = 0; i < 18; i++) { // croix en pixels
|
||||
ctx.fillRect(7 + i, 7 + i, 3, 3);
|
||||
ctx.fillRect(24 - i, 7 + i, 3, 3);
|
||||
}
|
||||
}
|
||||
|
||||
function addTool(menu, id, name, drawIcon, sub, cost = 0) {
|
||||
const icon = document.createElement('canvas');
|
||||
icon.width = icon.height = 32;
|
||||
drawIcon(icon.getContext('2d'));
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.textContent = name;
|
||||
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'tool';
|
||||
btn.dataset.tool = id;
|
||||
btn.dataset.menu = menu; // « Démolir » existe dans les deux menus : on ne surligne que celui qui est ouvert
|
||||
btn.setAttribute('aria-pressed', 'false');
|
||||
btn.dataset.cost = cost;
|
||||
const subLabel = document.createElement('span');
|
||||
subLabel.className = 'cost';
|
||||
subLabel.textContent = sub;
|
||||
btn.append(icon, label, subLabel);
|
||||
btn.onclick = () => setTool(state.tool === id ? null : id);
|
||||
|
||||
const li = document.createElement('li');
|
||||
li.append(btn);
|
||||
$(MENUS[menu].list).append(li);
|
||||
}
|
||||
|
||||
// Menus de construction : un bouton sur le côté qui ouvre un menu déroulant. Un seul menu ouvert à la fois.
|
||||
// build : bâtiments (vue de surface) ; pipes : tuyaux (vue sous-terre, « Retirer » démolit un tuyau).
|
||||
const MENUS = {
|
||||
build: { btn: 'btn-build', list: 'build-list', mode: 'surface' },
|
||||
pipes: { btn: 'btn-layer', list: 'pipe-list', mode: 'underground' },
|
||||
};
|
||||
let openMenu = null;
|
||||
|
||||
function buildLists() {
|
||||
for (const [id, building] of Object.entries(BUILDINGS)) {
|
||||
addTool('build', id, building.name, ctx => drawBuildingIcon(ctx, id), `${building.cost ?? 0} €`, building.cost ?? 0);
|
||||
}
|
||||
addTool('build', 'demolish', 'Démolir', drawDemolishIcon, `${Math.round(REFUND * 100)} % remboursé`);
|
||||
|
||||
for (const [id, r] of Object.entries(RESOURCES)) {
|
||||
addTool('pipes', `pipe:${id}`, r.pipe, ctx => drawPipeIcon(ctx, id), `${r.cost} € / case`, r.cost);
|
||||
}
|
||||
addTool('pipes', 'demolish', 'Retirer', drawDemolishIcon, `${Math.round(REFUND * 100)} % remboursé`);
|
||||
}
|
||||
|
||||
export function setTool(tool) {
|
||||
state.tool = tool;
|
||||
document.querySelectorAll('.dropdown .tool').forEach(btn => {
|
||||
const on = btn.dataset.tool === tool && btn.dataset.menu === openMenu;
|
||||
btn.classList.toggle('selected', on);
|
||||
btn.setAttribute('aria-pressed', String(on));
|
||||
});
|
||||
}
|
||||
|
||||
function closeMenu() {
|
||||
const m = MENUS[openMenu];
|
||||
$(m.list).classList.add('hidden');
|
||||
$(m.btn).classList.remove('active');
|
||||
$(m.btn).setAttribute('aria-expanded', 'false');
|
||||
openMenu = null;
|
||||
}
|
||||
|
||||
// Ouvre un menu (ou ferme tout avec null). Le menu déjà ouvert est fermé d'abord ; la vue suit :
|
||||
// sous-terre quand le menu des tuyaux est ouvert, surface sinon. Changer de menu désélectionne l'outil.
|
||||
export function setMenu(name) {
|
||||
if (name === openMenu) return;
|
||||
if (openMenu) closeMenu();
|
||||
openMenu = name;
|
||||
if (name) {
|
||||
const m = MENUS[name];
|
||||
$(m.list).classList.remove('hidden');
|
||||
$(m.btn).classList.add('active');
|
||||
$(m.btn).setAttribute('aria-expanded', 'true');
|
||||
}
|
||||
state.mode = name ? MENUS[name].mode : 'surface';
|
||||
state.hover = null;
|
||||
setTool(null);
|
||||
}
|
||||
|
||||
function toggleMenu(name) {
|
||||
setMenu(openMenu === name ? null : name);
|
||||
}
|
||||
|
||||
// Mode dev : taper « devmode » pendant une partie (sans rien sélectionner de particulier) ajoute de l'argent.
|
||||
const DEV_CODE = 'devmode';
|
||||
const DEV_MONEY = 99999;
|
||||
let devBuffer = '';
|
||||
|
||||
function watchDevCode(e) {
|
||||
if (e.ctrlKey || e.metaKey || e.altKey || e.key.length !== 1) return; // lettres seules
|
||||
devBuffer = (devBuffer + e.key.toLowerCase()).slice(-DEV_CODE.length);
|
||||
if (devBuffer !== DEV_CODE) return;
|
||||
devBuffer = '';
|
||||
state.money += DEV_MONEY;
|
||||
notify(`Mode dev : +${DEV_MONEY.toLocaleString('fr-FR')} €`);
|
||||
save();
|
||||
}
|
||||
|
||||
export function showMenu() {
|
||||
setMenu(null);
|
||||
$('menu').classList.remove('hidden');
|
||||
$('game').classList.add('hidden');
|
||||
$('btn-continue').disabled = !hasSave();
|
||||
}
|
||||
|
||||
export function showGame() {
|
||||
setMenu(null);
|
||||
state.mode = 'surface';
|
||||
$('menu').classList.add('hidden');
|
||||
$('game').classList.remove('hidden');
|
||||
}
|
||||
|
||||
// ---------- HUD : production, vent, infos de la case survolée ----------
|
||||
|
||||
const fmt = n => n.toLocaleString('fr-FR', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
|
||||
|
||||
function setText(id, text) {
|
||||
const el = $(id);
|
||||
if (el.textContent !== text) el.textContent = text; // évite de toucher au DOM sans raison
|
||||
}
|
||||
|
||||
function buildingInfo(cell, def) {
|
||||
if (cell.status === 'unmanaged') return `${def.name} : non gérée (pas assez de bureaux)`;
|
||||
if (cell.status === 'maintenance') return `${def.name} : en entretien (${Math.ceil(cell.maint)} s)`;
|
||||
const eff = cell.eff ?? 1;
|
||||
const bits = [def.name];
|
||||
if (def.power) bits.push(`${fmt(def.power.output * eff)} MW`);
|
||||
for (const [res, rate] of Object.entries(def.produces ?? {})) bits.push(`${RESOURCES[res]?.label ?? res} ${fmt(rate * eff)}/s`);
|
||||
if (cell.starved) bits.push(RESOURCES[cell.starved].lack);
|
||||
if (def.office) bits.push(`${def.office.capacity} postes`);
|
||||
if (def.maintenance?.every && cell.mt != null) bits.push(`entretien dans ${Math.ceil(cell.mt)} s`);
|
||||
return bits.join(' · ');
|
||||
}
|
||||
|
||||
function cellInfo(state) {
|
||||
if (state.notice) return state.notice.text;
|
||||
const hv = state.hover;
|
||||
if (!hv) return state.mode === 'underground'
|
||||
? "Vue sous-terre : relie la pompe, la centrale et la turbine avec des tuyaux (glisser pour en poser plusieurs)."
|
||||
: "Molette : zoom · clic maintenu sans outil : déplacer la vue · clic droit : désélectionner l'outil";
|
||||
const cell = state.grid[hv.y][hv.x];
|
||||
const def = cell && BUILDINGS[cell.type];
|
||||
const w = windAt(state.terrain, hv.x, hv.y, state.wind.dir);
|
||||
|
||||
if (state.water[hv.y][hv.x]) return "Eau · non constructible";
|
||||
|
||||
const under = state.mode === 'underground';
|
||||
const pipe = state.pipes[hv.y][hv.x];
|
||||
const net = state.pipeNet[hv.y]?.[hv.x];
|
||||
|
||||
const parts = [];
|
||||
if (def) parts.push(buildingInfo(cell, def));
|
||||
if (under && pipe) parts.push(`${RESOURCES[pipe].pipe} · offre ${fmt(net?.supply ?? 0)}/s · demande ${fmt(net?.demand ?? 0)}/s`);
|
||||
parts.push(`Altitude ${w.height}`);
|
||||
if (!under && (!def || def.power?.scalesWithWind)) parts.push(`${w.label}, vent x${fmt(w.factor)}`);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
function setNeg(id, neg) {
|
||||
$(id).classList.toggle('neg', neg);
|
||||
}
|
||||
|
||||
export function updateHud(state) {
|
||||
const dir = WIND_DIRS[state.wind.dir];
|
||||
const { capacity, need } = state.slots;
|
||||
|
||||
setText('hud-money', `Argent : ${Math.trunc(state.money).toLocaleString('fr-FR')} €`);
|
||||
setNeg('hud-money', state.money < 0);
|
||||
setText('hud-power', `Production : ${fmt(state.power)} MW (+${fmt(state.income)} €/s)`);
|
||||
setText('hud-slots', `Gestion : ${need}/${capacity}`);
|
||||
setNeg('hud-slots', need > capacity);
|
||||
setText('hud-wind', `Vent ${dir.label} ${dir.arrow}`);
|
||||
setText('hud-cell', cellInfo(state));
|
||||
|
||||
document.querySelectorAll('.dropdown .tool').forEach(btn => {
|
||||
btn.classList.toggle('poor', state.money < Number(btn.dataset.cost));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
:root {
|
||||
--bg: #161616;
|
||||
--cell: #2a2a2a;
|
||||
--line: #3a3a3a;
|
||||
--text: #d8d8d8;
|
||||
--muted: #8a8a8a;
|
||||
--accent: #e0603a;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace;
|
||||
}
|
||||
|
||||
.screen {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.hidden { display: none !important; }
|
||||
|
||||
h1 {
|
||||
margin: 0 0 1.5rem;
|
||||
font-size: 3rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
button {
|
||||
min-width: 12rem;
|
||||
padding: 0.7rem 2rem;
|
||||
font: inherit;
|
||||
font-size: 1.1rem;
|
||||
color: var(--text);
|
||||
background: var(--cell);
|
||||
border: 2px solid var(--muted);
|
||||
box-shadow: 4px 4px 0 #000;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) { border-color: var(--accent); }
|
||||
|
||||
button:active:not(:disabled) {
|
||||
transform: translate(2px, 2px);
|
||||
box-shadow: 2px 2px 0 #000;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
color: #555;
|
||||
border-color: var(--line);
|
||||
box-shadow: none;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
button:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
#btn-menu { align-self: flex-start; min-width: 0; padding: 0.4rem 1.2rem; font-size: 1rem; }
|
||||
|
||||
canvas {
|
||||
display: block;
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
|
||||
/* Écran de jeu : plein écran, la zone de la carte prend tout l'espace restant. */
|
||||
#game {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
align-items: stretch;
|
||||
gap: 0.6rem;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.stage {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.viewport {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
background: #0e0e0e;
|
||||
border: 2px solid var(--line);
|
||||
}
|
||||
|
||||
.viewport canvas {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
touch-action: none; /* glisser = déplacer la vue ou poser des tuyaux, jamais faire défiler la page */
|
||||
}
|
||||
|
||||
/* Boutons de menu sur le côté ; chacun ouvre un menu déroulant à sa droite, par-dessus la carte. */
|
||||
.sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.side-item { position: relative; }
|
||||
|
||||
.icon-btn { min-width: 0; padding: 0.6rem; line-height: 0; }
|
||||
.icon-btn svg { width: 28px; height: 28px; fill: currentColor; }
|
||||
.icon-btn.active { border-color: var(--accent); color: var(--accent); }
|
||||
|
||||
.dropdown {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: calc(100% + 0.5rem);
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
min-width: 16rem;
|
||||
max-height: calc(100dvh - 7rem);
|
||||
margin: 0;
|
||||
padding: 0.6rem;
|
||||
overflow-y: auto;
|
||||
list-style: none;
|
||||
background: var(--bg);
|
||||
border: 2px solid var(--muted);
|
||||
box-shadow: 4px 4px 0 #000;
|
||||
}
|
||||
|
||||
.tool {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.35rem 0.7rem;
|
||||
font-size: 0.9rem;
|
||||
text-align: left;
|
||||
box-shadow: 2px 2px 0 #000;
|
||||
}
|
||||
|
||||
.tool canvas { flex: none; width: 40px; height: 40px; }
|
||||
.tool .cost { margin-left: auto; padding-left: 0.5rem; white-space: nowrap; }
|
||||
.tool.selected { border-color: var(--accent); }
|
||||
|
||||
.topbar {
|
||||
align-self: stretch;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.topbar #btn-menu { align-self: center; }
|
||||
|
||||
.hud { display: flex; flex-wrap: wrap; gap: 0.25rem 1.5rem; }
|
||||
#hud-power { color: var(--accent); font-weight: 700; }
|
||||
|
||||
.info { margin: 0; min-height: 1.4em; color: var(--muted); font-size: 0.9rem; }
|
||||
|
||||
#hud-money { font-weight: 700; }
|
||||
.neg { color: #e05050; }
|
||||
|
||||
.tool .cost { color: var(--muted); font-size: 0.75rem; }
|
||||
.tool.poor .cost { color: #e05050; }
|
||||
|
||||
.info { text-align: center; }
|
||||
Reference in New Issue
Block a user