Bläddra i källkod

Add difficulty levels to Orbital Claim mining mode

Mining Race now has Easy, Normal and Hard, defined in entities.json. Each level sets the quota, time limit, starting minerals, ore field shape, and enemy hull, count and build-window scaling.

The title screen shows one start button per difficulty, with its quota, clock and personal best. Restart and Play Again keep the chosen difficulty.

Field generation takes a minOre option, so a field always holds at least target x oreMargin ore, whatever the seed. Personal bests are stored per difficulty; Normal keeps the old 'mining' key, so existing records still count. The pause menu shows the ore left in the field, and the end summary shows the difficulty.
Toby Chui 3 veckor sedan
förälder
incheckning
fe8be3af30

+ 44 - 1
src/web/Orbital Claim/assets/entities.json

@@ -635,7 +635,50 @@
     "mining": {
     "mining": {
       "goal": "Bank a target amount of minerals before the timer expires.",
       "goal": "Bank a target amount of minerals before the timer expires.",
       "target": 6000,
       "target": 6000,
-      "time": 600
+      "time": 600,
+      "defaultDifficulty": "normal",
+      "difficulties": {
+        "$comment": "oreMargin: every field holds at least target x oreMargin ore, whatever the seed. clusters / oreRichness / homeRocks shape the field; enemyHp / enemyCount / buildWindow scale the waves.",
+        "easy": {
+          "name": "Easy",
+          "target": 4000,
+          "time": 720,
+          "startMinerals": 450,
+          "clusters": 16,
+          "oreRichness": 1.15,
+          "homeRocks": 9,
+          "oreMargin": 4,
+          "enemyHp": 0.7,
+          "enemyCount": 0.75,
+          "buildWindow": 1.3
+        },
+        "normal": {
+          "name": "Normal",
+          "target": 6000,
+          "time": 600,
+          "startMinerals": 300,
+          "clusters": 14,
+          "oreRichness": 1,
+          "homeRocks": 7,
+          "oreMargin": 3,
+          "enemyHp": 1,
+          "enemyCount": 1,
+          "buildWindow": 1
+        },
+        "hard": {
+          "name": "Hard",
+          "target": 9000,
+          "time": 480,
+          "startMinerals": 250,
+          "clusters": 8,
+          "oreRichness": 0.6,
+          "homeRocks": 4,
+          "oreMargin": 2.5,
+          "enemyHp": 1.35,
+          "enemyCount": 1.3,
+          "buildWindow": 0.8
+        }
+      }
     },
     },
     "survival": {
     "survival": {
       "goal": "Last as long as possible against endless escalating waves."
       "goal": "Last as long as possible against endless escalating waves."

+ 21 - 0
src/web/Orbital Claim/index.html

@@ -102,6 +102,27 @@
   .mode .mn { display:block; font-size:15px; font-weight:600; color:#e6f2ff; }
   .mode .mn { display:block; font-size:15px; font-weight:600; color:#e6f2ff; }
   .mode .md { display:block; font-size:11.5px; color:var(--dim); margin:5px 0 9px; line-height:1.5; }
   .mode .md { display:block; font-size:11.5px; color:var(--dim); margin:5px 0 9px; line-height:1.5; }
   .mode .mb { display:block; font-size:11px; color:var(--mint); }
   .mode .mb { display:block; font-size:11px; color:var(--mint); }
+  /* A mode with difficulties: the card holds one start button per level. */
+  .mode.has-diff { cursor:default; width:262px; }
+  .mode.has-diff:hover { border-color:var(--line); background:var(--panel); transform:none; }
+  .diffs { display:grid; grid-template-columns:repeat(3, 1fr); gap:5px; margin-top:-1px; }
+  .diff {
+    display:flex; flex-direction:column; align-items:center; gap:1px; min-width:0;
+    font:inherit; padding:6px 2px 5px; cursor:pointer; color:var(--text);
+    background:#0d1622; border:1px solid var(--line); border-radius:6px;
+    transition:border-color .14s, background .14s, transform .1s;
+  }
+  .diff:hover { transform:translateY(-1px); }
+  .diff:focus-visible { outline:2px solid var(--cyan); outline-offset:1px; }
+  .diff b { font-size:12px; font-weight:600; }
+  .diff i { font-style:normal; font-size:10px; color:var(--dim); font-variant-numeric:tabular-nums; }
+  .diff em { font-style:normal; font-size:10px; color:var(--mint); font-variant-numeric:tabular-nums; }
+  .diff-easy b { color:var(--mint); }
+  .diff-easy:hover { border-color:#2f7a5c; background:#0f2420; }
+  .diff-normal b { color:var(--cyan); }
+  .diff-normal:hover { border-color:var(--cyan); background:#101f2b; }
+  .diff-hard b { color:#ff9a8b; }
+  .diff-hard:hover { border-color:#7d3a3a; background:#1d1013; }
   .mode.debug { border-style:dashed; border-color:#6b4d16; }
   .mode.debug { border-style:dashed; border-color:#6b4d16; }
   .mode.debug .mb { color:var(--amber); }
   .mode.debug .mb { color:var(--amber); }
   .howto {
   .howto {

+ 72 - 7
src/web/Orbital Claim/src/Game.js

@@ -104,7 +104,7 @@ export class Game {
   _bindOverlay() {
   _bindOverlay() {
     // Bound once, rather than per run, so repeated games do not stack handlers.
     // Bound once, rather than per run, so repeated games do not stack handlers.
     document.getElementById('again').addEventListener('click', () => {
     document.getElementById('again').addEventListener('click', () => {
-      this.start(this.mode?.key ?? 'survival');
+      this.start(this.mode?.key ?? 'survival', this.mode?.difficulty);
     });
     });
     document.getElementById('tomenu').addEventListener('click', () => this.quitToTitle());
     document.getElementById('tomenu').addEventListener('click', () => this.quitToTitle());
     document.getElementById('title-settings').addEventListener('click', () => this.menu.open());
     document.getElementById('title-settings').addEventListener('click', () => this.menu.open());
@@ -168,7 +168,20 @@ export class Game {
   }
   }
 
 
   get modeName() {
   get modeName() {
-    return MODE_NAMES[this.mode?.key] ?? this.mode?.name ?? '';
+    const name = MODE_NAMES[this.mode?.key] ?? this.mode?.name ?? '';
+    return this.mode?.difficultyName ? `${name} (${this.mode.difficultyName})` : name;
+  }
+
+  /**
+   * A mode's settings with its difficulty laid over them. Modes without
+   * difficulties come back as they are, with no difficulty key.
+   */
+  _modeConfig(modeKey, difficulty) {
+    const base = this.data.modes?.[modeKey] ?? {};
+    const diffs = base.difficulties;
+    if (!diffs) return base;
+    const key = diffs[difficulty] ? difficulty : base.defaultDifficulty ?? 'normal';
+    return { ...base, ...diffs[key], difficulty: key };
   }
   }
 
 
   /** Sandbox runs and runs with creative tools switched on. */
   /** Sandbox runs and runs with creative tools switched on. */
@@ -197,6 +210,10 @@ export class Game {
 
 
     for (const [key, cfg] of Object.entries(this.data.modes ?? {})) {
     for (const [key, cfg] of Object.entries(this.data.modes ?? {})) {
       if (!MODE_CLASSES[key]) continue; // 'missions' is not built yet
       if (!MODE_CLASSES[key]) continue; // 'missions' is not built yet
+      if (cfg.difficulties) {
+        list.appendChild(this._difficultyCard(key, cfg));
+        continue;
+      }
       const best = this.save.bestFor(key);
       const best = this.save.bestFor(key);
       const debug = key === 'sandbox';
       const debug = key === 'sandbox';
       const btn = document.createElement('button');
       const btn = document.createElement('button');
@@ -215,6 +232,37 @@ export class Game {
     this.titleScene.start();
     this.titleScene.start();
   }
   }
 
 
+  /**
+   * A mode card with one start button per difficulty, each showing its quota,
+   * clock and personal best — picking a difficulty is starting the run, so
+   * there is no selection to remember.
+   */
+  _difficultyCard(key, cfg) {
+    const card = document.createElement('div');
+    card.className = 'mode has-diff';
+    card.setAttribute('role', 'group');
+    card.setAttribute('aria-label', MODE_NAMES[key] ?? key);
+    const diffs = Object.entries(cfg.difficulties).filter(([k]) => !k.startsWith('$'));
+    card.innerHTML = `
+      <span class="mn">${MODE_NAMES[key] ?? key}</span>
+      <span class="md">${cfg.goal ?? ''}</span>
+      <span class="diffs">
+        ${diffs.map(([dk, d]) => {
+          const best = this.save.bestFor(MiningMode.recordKeyFor(dk));
+          return `<button class="diff diff-${dk}" data-diff="${dk}"
+              title="${d.name}: bank ${d.target.toLocaleString()} minerals in ${formatTime(d.time)}">
+            <b>${d.name}</b>
+            <i>${(d.target / 1000).toLocaleString()}k · ${formatTime(d.time)}</i>
+            <em>${best ? this._formatBest(best) : '—'}</em>
+          </button>`;
+        }).join('')}
+      </span>`;
+    card.querySelectorAll('[data-diff]').forEach((b) => {
+      b.addEventListener('click', () => this.start(key, b.dataset.diff));
+    });
+    return card;
+  }
+
   _formatBest(best) {
   _formatBest(best) {
     if (!best) return '—';
     if (!best) return '—';
     return best.metric === 'time' ? formatTime(best.value) : `wave ${best.value}`;
     return best.metric === 'time' ? formatTime(best.value) : `wave ${best.value}`;
@@ -222,7 +270,12 @@ export class Game {
 
 
   // ------------------------------------------------------------------- start
   // ------------------------------------------------------------------- start
 
 
-  start(modeKey) {
+  /**
+   * @param {string} modeKey
+   * @param {string} [difficulty] for modes that have difficulties; the mode's
+   *   default otherwise
+   */
+  start(modeKey, difficulty) {
     this.menu.close({ resume: false });
     this.menu.close({ resume: false });
     this.titleScene.stop();
     this.titleScene.stop();
     document.getElementById('menu').classList.remove('show');
     document.getElementById('menu').classList.remove('show');
@@ -230,13 +283,25 @@ export class Game {
 
 
     this.runCharts?.destroy();
     this.runCharts?.destroy();
     this.runCharts = null;
     this.runCharts = null;
-    this.world = new World(this.data, Math.floor(Math.random() * 100000));
+    const cfg = this._modeConfig(modeKey, difficulty);
+    this.world = new World(this.data, Math.floor(Math.random() * 100000), {
+      startMinerals: cfg.startMinerals,
+      field: {
+        clusters: cfg.clusters,
+        richness: cfg.oreRichness,
+        homeRocks: cfg.homeRocks,
+        // A quota must always be payable from the field, with room to spare
+        // for rocks lost to raids or too exposed to work.
+        minOre: cfg.target ? cfg.target * (cfg.oreMargin ?? 2) : 0,
+      },
+      waves: { hp: cfg.enemyHp, count: cfg.enemyCount, window: cfg.buildWindow },
+    });
     this.world.onSound = (cue, x, y) => this._worldSound(cue, x, y);
     this.world.onSound = (cue, x, y) => this._worldSound(cue, x, y);
     this.world.waves.onWaveStart = () => this.sound.play('waveStart');
     this.world.waves.onWaveStart = () => this.sound.play('waveStart');
     this.world.waves.onWaveClear = () => this.sound.play('waveClear');
     this.world.waves.onWaveClear = () => this.sound.play('waveClear');
     this.stats = new StatsRecorder(this.world);
     this.stats = new StatsRecorder(this.world);
     const Cls = MODE_CLASSES[modeKey] ?? SurvivalMode;
     const Cls = MODE_CLASSES[modeKey] ?? SurvivalMode;
-    this.mode = new Cls(this.world, this.data.modes?.[modeKey] ?? {});
+    this.mode = new Cls(this.world, cfg);
     this.inRun = true;
     this.inRun = true;
 
 
     this.hud = new Hud(this.hudRoot, this.world, this.data);
     this.hud = new Hud(this.hudRoot, this.world, this.data);
@@ -647,8 +712,8 @@ export class Game {
     this.stats.finish();
     this.stats.finish();
     const won = this.mode.state === 'won';
     const won = this.mode.state === 'won';
     // A run that used creative tools proves nothing, so it never sets a best.
     // A run that used creative tools proves nothing, so it never sets a best.
-    const isBest = !this.mode.creative && this.save.recordScore(this.mode.key, this.mode.score());
-    const best = this.save.bestFor(this.mode.key);
+    const isBest = !this.mode.creative && this.save.recordScore(this.mode.recordKey, this.mode.score());
+    const best = this.save.bestFor(this.mode.recordKey);
     this.sound.setHum(0);
     this.sound.setHum(0);
     this.sound.play(won ? 'win' : 'lose');
     this.sound.play(won ? 'win' : 'lose');
 
 

+ 26 - 13
src/web/Orbital Claim/src/systems/WaveDirector.js

@@ -10,15 +10,24 @@
  * survival mode runs on.
  * survival mode runs on.
  */
  */
 export class WaveDirector {
 export class WaveDirector {
-  constructor(data, world) {
+  /**
+   * @param {object} data
+   * @param {object} world
+   * @param {{hp?:number, count?:number, window?:number}} [scale] difficulty
+   *   multipliers on ship hull, ships per wave and build-window length
+   */
+  constructor(data, world, scale = {}) {
     this.data = data;
     this.data = data;
     this.world = world;
     this.world = world;
     const w = data.waves ?? {};
     const w = data.waves ?? {};
     this.list = w.list ?? [];
     this.list = w.list ?? [];
-    this.buildWindow = w.buildWindow ?? 25;
+    this.hpMult = scale.hp ?? 1;
+    this.countMult = scale.count ?? 1;
+    const windowMult = scale.window ?? 1;
+    this.buildWindow = (w.buildWindow ?? 25) * windowMult;
     // The opening window is much longer: there is nothing built yet, and the
     // The opening window is much longer: there is nothing built yet, and the
     // first minutes are where a base is actually established.
     // first minutes are where a base is actually established.
-    this.firstWindow = w.firstWindow ?? this.buildWindow;
+    this.firstWindow = (w.firstWindow ?? w.buildWindow ?? 25) * windowMult;
     this.endless = w.endless ?? { after: 10, hpScale: 1.12, countScale: 1.08 };
     this.endless = w.endless ?? { after: 10, hpScale: 1.12, countScale: 1.08 };
 
 
     this.waveIndex = 0;       // how many waves have been launched
     this.waveIndex = 0;       // how many waves have been launched
@@ -41,20 +50,24 @@ export class WaveDirector {
 
 
   /** Composition of wave n (1-based), scaling past the scripted list. */
   /** Composition of wave n (1-based), scaling past the scripted list. */
   compositionFor(n) {
   compositionFor(n) {
+    let comp;
+    let mult = this.countMult;
     if (n <= this.list.length) {
     if (n <= this.list.length) {
-      return this._parse(this.list[n - 1].spawn);
+      comp = this._parse(this.list[n - 1].spawn);
+    } else {
+      // Beyond the script: replay the last entry with growing counts.
+      comp = this._parse(this.list[this.list.length - 1].spawn);
+      mult *= Math.pow(this.endless.countScale ?? 1.08, n - this.list.length);
     }
     }
-    // Beyond the script: replay the last entry with growing counts.
-    const base = this._parse(this.list[this.list.length - 1].spawn);
-    const over = n - this.list.length;
-    const mult = Math.pow(this.endless.countScale ?? 1.08, over);
-    return base.map((e) => ({ type: e.type, count: Math.ceil(e.count * mult) }));
+    if (mult === 1) return comp;
+    // Never below one ship of a listed type, so an easy wave keeps its shape.
+    return comp.map((e) => ({ type: e.type, count: Math.max(1, Math.round(e.count * mult)) }));
   }
   }
 
 
-  /** Extra hit points multiplier applied to ships past the scripted list. */
+  /** Hit point multiplier for wave n: difficulty, then endless scaling. */
   hpScaleFor(n) {
   hpScaleFor(n) {
-    if (n <= this.list.length) return 1;
-    return Math.pow(this.endless.hpScale ?? 1.12, n - this.list.length);
+    if (n <= this.list.length) return this.hpMult;
+    return this.hpMult * Math.pow(this.endless.hpScale ?? 1.12, n - this.list.length);
   }
   }
 
 
   _parse(spawn) {
   _parse(spawn) {
@@ -166,7 +179,7 @@ export class WaveDirector {
     const e = this.world.spawnEnemy(type, Math.cos(a) * r, Math.sin(a) * r);
     const e = this.world.spawnEnemy(type, Math.cos(a) * r, Math.sin(a) * r);
     if (e) {
     if (e) {
       const scale = this.hpScaleFor(this.waveIndex);
       const scale = this.hpScaleFor(this.waveIndex);
-      if (scale > 1) {
+      if (scale !== 1) {
         e.maxHp = Math.round(e.maxHp * scale);
         e.maxHp = Math.round(e.maxHp * scale);
         e.hp = e.maxHp;
         e.hp = e.maxHp;
       }
       }

+ 13 - 0
src/web/Orbital Claim/src/systems/modes/MiningMode.js

@@ -14,6 +14,18 @@ export class MiningMode extends Mode {
     this.name = 'Mining Race';
     this.name = 'Mining Race';
     this.target = cfg.target ?? 6000;
     this.target = cfg.target ?? 6000;
     this.timeLimit = cfg.time ?? 600;
     this.timeLimit = cfg.time ?? 600;
+    // Set by the Game from entities.json → modes.mining.difficulties.
+    this.difficulty = cfg.difficulty ?? 'normal';
+    this.difficultyName = cfg.name ?? 'Normal';
+  }
+
+  /** Normal keeps the plain key, so bests from before difficulties still count. */
+  get recordKey() {
+    return MiningMode.recordKeyFor(this.difficulty);
+  }
+
+  static recordKeyFor(difficulty) {
+    return difficulty === 'normal' ? 'mining' : `mining-${difficulty}`;
   }
   }
 
 
   get remaining() {
   get remaining() {
@@ -44,6 +56,7 @@ export class MiningMode extends Mode {
   summary() {
   summary() {
     const mined = Math.floor(this.world.economy.totalMined);
     const mined = Math.floor(this.world.economy.totalMined);
     return [
     return [
+      ['Difficulty', this.difficultyName],
       ['Extracted', `${mined} / ${this.target}`],
       ['Extracted', `${mined} / ${this.target}`],
       ['Time taken', formatTime(this.elapsed)],
       ['Time taken', formatTime(this.elapsed)],
       ['Waves survived', String(this.world.waves.waveIndex)],
       ['Waves survived', String(this.world.waves.waveIndex)],

+ 5 - 0
src/web/Orbital Claim/src/systems/modes/Mode.js

@@ -25,6 +25,11 @@ export class Mode {
     return this.state !== 'playing';
     return this.state !== 'playing';
   }
   }
 
 
+  /** Where this run's personal best is kept. Difficulties keep their own. */
+  get recordKey() {
+    return this.key;
+  }
+
   update(dt) {
   update(dt) {
     if (this.finished) return;
     if (this.finished) return;
     this.elapsed += dt;
     this.elapsed += dt;

+ 2 - 1
src/web/Orbital Claim/src/ui/PauseMenu.js

@@ -209,6 +209,7 @@ export class PauseMenu {
     ];
     ];
     if (mode.target !== undefined) {
     if (mode.target !== undefined) {
       stats.push(['Mined', `${Math.floor(w.economy.totalMined)} / ${mode.target}`]);
       stats.push(['Mined', `${Math.floor(w.economy.totalMined)} / ${mode.target}`]);
+      stats.push(['Ore in field', Math.floor(w.oreRemaining).toLocaleString()]);
     }
     }
 
 
     return `
     return `
@@ -499,7 +500,7 @@ export class PauseMenu {
         this.confirm({
         this.confirm({
           title: 'Restart this run?', ok: 'Restart', danger: true,
           title: 'Restart this run?', ok: 'Restart', danger: true,
           text: `A fresh ${g.modeName} run starts on a new map. Progress in this one is lost.`,
           text: `A fresh ${g.modeName} run starts on a new map. Progress in this one is lost.`,
-          run: () => g.start(g.mode.key),
+          run: () => g.start(g.mode.key, g.mode.difficulty),
         });
         });
         break;
         break;
       case 'title':
       case 'title':

+ 32 - 18
src/web/Orbital Claim/src/world/Field.js

@@ -15,18 +15,32 @@ import { Asteroid } from '../entities/Asteroid.js';
 export class Field {
 export class Field {
   /**
   /**
    * @param {number} seed
    * @param {number} seed
-   * @param {object} opts { radius, clusters, hubClearing }
+   * @param {object} opts
+   * @param {number} [opts.radius]
+   * @param {number} [opts.clusters] number of outer clusters
+   * @param {number} [opts.hubClearing] empty radius around the start
+   * @param {number} [opts.richness] multiplier on every rock's ore
+   * @param {number} [opts.homeRocks] lean rocks placed just outside the clearing
+   * @param {number} [opts.minOre] the field is topped up with extra clusters
+   *   until it holds at least this much ore in total
    */
    */
   static generate(seed = 1337, opts = {}) {
   static generate(seed = 1337, opts = {}) {
     const rand = rng(seed);
     const rand = rng(seed);
     const radius = opts.radius ?? 1600;
     const radius = opts.radius ?? 1600;
     const clusterCount = opts.clusters ?? 14;
     const clusterCount = opts.clusters ?? 14;
     const clearing = opts.hubClearing ?? 260;
     const clearing = opts.hubClearing ?? 260;
+    const richness = opts.richness ?? 1;
+    const minOre = opts.minOre ?? 0;
 
 
     const asteroids = [];
     const asteroids = [];
     const sprites = ['asteroid-a', 'asteroid-b', 'asteroid-c'];
     const sprites = ['asteroid-a', 'asteroid-b', 'asteroid-c'];
+    let totalOre = 0;
+    const add = (x, y, ore) => {
+      asteroids.push(new Asteroid(x, y, ore, sprites[Math.floor(rand() * sprites.length)]));
+      totalOre += ore;
+    };
 
 
-    for (let c = 0; c < clusterCount; c++) {
+    const addCluster = () => {
       // Bias clusters outward: sqrt gives an even area distribution, and we
       // Bias clusters outward: sqrt gives an even area distribution, and we
       // push past the hub clearing so the start is defensible but poor.
       // push past the hub clearing so the start is defensible but poor.
       const t = 0.25 + 0.75 * Math.sqrt(rand());
       const t = 0.25 + 0.75 * Math.sqrt(rand());
@@ -38,7 +52,7 @@ export class Field {
       const spread = 90 + rand() * 130;
       const spread = 90 + rand() * 130;
       const count = 3 + Math.floor(rand() * 6);
       const count = 3 + Math.floor(rand() * 6);
       // Richness scales with distance from home.
       // Richness scales with distance from home.
-      const richness = 0.45 + 0.55 * (dist / radius);
+      const depth = 0.45 + 0.55 * (dist / radius);
 
 
       for (let i = 0; i < count; i++) {
       for (let i = 0; i < count; i++) {
         const a = rand() * Math.PI * 2;
         const a = rand() * Math.PI * 2;
@@ -46,27 +60,27 @@ export class Field {
         const x = cx + Math.cos(a) * r;
         const x = cx + Math.cos(a) * r;
         const y = cy + Math.sin(a) * r;
         const y = cy + Math.sin(a) * r;
         if (Math.hypot(x, y) < clearing) continue;
         if (Math.hypot(x, y) < clearing) continue;
-
-        const ore = Math.round((900 + rand() * 2700) * richness);
-        const sprite = sprites[Math.floor(rand() * sprites.length)];
-        asteroids.push(new Asteroid(x, y, ore, sprite));
+        add(x, y, Math.round((900 + rand() * 2700) * depth * richness));
       }
       }
-    }
+    };
+
+    for (let c = 0; c < clusterCount; c++) addCluster();
 
 
     // A few lean rocks near home so the opening has something to work.
     // A few lean rocks near home so the opening has something to work.
-    for (let i = 0; i < 7; i++) {
+    const homeRocks = opts.homeRocks ?? 7;
+    for (let i = 0; i < homeRocks; i++) {
       const ang = rand() * Math.PI * 2;
       const ang = rand() * Math.PI * 2;
       const r = clearing + rand() * 170;
       const r = clearing + rand() * 170;
-      asteroids.push(
-        new Asteroid(
-          Math.cos(ang) * r,
-          Math.sin(ang) * r,
-          Math.round(660 + rand() * 780),
-          sprites[Math.floor(rand() * sprites.length)]
-        )
-      );
+      add(Math.cos(ang) * r, Math.sin(ang) * r, Math.round((660 + rand() * 780) * richness));
     }
     }
 
 
-    return { asteroids, radius, seed };
+    // The guarantee: a mode that asks for a quota gets a field that can pay it,
+    // whatever the seed rolled. Extra clusters rather than richer rocks, so a
+    // short field still looks like every other one. The guard only matters for
+    // absurd settings; one cluster is worth well over a thousand ore.
+    let guard = 0;
+    while (totalOre < minOre && guard++ < 200) addCluster();
+
+    return { asteroids, radius, seed, totalOre };
   }
   }
 }
 }

+ 25 - 4
src/web/Orbital Claim/src/world/World.js

@@ -52,7 +52,16 @@ const ENEMY_CLASSES = {
  * never move.
  * never move.
  */
  */
 export class World {
 export class World {
-  constructor(data, seed = 1337) {
+  /**
+   * @param {object} data entities.json
+   * @param {number} seed
+   * @param {object} [opts] per-run tuning, from a mode's difficulty
+   * @param {object} [opts.field] passed to Field.generate (clusters, richness,
+   *   homeRocks, minOre)
+   * @param {number} [opts.startMinerals]
+   * @param {{hp?:number, count?:number, window?:number}} [opts.waves]
+   */
+  constructor(data, seed = 1337, opts = {}) {
     this.data = data;
     this.data = data;
     this.seed = seed;
     this.seed = seed;
 
 
@@ -62,9 +71,11 @@ export class World {
     this.effects = [];
     this.effects = [];
     this.bots = [];        // repair drones, owned by their stations
     this.bots = [];        // repair drones, owned by their stations
 
 
-    const field = Field.generate(seed, { radius: 1600 });
+    const field = Field.generate(seed, { radius: 1600, ...opts.field });
     this.asteroids = field.asteroids;
     this.asteroids = field.asteroids;
     this.fieldRadius = field.radius;
     this.fieldRadius = field.radius;
+    /** Ore the field held when it was generated. */
+    this.fieldOre = field.totalOre;
 
 
     this.asteroidHash = new SpatialHash(160);
     this.asteroidHash = new SpatialHash(160);
     this.asteroidHash.rebuild(this.asteroids);
     this.asteroidHash.rebuild(this.asteroids);
@@ -74,7 +85,10 @@ export class World {
     this.enemyHash = new SpatialHash(128);
     this.enemyHash = new SpatialHash(128);
 
 
     this.grid = new PowerGrid(data.grid?.linkRange ?? 170);
     this.grid = new PowerGrid(data.grid?.linkRange ?? 170);
-    this.economy = new Economy(data.resources?.minerals);
+    this.economy = new Economy({
+      ...data.resources?.minerals,
+      ...(opts.startMinerals != null ? { start: opts.startMinerals } : {}),
+    });
 
 
     this.time = 0;
     this.time = 0;
     // Sandbox: structures are finished the moment they are placed.
     // Sandbox: structures are finished the moment they are placed.
@@ -94,7 +108,14 @@ export class World {
     this.structuresLost = 0;
     this.structuresLost = 0;
 
 
     this._placeStartingBase();
     this._placeStartingBase();
-    this.waves = new WaveDirector(data, this);
+    this.waves = new WaveDirector(data, this, opts.waves);
+  }
+
+  /** Ore still in the rocks, for readouts; not cheap, so not per frame. */
+  get oreRemaining() {
+    let ore = 0;
+    for (const a of this.asteroids) ore += a.ore;
+    return ore;
   }
   }
 
 
   /**
   /**