Claude Claude Sonnet 5 commited on
Commit
34ea8bc
·
unverified ·
1 Parent(s): e735d2f

Tier 1: camera + zoom, fog of war, and a Skiff-countering unit

Browse files

Three independent features, the biggest-leverage items from a
brainstormed improvement list, built in dependency order (fog of
war's reveal effect only means something once you can actually pan
around to see it).

## Camera + zoom (camera.js, new)

The whole 1600x1000 map used to be squeezed into one screen — units
were tiny dots. The canvas is now a fixed-resolution viewport with a
camera (pan via WASD/arrows, zoom via mouse wheel toward the cursor,
clamped to map bounds) instead of a 1:1 map-to-canvas mapping.
render.js draws through a camera transform; input.js's toWorld()
converts screen->world through it too, so selection/commands keep
working exactly as before. Fixed a latent bug while wiring this up:
attachInput() was never cleaning up its event listeners, so every
"Choose another battlefield" replay stacked a fresh full set on the
same canvas/window — added an AbortController-based destroy().

## Fog of war (engine/fog.js, new)

A coarse grid tracks which cells are currently in a player
unit/building's sight radius (recomputed each tick) and which have
ever been seen (permanent). Enemy units/buildings only render and
can only be targeted when the cell they're in is currently visible
— no remembered snapshots, they just stop rendering when vision
moves on. Resource nodes stay always-visible (charted map knowledge
per data.js's flavor, not battlefield intel), which also keeps
gathering completely unaffected. The AI still plays with full
internal knowledge, same as before — only the player's view and
targeting are gated.

## Bastion: a real Skiff counter (engine/entities.js)

A second combat unit produced from the Barracks: slower, short-
ranged, tankier, and costlier than Skiff, with bonus damage
specifically against it (engine/combat.js's bonusVs table) — so
"mass Skiffs" is no longer the only strategy. Renders as a diamond,
a third silhouette next to Worker's circle and Skiff's triangle. The
AI mixes Bastion into its production (roughly 1 in 3) instead of
pure Skiff spam.

15 new tests (camera math already covered by manual/browser
verification; fog grid, Bastion's bonus damage and stat tradeoffs,
AI production mix, and the Barracks producing both unit types are
all covered directly). All 64 tests pass. Manually verified in-
browser: zoom/pan/clamp precision, fog states across
unexplored/scouted/re-fogged, three distinct unit silhouettes, and a
live Bastion vs Skiff fight landing exactly on the expected damage
numbers.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BDmJ8vc9jxc6TUegK9F2YJ

README.md CHANGED
@@ -14,9 +14,13 @@ The original game has no build step and no module system: ~30 script-tag files a
14
 
15
  ## Status
16
 
17
- First playable vertical slice: a 1v1 skirmish against a scripted AI on Ferros Prime (a mining world from `data.js`). Gather ore/crystals/radioactives with Workers, build a Barracks, produce Skiffs, fight, win by destroying the enemy Command Center (or lose yours). No tech tree, no multiple maps, no multiplayer yet — see `engine/` for the sim (fixed-timestep loop, movement, gather, combat, production, AI) and `render.js`/`input.js` for the canvas view and mouse controls.
18
 
19
- Controls: left-drag to select your units, right-click to move/gather/attack depending on what's under the cursor, click a Worker or a completed building for build/produce options in the side panel.
 
 
 
 
20
 
21
  ## Running it
22
 
 
14
 
15
  ## Status
16
 
17
+ A 1v1 skirmish against a scripted AI on one of three charted worlds (Ferros Prime, Korrath, Vesper — picked at the start of each match). Gather ore/crystals/radioactives with Workers, build a Barracks, produce Skiffs and Bastions, fight under fog of war, win by destroying the enemy Command Center (or lose yours). No tech tree, no multiplayer yet — see `engine/` for the sim (fixed-timestep loop, movement + local avoidance, gather, combat, production, fog of war, AI) and `render.js`/`input.js`/`camera.js` for the canvas view, camera, and mouse/keyboard controls.
18
 
19
+ Two combat units with a real counter relationship: Skiff (fast, ranged, cheap) vs Bastion (slow, short-ranged, tanky, bonus damage specifically against Skiffs) — scouting what the enemy is building matters.
20
+
21
+ Controls: left-drag to select your units, right-click to move (ignores enemies) or gather/assist-build/attack depending on what's under the cursor, Shift+right-click for attack-move (engages anything encountered along the way), mouse wheel to zoom, WASD/arrow keys to pan. Click a Worker or a completed building for build/produce options in the side panel.
22
+
23
+ Fog of war hides enemy units and buildings outside your current vision (resource deposits are always shown — they're charted map knowledge, not battlefield intel). The AI plays with full knowledge of the map; only the player's view and targeting are fogged.
24
 
25
  ## Running it
26
 
camera.js ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ Camera: pans and zooms the view over the map instead of squeezing
3
+ the whole map into one screen. Pure view-space math — never reads or
4
+ mutates game state, just converts between screen (CSS pixel, origin
5
+ at the canvas's top-left) and world (map) coordinates.
6
+ ============================================================ */
7
+
8
+ "use strict";
9
+
10
+ export const MIN_ZOOM = 0.6;
11
+ export const MAX_ZOOM = 2.5;
12
+ const PAN_SPEED = 900; // world units/sec of keyboard pan at zoom 1
13
+
14
+ export function createCamera(map) {
15
+ return { x: map.width / 2, y: map.height / 2, zoom: 1 };
16
+ }
17
+
18
+ export function screenToWorld(camera, vw, vh, sx, sy) {
19
+ return {
20
+ x: camera.x + (sx - vw / 2) / camera.zoom,
21
+ y: camera.y + (sy - vh / 2) / camera.zoom,
22
+ };
23
+ }
24
+
25
+ export function worldToScreen(camera, vw, vh, wx, wy) {
26
+ return {
27
+ x: vw / 2 + (wx - camera.x) * camera.zoom,
28
+ y: vh / 2 + (wy - camera.y) * camera.zoom,
29
+ };
30
+ }
31
+
32
+ // Keeps the camera from panning past the map edge into empty space. Once
33
+ // the viewport is wider/taller than the map (zoomed out far enough, or a
34
+ // tiny window), that axis just centers instead of "clamping" to a
35
+ // backwards range.
36
+ export function clampCamera(camera, map, vw, vh) {
37
+ const halfW = vw / (2 * camera.zoom);
38
+ const halfH = vh / (2 * camera.zoom);
39
+ camera.x = map.width <= 2 * halfW ? map.width / 2 : Math.min(Math.max(camera.x, halfW), map.width - halfW);
40
+ camera.y = map.height <= 2 * halfH ? map.height / 2 : Math.min(Math.max(camera.y, halfH), map.height - halfH);
41
+ }
42
+
43
+ // Zooms by `factor` while keeping the world point under (sx, sy) fixed on
44
+ // screen, so scrolling the wheel feels like it's zooming toward the
45
+ // cursor instead of the map drifting out from under it.
46
+ export function zoomAt(camera, map, vw, vh, sx, sy, factor) {
47
+ const before = screenToWorld(camera, vw, vh, sx, sy);
48
+ camera.zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, camera.zoom * factor));
49
+ const after = screenToWorld(camera, vw, vh, sx, sy);
50
+ camera.x += before.x - after.x;
51
+ camera.y += before.y - after.y;
52
+ clampCamera(camera, map, vw, vh);
53
+ }
54
+
55
+ // dx/dy is a direction (not necessarily normalized) — e.g. from held
56
+ // keys — scaled by dt and the current zoom so panning covers the same
57
+ // screen distance per second regardless of zoom level.
58
+ export function panCamera(camera, map, vw, vh, dx, dy, dt) {
59
+ if (dx === 0 && dy === 0) return;
60
+ const len = Math.hypot(dx, dy);
61
+ camera.x += (dx / len) * PAN_SPEED * dt / camera.zoom;
62
+ camera.y += (dy / len) * PAN_SPEED * dt / camera.zoom;
63
+ clampCamera(camera, map, vw, vh);
64
+ }
engine/ai.js CHANGED
@@ -1,9 +1,9 @@
1
  /* ============================================================
2
  Scripted AI opponent: keep workers on the nearest node, keep
3
  population growing, put up a Barracks once it can afford one, then
4
- pump Skiffs and throw them at the player's base once it has a real
5
- force (or the game's dragged on long enough that it should commit
6
- anyway).
7
  ============================================================ */
8
 
9
  "use strict";
@@ -15,8 +15,9 @@ import { playerBuildings, playerUnits } from "./state.js";
15
 
16
  const THINK_INTERVAL = 1.5;
17
  const WORKER_TARGET = 6;
18
- const SKIFF_ATTACK_SIZE = 6;
19
  const ATTACK_TIMEOUT = 150;
 
20
 
21
  export function runAI(state, dt) {
22
  state.aiThink = (state.aiThink || 0) - dt;
@@ -25,7 +26,7 @@ export function runAI(state, dt) {
25
 
26
  const ai = state.players.ai;
27
  const workers = playerUnits(state, "ai").filter(u => u.type === "worker");
28
- const skiffs = playerUnits(state, "ai").filter(u => u.type === "skiff");
29
  const buildings = playerBuildings(state, "ai");
30
  const cc = buildings.find(b => b.type === "command" && !b.constructing);
31
  const barracks = buildings.find(b => b.type === "barracks");
@@ -41,13 +42,16 @@ export function runAI(state, dt) {
41
  }
42
 
43
  if (barracks && !barracks.constructing && barracks.queue.length === 0) {
44
- queueProduction(state, barracks.id, "skiff");
 
 
 
45
  }
46
 
47
- const readyToAttack = skiffs.length >= SKIFF_ATTACK_SIZE || state.time > ATTACK_TIMEOUT;
48
- if (readyToAttack && skiffs.length > 0 && !state.aiAttacked) {
49
  const target = state.map.bases.player;
50
- issueAttackMove(skiffs, target.x, target.y);
51
  state.aiAttacked = true;
52
  }
53
  }
 
1
  /* ============================================================
2
  Scripted AI opponent: keep workers on the nearest node, keep
3
  population growing, put up a Barracks once it can afford one, then
4
+ mix Skiffs and Bastions (roughly 1 Bastion per BASTION_RATIO units)
5
+ and throw the whole army at the player's base once it's big enough
6
+ (or the game's dragged on long enough that it should commit anyway).
7
  ============================================================ */
8
 
9
  "use strict";
 
15
 
16
  const THINK_INTERVAL = 1.5;
17
  const WORKER_TARGET = 6;
18
+ const ARMY_ATTACK_SIZE = 6;
19
  const ATTACK_TIMEOUT = 150;
20
+ const BASTION_RATIO = 3; // every 3rd unit built is a Bastion instead of a Skiff
21
 
22
  export function runAI(state, dt) {
23
  state.aiThink = (state.aiThink || 0) - dt;
 
26
 
27
  const ai = state.players.ai;
28
  const workers = playerUnits(state, "ai").filter(u => u.type === "worker");
29
+ const army = playerUnits(state, "ai").filter(u => u.type === "skiff" || u.type === "bastion");
30
  const buildings = playerBuildings(state, "ai");
31
  const cc = buildings.find(b => b.type === "command" && !b.constructing);
32
  const barracks = buildings.find(b => b.type === "barracks");
 
42
  }
43
 
44
  if (barracks && !barracks.constructing && barracks.queue.length === 0) {
45
+ const nextIsBastion = (state.aiUnitsBuilt || 0) % BASTION_RATIO === BASTION_RATIO - 1;
46
+ if (queueProduction(state, barracks.id, nextIsBastion ? "bastion" : "skiff")) {
47
+ state.aiUnitsBuilt = (state.aiUnitsBuilt || 0) + 1;
48
+ }
49
  }
50
 
51
+ const readyToAttack = army.length >= ARMY_ATTACK_SIZE || state.time > ATTACK_TIMEOUT;
52
+ if (readyToAttack && army.length > 0 && !state.aiAttacked) {
53
  const target = state.map.bases.player;
54
+ issueAttackMove(army, target.x, target.y);
55
  state.aiAttacked = true;
56
  }
57
  }
engine/combat.js CHANGED
@@ -1,11 +1,14 @@
1
  /* ============================================================
2
- Combat-role units (skiffs): auto-acquire the nearest enemy within
3
- aggro range, close to weapon range, and fire on cooldown. An explicit
4
- 'attack' order pins the target; 'attack-move' auto-engages anything
5
- encountered en route to its destination.
 
 
 
6
 
7
  A plain 'move' order is the deliberate exception: it's how a player
8
- pulls a skiff OUT of a fight or redirects it past a threat, so it
9
  skips auto-acquire entirely rather than getting silently overridden
10
  the moment an enemy wanders into aggro range.
11
  ============================================================ */
@@ -37,7 +40,7 @@ export function updateCombat(state, unit, dt) {
37
  if (dist > def.range) {
38
  stepToward(state, unit, target.x, target.y, def.speed, dt);
39
  } else if (unit.attackTimer <= 0) {
40
- target.hp -= def.attack;
41
  unit.attackTimer = def.cooldown;
42
  if (target.hp <= 0) {
43
  removeEntity(state, target.id);
@@ -54,6 +57,11 @@ export function updateCombat(state, unit, dt) {
54
  }
55
  }
56
 
 
 
 
 
 
57
  function isAlive(state, id) {
58
  const e = getEntity(state, id);
59
  return !!e && e.hp > 0;
 
1
  /* ============================================================
2
+ Combat-role units (Skiff, Bastion): auto-acquire the nearest enemy
3
+ within aggro range, close to weapon range, and fire on cooldown. An
4
+ explicit 'attack' order pins the target; 'attack-move' auto-engages
5
+ anything encountered en route to its destination. A unit type's
6
+ bonusVs table (entities.js) adds extra damage against a specific
7
+ target type — Bastion's slow, short-range bulk is built to punch
8
+ through Skiff hulls specifically.
9
 
10
  A plain 'move' order is the deliberate exception: it's how a player
11
+ pulls a unit OUT of a fight or redirects it past a threat, so it
12
  skips auto-acquire entirely rather than getting silently overridden
13
  the moment an enemy wanders into aggro range.
14
  ============================================================ */
 
40
  if (dist > def.range) {
41
  stepToward(state, unit, target.x, target.y, def.speed, dt);
42
  } else if (unit.attackTimer <= 0) {
43
+ target.hp -= attackDamage(def, target);
44
  unit.attackTimer = def.cooldown;
45
  if (target.hp <= 0) {
46
  removeEntity(state, target.id);
 
57
  }
58
  }
59
 
60
+ function attackDamage(def, target) {
61
+ const bonus = def.bonusVs && def.bonusVs[target.type] || 0;
62
+ return def.attack + bonus;
63
+ }
64
+
65
  function isAlive(state, id) {
66
  const e = getEntity(state, id);
67
  return !!e && e.hp > 0;
engine/entities.js CHANGED
@@ -13,11 +13,13 @@ export const BUILDINGS = {
13
  cost: {}, buildTime: 0, // pre-placed at game start, never queued
14
  produces: ["worker"],
15
  isCommandCenter: true,
 
16
  },
17
  barracks: {
18
  id: "barracks", name: "Barracks", hp: 500, radius: 20,
19
  cost: { ore: 150 }, buildTime: 20,
20
- produces: ["skiff"],
 
21
  },
22
  };
23
 
@@ -26,6 +28,7 @@ export const UNITS = {
26
  id: "worker", name: "Worker", hp: 40, radius: 6, speed: 60,
27
  cost: { ore: 50 }, buildTime: 8,
28
  role: "worker", gatherRate: 10, cargoCap: 10,
 
29
  },
30
  skiff: {
31
  id: "skiff", name: "Skiff", hp: 80, radius: 7, speed: 90,
@@ -33,6 +36,13 @@ export const UNITS = {
33
  role: "combat", attack: 12, range: 40, cooldown: 1,
34
  sight: 160, aggroRange: 120,
35
  },
 
 
 
 
 
 
 
36
  };
37
 
38
  export function canAfford(resources, cost) {
 
13
  cost: {}, buildTime: 0, // pre-placed at game start, never queued
14
  produces: ["worker"],
15
  isCommandCenter: true,
16
+ sight: 220,
17
  },
18
  barracks: {
19
  id: "barracks", name: "Barracks", hp: 500, radius: 20,
20
  cost: { ore: 150 }, buildTime: 20,
21
+ produces: ["skiff", "bastion"],
22
+ sight: 150,
23
  },
24
  };
25
 
 
28
  id: "worker", name: "Worker", hp: 40, radius: 6, speed: 60,
29
  cost: { ore: 50 }, buildTime: 8,
30
  role: "worker", gatherRate: 10, cargoCap: 10,
31
+ sight: 110,
32
  },
33
  skiff: {
34
  id: "skiff", name: "Skiff", hp: 80, radius: 7, speed: 90,
 
36
  role: "combat", attack: 12, range: 40, cooldown: 1,
37
  sight: 160, aggroRange: 120,
38
  },
39
+ bastion: {
40
+ id: "bastion", name: "Bastion", hp: 160, radius: 9, speed: 60,
41
+ cost: { ore: 160 }, buildTime: 18,
42
+ role: "combat", attack: 10, range: 18, cooldown: 1.2,
43
+ sight: 130, aggroRange: 100,
44
+ bonusVs: { skiff: 14 }, // heavy armor built to tear through skiff hulls up close
45
+ },
46
  };
47
 
48
  export function canAfford(resources, cost) {
engine/fog.js ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ Fog of war for the player's view: a coarse grid tracks which cells
3
+ are currently in sight of a player unit/building (recomputed fresh
4
+ every tick) and which have ever been seen (permanent, once set).
5
+
6
+ Deliberately scoped to units/buildings only — resource nodes stay
7
+ visible regardless (the charted deposits from data.js are treated as
8
+ known map knowledge, not battlefield intel), and there's no
9
+ "remembered snapshot" of enemy positions once they leave vision, they
10
+ simply stop rendering. The AI plays with full knowledge of the map
11
+ internally (it always has); this only ever gates what the player sees
12
+ and can target.
13
+ ============================================================ */
14
+
15
+ "use strict";
16
+
17
+ import { UNITS, BUILDINGS } from "./entities.js";
18
+
19
+ export const FOG_CELL_SIZE = 40;
20
+
21
+ export function createFog(map) {
22
+ const cols = Math.ceil(map.width / FOG_CELL_SIZE);
23
+ const rows = Math.ceil(map.height / FOG_CELL_SIZE);
24
+ return { cols, rows, explored: new Uint8Array(cols * rows), visible: new Uint8Array(cols * rows) };
25
+ }
26
+
27
+ function cellOf(fog, wx, wy) {
28
+ return { cx: Math.floor(wx / FOG_CELL_SIZE), cy: Math.floor(wy / FOG_CELL_SIZE) };
29
+ }
30
+
31
+ function inBounds(fog, cx, cy) {
32
+ return cx >= 0 && cy >= 0 && cx < fog.cols && cy < fog.rows;
33
+ }
34
+
35
+ export function isVisibleAt(fog, wx, wy) {
36
+ const { cx, cy } = cellOf(fog, wx, wy);
37
+ return inBounds(fog, cx, cy) && fog.visible[cy * fog.cols + cx] === 1;
38
+ }
39
+
40
+ export function isExploredAt(fog, wx, wy) {
41
+ const { cx, cy } = cellOf(fog, wx, wy);
42
+ return inBounds(fog, cx, cy) && fog.explored[cy * fog.cols + cx] === 1;
43
+ }
44
+
45
+ function reveal(fog, x, y, sight) {
46
+ const { cx, cy } = cellOf(fog, x, y);
47
+ const reach = Math.ceil(sight / FOG_CELL_SIZE);
48
+ for (let gy = Math.max(0, cy - reach); gy <= Math.min(fog.rows - 1, cy + reach); gy++) {
49
+ for (let gx = Math.max(0, cx - reach); gx <= Math.min(fog.cols - 1, cx + reach); gx++) {
50
+ const cellCx = gx * FOG_CELL_SIZE + FOG_CELL_SIZE / 2;
51
+ const cellCy = gy * FOG_CELL_SIZE + FOG_CELL_SIZE / 2;
52
+ if (Math.hypot(cellCx - x, cellCy - y) > sight) continue;
53
+ const idx = gy * fog.cols + gx;
54
+ fog.visible[idx] = 1;
55
+ fog.explored[idx] = 1;
56
+ }
57
+ }
58
+ }
59
+
60
+ // Recomputes `visible` from scratch each call (cheap at this grid
61
+ // resolution) and folds newly-seen cells permanently into `explored`.
62
+ export function updateFog(state, fog, owner) {
63
+ fog.visible.fill(0);
64
+ for (const u of state.units.values()) {
65
+ if (u.owner === owner) reveal(fog, u.x, u.y, UNITS[u.type].sight);
66
+ }
67
+ for (const b of state.buildings.values()) {
68
+ if (b.owner === owner) reveal(fog, b.x, b.y, BUILDINGS[b.type].sight);
69
+ }
70
+ }
engine/sim.js CHANGED
@@ -11,6 +11,7 @@ import { updateGather } from "./gather.js";
11
  import { updateCombat } from "./combat.js";
12
  import { updateBuildingConstruction, updateProductionQueue, BUILD_REACH } from "./production.js";
13
  import { applySeparation } from "./separation.js";
 
14
  import { UNITS } from "./entities.js";
15
  import { checkWinCondition } from "./victory.js";
16
  import { runAI } from "./ai.js";
@@ -22,6 +23,7 @@ export function tick(state, dt) {
22
 
23
  for (const unit of state.units.values()) updateUnit(state, unit, dt);
24
  applySeparation(state, dt);
 
25
  for (const building of state.buildings.values()) {
26
  updateBuildingConstruction(state, building, dt);
27
  updateProductionQueue(state, building, dt);
 
11
  import { updateCombat } from "./combat.js";
12
  import { updateBuildingConstruction, updateProductionQueue, BUILD_REACH } from "./production.js";
13
  import { applySeparation } from "./separation.js";
14
+ import { updateFog } from "./fog.js";
15
  import { UNITS } from "./entities.js";
16
  import { checkWinCondition } from "./victory.js";
17
  import { runAI } from "./ai.js";
 
23
 
24
  for (const unit of state.units.values()) updateUnit(state, unit, dt);
25
  applySeparation(state, dt);
26
+ updateFog(state, state.fog, "player");
27
  for (const building of state.buildings.values()) {
28
  updateBuildingConstruction(state, building, dt);
29
  updateProductionQueue(state, building, dt);
engine/state.js CHANGED
@@ -8,6 +8,7 @@
8
 
9
  import { generateMap } from "./map.js";
10
  import { BUILDINGS, UNITS } from "./entities.js";
 
11
 
12
  let nextEntityId = 1;
13
  function newId(prefix) { return `${prefix}${nextEntityId++}`; }
@@ -51,10 +52,12 @@ export function createGameState(opts = {}) {
51
  units: new Map(),
52
  buildings: new Map(),
53
  selection: [], // unit/building ids currently selected by the human player
 
54
  };
55
 
56
  seedPlayer(state, "player", map.bases.player);
57
  seedPlayer(state, "ai", map.bases.ai);
 
58
 
59
  return state;
60
  }
 
8
 
9
  import { generateMap } from "./map.js";
10
  import { BUILDINGS, UNITS } from "./entities.js";
11
+ import { createFog, updateFog } from "./fog.js";
12
 
13
  let nextEntityId = 1;
14
  function newId(prefix) { return `${prefix}${nextEntityId++}`; }
 
52
  units: new Map(),
53
  buildings: new Map(),
54
  selection: [], // unit/building ids currently selected by the human player
55
+ fog: createFog(map), // the player's fog of war — see engine/fog.js
56
  };
57
 
58
  seedPlayer(state, "player", map.bases.player);
59
  seedPlayer(state, "ai", map.bases.ai);
60
+ updateFog(state, state.fog, "player"); // so the starting base's vision is correct before the first render
61
 
62
  return state;
63
  }
input.js CHANGED
@@ -1,37 +1,55 @@
1
  /* ============================================================
2
- Mouse input: left-drag to box-select the player's own units, right-
3
- click to issue a context-sensitive order (attack an enemy, gather a
4
- node, or just move), and a build-placement mode the HUD arms via
5
- startBuild().
 
6
  ============================================================ */
7
 
8
  "use strict";
9
 
10
- import { MAP_WIDTH, MAP_HEIGHT } from "./engine/map.js";
11
  import { issueMove, issueGather, issueAttack, issueAttackMove, issueBuild, issueAssistBuild } from "./engine/commands.js";
12
  import { UNITS } from "./engine/entities.js";
 
 
13
 
14
  const CLICK_THRESHOLD = 4;
15
  const UNIT_PICK_RADIUS = 10;
16
  const NODE_PICK_RADIUS = 14;
 
 
 
 
 
 
 
17
 
18
  export function attachInput(canvas, state, onChange) {
 
 
 
 
 
19
  let dragBox = null;
20
  let buildMode = null;
21
 
 
 
 
 
22
  function toWorld(clientX, clientY) {
23
  const rect = canvas.getBoundingClientRect();
24
- return {
25
- x: ((clientX - rect.left) / rect.width) * MAP_WIDTH,
26
- y: ((clientY - rect.top) / rect.height) * MAP_HEIGHT,
27
- };
28
  }
29
 
30
  function entityAt(x, y) {
31
  for (const u of state.units.values()) {
 
32
  if (Math.hypot(u.x - x, u.y - y) <= UNIT_PICK_RADIUS) return u;
33
  }
34
  for (const b of state.buildings.values()) {
 
35
  if (Math.abs(b.x - x) <= b.radius && Math.abs(b.y - y) <= b.radius) return b;
36
  }
37
  return null;
@@ -46,14 +64,14 @@ export function attachInput(canvas, state, onChange) {
46
  const p = toWorld(e.clientX, e.clientY);
47
  if (buildMode) { placeBuildingAt(p); return; }
48
  dragBox = { x1: p.x, y1: p.y, x2: p.x, y2: p.y };
49
- });
50
 
51
  canvas.addEventListener("mousemove", e => {
52
  if (!dragBox) return;
53
  const p = toWorld(e.clientX, e.clientY);
54
  dragBox.x2 = p.x;
55
  dragBox.y2 = p.y;
56
- });
57
 
58
  window.addEventListener("mouseup", e => {
59
  if (e.button !== 0 || !dragBox) return;
@@ -71,7 +89,7 @@ export function attachInput(canvas, state, onChange) {
71
  .map(u => u.id);
72
  }
73
  onChange();
74
- });
75
 
76
  canvas.addEventListener("contextmenu", e => {
77
  e.preventDefault();
@@ -113,7 +131,17 @@ export function attachInput(canvas, state, onChange) {
113
  } else {
114
  issueMove(selected, p.x, p.y);
115
  }
116
- });
 
 
 
 
 
 
 
 
 
 
117
 
118
  function placeBuildingAt(p) {
119
  const buildingType = buildMode.buildingType;
@@ -127,5 +155,20 @@ export function attachInput(canvas, state, onChange) {
127
  getDragBox: () => dragBox,
128
  startBuild(buildingType) { buildMode = { buildingType }; },
129
  get building() { return buildMode; },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  };
131
  }
 
1
  /* ============================================================
2
+ Mouse + keyboard input: left-drag to box-select the player's own
3
+ units, right-click to issue a context-sensitive order (attack an
4
+ enemy, gather a node, or just move), a build-placement mode the HUD
5
+ arms via startBuild(), and camera control (wheel to zoom, WASD/arrows
6
+ to pan).
7
  ============================================================ */
8
 
9
  "use strict";
10
 
 
11
  import { issueMove, issueGather, issueAttack, issueAttackMove, issueBuild, issueAssistBuild } from "./engine/commands.js";
12
  import { UNITS } from "./engine/entities.js";
13
+ import { isVisibleAt } from "./engine/fog.js";
14
+ import { createCamera, screenToWorld, zoomAt, panCamera } from "./camera.js";
15
 
16
  const CLICK_THRESHOLD = 4;
17
  const UNIT_PICK_RADIUS = 10;
18
  const NODE_PICK_RADIUS = 14;
19
+ const ZOOM_STEP = 1.12;
20
+ const PAN_KEYS = {
21
+ arrowleft: [-1, 0], a: [-1, 0],
22
+ arrowright: [1, 0], d: [1, 0],
23
+ arrowup: [0, -1], w: [0, -1],
24
+ arrowdown: [0, 1], s: [0, 1],
25
+ };
26
 
27
  export function attachInput(canvas, state, onChange) {
28
+ const controller = new AbortController();
29
+ const { signal } = controller;
30
+ const camera = createCamera(state.map);
31
+ const heldKeys = new Set();
32
+
33
  let dragBox = null;
34
  let buildMode = null;
35
 
36
+ function viewport() {
37
+ return { vw: canvas.clientWidth, vh: canvas.clientHeight };
38
+ }
39
+
40
  function toWorld(clientX, clientY) {
41
  const rect = canvas.getBoundingClientRect();
42
+ const { vw, vh } = viewport();
43
+ return screenToWorld(camera, vw, vh, clientX - rect.left, clientY - rect.top);
 
 
44
  }
45
 
46
  function entityAt(x, y) {
47
  for (const u of state.units.values()) {
48
+ if (u.owner !== "player" && !isVisibleAt(state.fog, u.x, u.y)) continue;
49
  if (Math.hypot(u.x - x, u.y - y) <= UNIT_PICK_RADIUS) return u;
50
  }
51
  for (const b of state.buildings.values()) {
52
+ if (b.owner !== "player" && !isVisibleAt(state.fog, b.x, b.y)) continue;
53
  if (Math.abs(b.x - x) <= b.radius && Math.abs(b.y - y) <= b.radius) return b;
54
  }
55
  return null;
 
64
  const p = toWorld(e.clientX, e.clientY);
65
  if (buildMode) { placeBuildingAt(p); return; }
66
  dragBox = { x1: p.x, y1: p.y, x2: p.x, y2: p.y };
67
+ }, { signal });
68
 
69
  canvas.addEventListener("mousemove", e => {
70
  if (!dragBox) return;
71
  const p = toWorld(e.clientX, e.clientY);
72
  dragBox.x2 = p.x;
73
  dragBox.y2 = p.y;
74
+ }, { signal });
75
 
76
  window.addEventListener("mouseup", e => {
77
  if (e.button !== 0 || !dragBox) return;
 
89
  .map(u => u.id);
90
  }
91
  onChange();
92
+ }, { signal });
93
 
94
  canvas.addEventListener("contextmenu", e => {
95
  e.preventDefault();
 
131
  } else {
132
  issueMove(selected, p.x, p.y);
133
  }
134
+ }, { signal });
135
+
136
+ canvas.addEventListener("wheel", e => {
137
+ e.preventDefault();
138
+ const rect = canvas.getBoundingClientRect();
139
+ const { vw, vh } = viewport();
140
+ zoomAt(camera, state.map, vw, vh, e.clientX - rect.left, e.clientY - rect.top, e.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP);
141
+ }, { signal, passive: false });
142
+
143
+ window.addEventListener("keydown", e => heldKeys.add(e.key.toLowerCase()), { signal });
144
+ window.addEventListener("keyup", e => heldKeys.delete(e.key.toLowerCase()), { signal });
145
 
146
  function placeBuildingAt(p) {
147
  const buildingType = buildMode.buildingType;
 
155
  getDragBox: () => dragBox,
156
  startBuild(buildingType) { buildMode = { buildingType }; },
157
  get building() { return buildMode; },
158
+ getCamera: () => camera,
159
+ tickCamera(dt) {
160
+ let dx = 0, dy = 0;
161
+ for (const key of heldKeys) {
162
+ const dir = PAN_KEYS[key];
163
+ if (dir) { dx += dir[0]; dy += dir[1]; }
164
+ }
165
+ const { vw, vh } = viewport();
166
+ panCamera(camera, state.map, vw, vh, dx, dy, dt);
167
+ },
168
+ // Removes every listener this call added — without this, starting a
169
+ // new game (map picker -> startGame again) would stack a second,
170
+ // third, ... full set of handlers on the same canvas/window, each
171
+ // reacting to one real click with a growing pile of stale ones.
172
+ destroy() { controller.abort(); },
173
  };
174
  }
main.js CHANGED
@@ -11,7 +11,6 @@ import { createLoop } from "./engine/loop.js";
11
  import { tick } from "./engine/sim.js";
12
  import { queueProduction } from "./engine/production.js";
13
  import { BUILDINGS, UNITS } from "./engine/entities.js";
14
- import { MAP_WIDTH, MAP_HEIGHT } from "./engine/map.js";
15
  import { PLANETS } from "./data.js";
16
  import { drawFrame } from "./render.js";
17
  import { attachInput } from "./input.js";
@@ -28,8 +27,8 @@ const mapSelectEl = document.getElementById("mapSelect");
28
 
29
  function resizeCanvas() {
30
  const dpr = window.devicePixelRatio || 1;
31
- canvas.width = MAP_WIDTH * dpr;
32
- canvas.height = MAP_HEIGHT * dpr;
33
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
34
  }
35
  window.addEventListener("resize", resizeCanvas);
@@ -63,6 +62,7 @@ function renderMapSelect() {
63
 
64
  function startGame(planetId) {
65
  if (loop) loop.stop();
 
66
  gameOverEl.classList.add("hidden");
67
 
68
  state = createGameState({ planetId });
@@ -70,12 +70,16 @@ function startGame(planetId) {
70
  announced = false;
71
  lastHud = 0;
72
  lastPanelSignature = null;
 
73
 
74
  loop = createLoop({
75
  update: dt => tick(state, dt),
76
  render: () => {
77
- drawFrame(ctx, state, input.getDragBox());
78
  const now = performance.now();
 
 
 
 
79
  if (now - lastHud > 150) { lastHud = now; renderHUD(); }
80
  if (state.over && !announced) { announced = true; loop.stop(); showGameOver(state.winner); }
81
  },
@@ -154,6 +158,7 @@ function rebuildSelectionPanel(sel) {
154
  const barracks = sel.find(e => e.kind === "building" && e.type === "barracks" && !e.constructing);
155
  if (barracks) {
156
  panelEl.appendChild(makeButton(`Produce Skiff (${UNITS.skiff.cost.ore} ore)`, () => queueProduction(state, barracks.id, "skiff")));
 
157
  }
158
 
159
  const worker = sel.find(e => e.kind === "unit" && e.type === "worker");
 
11
  import { tick } from "./engine/sim.js";
12
  import { queueProduction } from "./engine/production.js";
13
  import { BUILDINGS, UNITS } from "./engine/entities.js";
 
14
  import { PLANETS } from "./data.js";
15
  import { drawFrame } from "./render.js";
16
  import { attachInput } from "./input.js";
 
27
 
28
  function resizeCanvas() {
29
  const dpr = window.devicePixelRatio || 1;
30
+ canvas.width = canvas.clientWidth * dpr;
31
+ canvas.height = canvas.clientHeight * dpr;
32
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
33
  }
34
  window.addEventListener("resize", resizeCanvas);
 
62
 
63
  function startGame(planetId) {
64
  if (loop) loop.stop();
65
+ if (input) input.destroy();
66
  gameOverEl.classList.add("hidden");
67
 
68
  state = createGameState({ planetId });
 
70
  announced = false;
71
  lastHud = 0;
72
  lastPanelSignature = null;
73
+ let lastFrame = performance.now();
74
 
75
  loop = createLoop({
76
  update: dt => tick(state, dt),
77
  render: () => {
 
78
  const now = performance.now();
79
+ input.tickCamera((now - lastFrame) / 1000);
80
+ lastFrame = now;
81
+
82
+ drawFrame(ctx, state, input.getCamera(), canvas.clientWidth, canvas.clientHeight, input.getDragBox());
83
  if (now - lastHud > 150) { lastHud = now; renderHUD(); }
84
  if (state.over && !announced) { announced = true; loop.stop(); showGameOver(state.winner); }
85
  },
 
158
  const barracks = sel.find(e => e.kind === "building" && e.type === "barracks" && !e.constructing);
159
  if (barracks) {
160
  panelEl.appendChild(makeButton(`Produce Skiff (${UNITS.skiff.cost.ore} ore)`, () => queueProduction(state, barracks.id, "skiff")));
161
+ panelEl.appendChild(makeButton(`Produce Bastion (${UNITS.bastion.cost.ore} ore)`, () => queueProduction(state, barracks.id, "bastion")));
162
  }
163
 
164
  const worker = sel.find(e => e.kind === "unit" && e.type === "worker");
render.js CHANGED
@@ -1,28 +1,58 @@
1
  /* ============================================================
2
  Canvas rendering. Pure read of state — never mutates it. Assumes the
3
- caller already set up a device-pixel-ratio transform so drawing here
4
- happens in plain world coordinates (0..map.width, 0..map.height).
 
 
5
  ============================================================ */
6
 
7
  "use strict";
8
 
9
  import { COM } from "./data.js";
10
  import { UNITS } from "./engine/entities.js";
 
11
 
12
  // Facing angle per unit id, inferred frame-to-frame from movement — pure
13
  // render-side bookkeeping, never read by the sim.
14
  const facing = new Map();
15
 
16
- export function drawFrame(ctx, state, dragBox) {
17
- const { width, height } = state.map;
18
  ctx.fillStyle = "#05070f";
19
- ctx.fillRect(0, 0, width, height);
20
 
 
 
 
 
 
 
 
 
21
  drawNodes(ctx, state);
22
  drawBuildings(ctx, state);
23
  drawUnits(ctx, state);
24
  drawSelectionRings(ctx, state);
25
  if (dragBox) drawDragBox(ctx, dragBox);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  }
27
 
28
  function drawNodes(ctx, state) {
@@ -44,6 +74,7 @@ function drawNodes(ctx, state) {
44
 
45
  function drawBuildings(ctx, state) {
46
  for (const b of state.buildings.values()) {
 
47
  const color = state.players[b.owner].color;
48
  ctx.globalAlpha = b.constructing ? 0.5 : 1;
49
  ctx.fillStyle = color;
@@ -58,6 +89,7 @@ function drawBuildings(ctx, state) {
58
 
59
  function drawUnits(ctx, state) {
60
  for (const u of state.units.values()) {
 
61
  const def = UNITS[u.type];
62
  const color = state.players[u.owner].color;
63
  ctx.fillStyle = color;
@@ -69,7 +101,9 @@ function drawUnits(ctx, state) {
69
  ctx.strokeStyle = "#dce6ff";
70
  ctx.lineWidth = 1.5;
71
 
72
- if (def.role === "combat") {
 
 
73
  drawTriangle(ctx, u, def.radius * 2);
74
  } else {
75
  ctx.beginPath();
@@ -112,6 +146,20 @@ function drawTriangle(ctx, unit, r) {
112
  ctx.stroke();
113
  }
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  function drawHealthBar(ctx, cx, y, w, hp, maxHp) {
116
  if (hp >= maxHp) return;
117
  const pct = Math.max(0, hp / maxHp);
 
1
  /* ============================================================
2
  Canvas rendering. Pure read of state — never mutates it. Assumes the
3
+ caller already set up a device-pixel-ratio transform; drawFrame lays
4
+ the camera transform on top of that, so every draw* helper below just
5
+ works in plain world coordinates (0..map.width, 0..map.height) and
6
+ never has to know about the viewport or camera itself.
7
  ============================================================ */
8
 
9
  "use strict";
10
 
11
  import { COM } from "./data.js";
12
  import { UNITS } from "./engine/entities.js";
13
+ import { isVisibleAt, FOG_CELL_SIZE } from "./engine/fog.js";
14
 
15
  // Facing angle per unit id, inferred frame-to-frame from movement — pure
16
  // render-side bookkeeping, never read by the sim.
17
  const facing = new Map();
18
 
19
+ export function drawFrame(ctx, state, camera, viewportW, viewportH, dragBox) {
20
+ ctx.save();
21
  ctx.fillStyle = "#05070f";
22
+ ctx.fillRect(0, 0, viewportW, viewportH);
23
 
24
+ ctx.translate(viewportW / 2, viewportH / 2);
25
+ ctx.scale(camera.zoom, camera.zoom);
26
+ ctx.translate(-camera.x, -camera.y);
27
+
28
+ drawFogBase(ctx, state);
29
+ // Resource deposits are charted map knowledge (see data.js), not
30
+ // battlefield intel — they render at full visibility regardless of
31
+ // fog, on top of the dimmed backdrop.
32
  drawNodes(ctx, state);
33
  drawBuildings(ctx, state);
34
  drawUnits(ctx, state);
35
  drawSelectionRings(ctx, state);
36
  if (dragBox) drawDragBox(ctx, dragBox);
37
+
38
+ ctx.restore();
39
+ }
40
+
41
+ // Unexplored cells go solid black; explored-but-not-currently-visible
42
+ // cells get a dimming overlay so the player can see where they've
43
+ // scouted before without it looking fully lit. Currently-visible cells
44
+ // get nothing — the world underneath already reads at full brightness.
45
+ function drawFogBase(ctx, state) {
46
+ const fog = state.fog;
47
+ if (!fog) return;
48
+ for (let gy = 0; gy < fog.rows; gy++) {
49
+ for (let gx = 0; gx < fog.cols; gx++) {
50
+ const idx = gy * fog.cols + gx;
51
+ if (fog.visible[idx]) continue;
52
+ ctx.fillStyle = fog.explored[idx] ? "rgba(5, 7, 15, 0.55)" : "#05070f";
53
+ ctx.fillRect(gx * FOG_CELL_SIZE, gy * FOG_CELL_SIZE, FOG_CELL_SIZE, FOG_CELL_SIZE);
54
+ }
55
+ }
56
  }
57
 
58
  function drawNodes(ctx, state) {
 
74
 
75
  function drawBuildings(ctx, state) {
76
  for (const b of state.buildings.values()) {
77
+ if (b.owner !== "player" && !isVisibleAt(state.fog, b.x, b.y)) continue;
78
  const color = state.players[b.owner].color;
79
  ctx.globalAlpha = b.constructing ? 0.5 : 1;
80
  ctx.fillStyle = color;
 
89
 
90
  function drawUnits(ctx, state) {
91
  for (const u of state.units.values()) {
92
+ if (u.owner !== "player" && !isVisibleAt(state.fog, u.x, u.y)) continue;
93
  const def = UNITS[u.type];
94
  const color = state.players[u.owner].color;
95
  ctx.fillStyle = color;
 
101
  ctx.strokeStyle = "#dce6ff";
102
  ctx.lineWidth = 1.5;
103
 
104
+ if (u.type === "bastion") {
105
+ drawDiamond(ctx, u.x, u.y, def.radius * 1.7);
106
+ } else if (def.role === "combat") {
107
  drawTriangle(ctx, u, def.radius * 2);
108
  } else {
109
  ctx.beginPath();
 
146
  ctx.stroke();
147
  }
148
 
149
+ // Bastion draws as a diamond — a third silhouette next to Worker's circle
150
+ // and Skiff's triangle, so a mixed army reads at a glance instead of
151
+ // needing color/size alone to tell a tanky melee unit from a skirmisher.
152
+ function drawDiamond(ctx, cx, cy, r) {
153
+ ctx.beginPath();
154
+ ctx.moveTo(cx, cy - r);
155
+ ctx.lineTo(cx + r, cy);
156
+ ctx.lineTo(cx, cy + r);
157
+ ctx.lineTo(cx - r, cy);
158
+ ctx.closePath();
159
+ ctx.fill();
160
+ ctx.stroke();
161
+ }
162
+
163
  function drawHealthBar(ctx, cx, y, w, hp, maxHp) {
164
  if (hp >= maxHp) return;
165
  const pct = Math.max(0, hp / maxHp);
style.css CHANGED
@@ -84,9 +84,6 @@ html, body {
84
  #field {
85
  width: 100%;
86
  height: 100%;
87
- max-width: 100%;
88
- max-height: 100%;
89
- aspect-ratio: 1600 / 1000;
90
  border: 1px solid var(--border);
91
  border-radius: 6px;
92
  cursor: crosshair;
 
84
  #field {
85
  width: 100%;
86
  height: 100%;
 
 
 
87
  border: 1px solid var(--border);
88
  border-radius: 6px;
89
  cursor: crosshair;
test/ai.test.js ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createGameState, makeBuilding, makeUnit } from "../engine/state.js";
4
+ import { runAI } from "../engine/ai.js";
5
+
6
+ const THINK_INTERVAL = 1.5; // must match ai.js's own THINK_INTERVAL to force a fresh think cycle each call
7
+
8
+ test("the AI mixes in a Bastion every 3rd unit instead of pure Skiff spam", () => {
9
+ const state = createGameState({ planetId: "ferros" });
10
+ const barracks = makeBuilding("barracks", "ai", state.map.bases.ai.x, state.map.bases.ai.y - 100);
11
+ state.buildings.set(barracks.id, barracks);
12
+ state.players.ai.resources.ore = 100000;
13
+
14
+ const builtTypes = [];
15
+ for (let i = 0; i < 9; i++) {
16
+ runAI(state, THINK_INTERVAL);
17
+ if (barracks.queue.length) {
18
+ builtTypes.push(barracks.queue[barracks.queue.length - 1].unitType);
19
+ barracks.queue.length = 0; // clear so the next think cycle queues again immediately
20
+ }
21
+ }
22
+
23
+ assert.equal(builtTypes.length, 9, "every think cycle should have queued something with ample ore");
24
+ assert.deepEqual(builtTypes, ["skiff", "skiff", "bastion", "skiff", "skiff", "bastion", "skiff", "skiff", "bastion"]);
25
+ });
26
+
27
+ test("the AI's attack wave includes Bastions, not just Skiffs", () => {
28
+ const state = createGameState({ planetId: "ferros" });
29
+ state.time = 200; // past ATTACK_TIMEOUT, so it commits regardless of army size
30
+
31
+ const skiff = makeUnit("skiff", "ai", state.map.bases.ai.x, state.map.bases.ai.y);
32
+ const bastion = makeUnit("bastion", "ai", state.map.bases.ai.x, state.map.bases.ai.y);
33
+ state.units.set(skiff.id, skiff);
34
+ state.units.set(bastion.id, bastion);
35
+
36
+ runAI(state, THINK_INTERVAL);
37
+
38
+ assert.equal(skiff.order?.type, "attack-move");
39
+ assert.equal(bastion.order?.type, "attack-move");
40
+ });
test/combat.test.js CHANGED
@@ -93,3 +93,40 @@ test("attack-move still engages an enemy encountered along the way (unlike plain
93
 
94
  assert.ok(enemy.hp < enemyHp, "attack-move should still fight what it runs into");
95
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
  assert.ok(enemy.hp < enemyHp, "attack-move should still fight what it runs into");
95
  });
96
+
97
+ test("Bastion deals its bonus damage specifically against Skiff", () => {
98
+ const state = createGameState({ planetId: "ferros" });
99
+ const bastion = makeUnit("bastion", "player", 500, 500);
100
+ const skiff = makeUnit("skiff", "ai", 500 + UNITS.bastion.range - 1, 500); // within melee range
101
+ state.units.set(bastion.id, bastion);
102
+ state.units.set(skiff.id, skiff);
103
+ const startHp = skiff.hp;
104
+
105
+ updateCombat(state, bastion, UNITS.bastion.cooldown);
106
+
107
+ const expectedDamage = UNITS.bastion.attack + UNITS.bastion.bonusVs.skiff;
108
+ assert.equal(startHp - skiff.hp, expectedDamage);
109
+ });
110
+
111
+ test("Bastion deals only its base damage against a non-Skiff target", () => {
112
+ const state = createGameState({ planetId: "ferros" });
113
+ const attacker = makeUnit("bastion", "player", 500, 500);
114
+ const otherBastion = makeUnit("bastion", "ai", 500 + UNITS.bastion.range - 1, 500);
115
+ state.units.set(attacker.id, attacker);
116
+ state.units.set(otherBastion.id, otherBastion);
117
+ const startHp = otherBastion.hp;
118
+
119
+ updateCombat(state, attacker, UNITS.bastion.cooldown);
120
+
121
+ assert.equal(startHp - otherBastion.hp, UNITS.bastion.attack);
122
+ });
123
+
124
+ test("Skiff has no bonus damage table and deals only its base attack", () => {
125
+ const state = createGameState({ planetId: "ferros" });
126
+ const [a, b] = faceOff(state);
127
+ const startHp = b.hp;
128
+
129
+ updateCombat(state, a, UNITS.skiff.cooldown);
130
+
131
+ assert.equal(startHp - b.hp, UNITS.skiff.attack);
132
+ });
test/entities.test.js CHANGED
@@ -18,6 +18,20 @@ test("payCost deducts every listed commodity and leaves others untouched", () =>
18
  test("unit and building defs carry the fields the sim depends on", () => {
19
  assert.equal(UNITS.worker.role, "worker");
20
  assert.equal(UNITS.skiff.role, "combat");
 
21
  assert.equal(BUILDINGS.command.isCommandCenter, true);
22
  assert.ok(BUILDINGS.barracks.produces.includes("skiff"));
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  });
 
18
  test("unit and building defs carry the fields the sim depends on", () => {
19
  assert.equal(UNITS.worker.role, "worker");
20
  assert.equal(UNITS.skiff.role, "combat");
21
+ assert.equal(UNITS.bastion.role, "combat");
22
  assert.equal(BUILDINGS.command.isCommandCenter, true);
23
  assert.ok(BUILDINGS.barracks.produces.includes("skiff"));
24
+ assert.ok(BUILDINGS.barracks.produces.includes("bastion"));
25
+ });
26
+
27
+ test("Bastion is the deliberate Skiff counter: bonus damage vs skiff, but slower and costlier", () => {
28
+ assert.equal(UNITS.bastion.bonusVs.skiff, 14);
29
+ assert.ok(UNITS.bastion.speed < UNITS.skiff.speed, "Bastion should be slower, not a strict upgrade");
30
+ assert.ok(UNITS.bastion.cost.ore > UNITS.skiff.cost.ore, "Bastion should cost more, not a strict upgrade");
31
+ assert.ok(UNITS.bastion.hp > UNITS.skiff.hp);
32
+ });
33
+
34
+ test("every unit and building carries a sight radius for fog of war", () => {
35
+ for (const def of Object.values(UNITS)) assert.ok(def.sight > 0, `${def.id} needs a sight radius`);
36
+ for (const def of Object.values(BUILDINGS)) assert.ok(def.sight > 0, `${def.id} needs a sight radius`);
37
  });
test/fog.test.js ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createFog, updateFog, isVisibleAt, isExploredAt, FOG_CELL_SIZE } from "../engine/fog.js";
4
+ import { makeUnit, makeBuilding } from "../engine/state.js";
5
+
6
+ function mapStub(width = 800, height = 600) {
7
+ return { width, height };
8
+ }
9
+
10
+ test("a freshly created fog grid is entirely unexplored and not visible", () => {
11
+ const fog = createFog(mapStub());
12
+ assert.equal(isVisibleAt(fog, 100, 100), false);
13
+ assert.equal(isExploredAt(fog, 100, 100), false);
14
+ });
15
+
16
+ test("updateFog reveals cells within a unit's sight radius, and marks them explored", () => {
17
+ const map = mapStub();
18
+ const fog = createFog(map);
19
+ const worker = makeUnit("worker", "player", 400, 300); // worker sight = 110
20
+ const state = { units: new Map([[worker.id, worker]]), buildings: new Map() };
21
+
22
+ updateFog(state, fog, "player");
23
+
24
+ assert.equal(isVisibleAt(fog, 400, 300), true, "right on top of the worker");
25
+ assert.equal(isVisibleAt(fog, 400 + 100, 300), true, "within sight radius");
26
+ assert.equal(isVisibleAt(fog, 400 + 500, 300), false, "far outside sight radius");
27
+ assert.equal(isExploredAt(fog, 400, 300), true);
28
+ });
29
+
30
+ test("only the requested owner's entities grant vision", () => {
31
+ const map = mapStub();
32
+ const fog = createFog(map);
33
+ const enemy = makeUnit("skiff", "ai", 400, 300);
34
+ const state = { units: new Map([[enemy.id, enemy]]), buildings: new Map() };
35
+
36
+ updateFog(state, fog, "player");
37
+
38
+ assert.equal(isVisibleAt(fog, 400, 300), false, "an enemy unit shouldn't grant the player vision");
39
+ });
40
+
41
+ test("explored cells stay explored after the source of vision moves away, but stop being visible", () => {
42
+ const map = mapStub();
43
+ const fog = createFog(map);
44
+ const worker = makeUnit("worker", "player", 400, 300);
45
+ const state = { units: new Map([[worker.id, worker]]), buildings: new Map() };
46
+
47
+ updateFog(state, fog, "player");
48
+ assert.equal(isVisibleAt(fog, 400, 300), true);
49
+
50
+ worker.x = 400 + 1000; // walk far away, well outside the map even
51
+ updateFog(state, fog, "player");
52
+
53
+ assert.equal(isVisibleAt(fog, 400, 300), false, "no longer in sight");
54
+ assert.equal(isExploredAt(fog, 400, 300), true, "but permanently remembered as explored");
55
+ });
56
+
57
+ test("buildings also grant vision, at their own sight radius", () => {
58
+ const map = mapStub();
59
+ const fog = createFog(map);
60
+ const cc = makeBuilding("command", "player", 400, 300); // command sight = 220
61
+ const state = { units: new Map(), buildings: new Map([[cc.id, cc]]) };
62
+
63
+ updateFog(state, fog, "player");
64
+
65
+ assert.equal(isVisibleAt(fog, 400 + 200, 300), true);
66
+ assert.equal(isVisibleAt(fog, 400 + 300, 300), false);
67
+ });
68
+
69
+ test("cells outside the map bounds are neither visible nor explored, not a crash", () => {
70
+ const fog = createFog(mapStub());
71
+ assert.equal(isVisibleAt(fog, -50, -50), false);
72
+ assert.equal(isVisibleAt(fog, 100000, 100000), false);
73
+ });
74
+
75
+ test("FOG_CELL_SIZE is a sane positive grid resolution", () => {
76
+ assert.ok(FOG_CELL_SIZE > 0);
77
+ });
test/production.test.js CHANGED
@@ -38,6 +38,17 @@ test("queueProduction refuses a unit type the building can't produce", () => {
38
  assert.equal(ok, false);
39
  });
40
 
 
 
 
 
 
 
 
 
 
 
 
41
  test("a queued unit spawns once its build time elapses, at the building and owned by it", () => {
42
  const state = createGameState({ planetId: "ferros" });
43
  const cc = commandCenterOf(state, "player");
 
38
  assert.equal(ok, false);
39
  });
40
 
41
+ test("a Barracks can queue both Skiff and Bastion", () => {
42
+ const state = createGameState({ planetId: "ferros" });
43
+ const barracks = makeBuilding("barracks", "player", 500, 500);
44
+ state.buildings.set(barracks.id, barracks);
45
+ state.players.player.resources.ore = 1000;
46
+
47
+ assert.equal(queueProduction(state, barracks.id, "skiff"), true);
48
+ assert.equal(queueProduction(state, barracks.id, "bastion"), true);
49
+ assert.equal(barracks.queue.length, 2);
50
+ });
51
+
52
  test("a queued unit spawns once its build time elapses, at the building and owned by it", () => {
53
  const state = createGameState({ planetId: "ferros" });
54
  const cc = commandCenterOf(state, "player");