Compare commits

...

5 Commits

Author SHA1 Message Date
Brian Fertig 4813c17cce feat: add custom backgrounds for Bejeweled and Peggle games
- Add background images for Bejeweled Blitz and Peggle menu screens
- Update asset manifest with new bg-bejeweled and bg-peggle-menu textures
- Bejeweled: use new background with fallback to existing bj-bg
- Peggle: replace title/subtitle text with custom background image
- Adjust Peggle progress text position to top-right corner
2026-07-25 20:56:57 -06:00
Brian Fertig 195e88f2dc feat(totalannihilation): add auto-heal for idle builders
Idle builder units now automatically repair damaged allied structures
and units within their build range. A priority system ensures defensive
buildings are repaired before factories and other buildings. Auto-heal
orders are marked as non-player-assigned so explicit player orders
always take precedence. Builders can re-prioritize targets on a
retargeting cadence, similar to combat target acquisition.

Includes visual asset updates for TA arm and core units/structures.
Adjusts test to isolate passive self-heal from the new auto-heal mechanic.
2026-07-25 20:36:50 -06:00
Brian Fertig 39059a3551 feat(total-annihilation): add rocket trooper, constructor, and advanced vehicle plant
Introduce three new entities:
- Rocket Trooper: anti-armor infantry with shoulder-mounted guided rocket
- Constructor: unarmed tracked builder to replace lost commander build capacity
- Advanced Vehicle Plant: 4×4 factory with doubled production bays

Update AI composition weights and counter logic for the new units. Fix
byDef map to use Object.create(null) so the "constructor" key doesn't
shadow Object.prototype.constructor and silently poison gap calculations.

Add procedural art shapes for all three, register proc shapes in TARules,
update sprite frame assignments, and add core-structures assets.
2026-07-25 19:52:26 -06:00
Brian Fertig c835096610 feat(total-annihilation): polish visuals, audio, and game balance
- Add TA-specific sound effects (machinegun, 50cal, rocket variants, unit/vehicle loss)
- Add background artwork and update core-units sprite sheet with correct path and dimensions
- Introduce pintle gun weapon with burst fire mechanics
- Switch weapon sounds to TA-themed audio; support sound arrays for random variant picking
- Add impactSound field to projectile weapons, propagated through sim events
- Reduce unit build times and increase structure HP for better pacing
- Enable idle breathing/rotation animations on resource generators
- Replace solid-color backdrop with painted background image on main menu
- Fix camera state cleanup so menus render correctly after gameplay
2026-07-25 19:51:25 -06:00
Brian Fertig 3c053e5984 feat: add granular order queue cancellation
Introduce the ability to cancel individual queued orders, addressing the
previous limitation where `stop` only cleared the entire queue.

- Add `cancelOrder` logic with proper cleanup for unstarted BUILD orders
  (site removal, footprint unstamping, freeing builders)
- Implement queue hit-testing and visual selection highlighting in TAWorldView
- Wire up right-click cancellation, Delete/Backspace key binding, and
  click-to-highlight queue entries in the game scene
- Automatically invalidate queue selection when units die, are deselected,
  or orders are consumed

Players can now precisely manage command queues without affecting active or
completed constructions.
2026-07-25 16:16:33 -06:00
31 changed files with 556 additions and 49 deletions

BIN
assets/fx/ta-50cal.mp3 Normal file

Binary file not shown.

BIN
assets/fx/ta-machinegun.mp3 Normal file

Binary file not shown.

BIN
assets/fx/ta-rocket-1.mp3 Normal file

Binary file not shown.

BIN
assets/fx/ta-rocket-2.mp3 Normal file

Binary file not shown.

BIN
assets/fx/ta-unit-loss.mp3 Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 946 KiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

View File

@ -39,8 +39,8 @@
"frameWidth": 192, "frameHeight": 192, "cols": 6
},
"core-units": {
"key": "ta-core-units", "path": null, "kind": "unit",
"frameWidth": 64, "frameHeight": 64, "cols": 8
"key": "ta-core-units", "path": "assets/images/ta/core-units.png", "kind": "unit",
"frameWidth": 128, "frameHeight": 128, "cols": 8
},
"core-structures": {
"key": "ta-core-structures", "path": null, "kind": "structure",

View File

@ -245,7 +245,35 @@
"width": 1.5,
"lifeMs": 70
},
"sound": "sfx-battle-gunfire-modern"
"sound": "sfx-ta-machinegun"
},
{
"id": "pintlegun",
"name": "Pintle Gun",
"kind": "hitscan",
"damage": 9,
"reload": 0.5,
"burst": 3,
"burstDelay": 0.06,
"range": 200,
"spread": 0.05,
"targets": [
"ground"
],
"armorMul": {
"infantry": 1.3,
"light": 0.85,
"medium": 0.3,
"heavy": 0.12,
"structure": 0.2
},
"fx": {
"style": "tracer",
"color": "#ffe6a0",
"width": 1.5,
"lifeMs": 70
},
"sound": "sfx-ta-50cal"
},
{
"id": "sniperrifle",
@ -335,7 +363,40 @@
"width": 2,
"trail": true
},
"sound": "sfx-battle-missle"
"sound": "sfx-ta-rocket-1",
"impactSound": "sfx-ta-rocket-2"
},
{
"id": "shoulderrocket",
"name": "Shoulder Rocket",
"kind": "guided",
"damage": 32,
"reload": 2.2,
"burst": 1,
"range": 320,
"minRange": 60,
"speed": 260,
"turnRate": 2.0,
"aoe": 24,
"aoeFalloff": 0.15,
"targets": [
"ground"
],
"armorMul": {
"infantry": 0.35,
"light": 0.8,
"medium": 1.1,
"heavy": 1.3,
"structure": 1.0
},
"fx": {
"style": "rocket",
"color": "#ff9a5c",
"width": 1.5,
"trail": true
},
"sound": "sfx-ta-rocket-1",
"impactSound": "sfx-ta-rocket-2"
},
{
"id": "commanderlaser",
@ -448,7 +509,7 @@
"width": 2.5,
"trail": true
},
"sound": "sfx-battle-missle"
"sound": ["sfx-ta-rocket-1", "sfx-ta-rocket-2"]
}
],
"units": [
@ -523,7 +584,7 @@
"energy": 120,
"mass": 24
},
"buildTime": 6,
"buildTime": 2,
"builtBy": [
"barracks"
],
@ -553,7 +614,7 @@
"energy": 260,
"mass": 55
},
"buildTime": 12,
"buildTime": 6,
"builtBy": [
"barracks"
],
@ -567,6 +628,36 @@
"spritePx": 30,
"moveSound": "sfx-march"
},
{
"id": "rockettrooper",
"name": "Rocket Trooper",
"role": "combat",
"size": "small",
"radius": 16,
"hp": 240,
"speed": 50,
"turnRate": 5.5,
"moveClass": "foot",
"armorClass": "infantry",
"sight": 280,
"cost": {
"energy": 220,
"mass": 45
},
"buildTime": 5,
"builtBy": [
"barracks"
],
"weapons": [
"shoulderrocket"
],
"sheetSlot": "unitSheet",
"frame": 10,
"procShape": "rocketTrooper",
"icon": 6,
"spritePx": 30,
"moveSound": "sfx-march"
},
{
"id": "jeep",
"name": "Jeep",
@ -588,7 +679,7 @@
"vehicleplant"
],
"weapons": [
"rifle"
"pintlegun"
],
"sheetSlot": "unitSheet",
"frame": 4,
@ -659,6 +750,44 @@
"icon": 5,
"spritePx": 56,
"moveSound": "sfx-engine-heavy"
},
{
"id": "constructor",
"name": "Construction Vehicle",
"role": "builder",
"size": "medium",
"radius": 24,
"hp": 700,
"speed": 85,
"turnRate": 2.4,
"moveClass": "tread",
"armorClass": "light",
"sight": 340,
"cost": {
"energy": 500,
"mass": 140
},
"buildTime": 14,
"builtBy": [
"vehicleplant"
],
"buildPower": 90,
"buildRange": 180,
"builds": [
"energygen",
"massgen",
"barracks",
"vehicleplant",
"lasertower",
"missilelauncher",
"advancedvehicleplant"
],
"sheetSlot": "unitSheet",
"frame": 11,
"procShape": "constructor",
"icon": 7,
"spritePx": 50,
"moveSound": "sfx-engine-heavy"
}
],
"buildings": [
@ -669,7 +798,7 @@
"w": 2,
"h": 2
},
"hp": 1440,
"hp": 2440,
"armorClass": "structure",
"sight": 160,
"cost": {
@ -691,7 +820,8 @@
"frame": 0,
"buildFrame": 1,
"procShape": "energyGen",
"icon": 10
"icon": 10,
"idleAnimation": true
},
{
"id": "massgen",
@ -700,7 +830,7 @@
"w": 2,
"h": 2
},
"hp": 1260,
"hp": 2260,
"armorClass": "structure",
"sight": 160,
"cost": {
@ -722,7 +852,8 @@
"frame": 2,
"buildFrame": 3,
"procShape": "massGen",
"icon": 11
"icon": 11,
"idleAnimation": true
},
{
"id": "barracks",
@ -731,7 +862,7 @@
"w": 3,
"h": 3
},
"hp": 2520,
"hp": 3520,
"armorClass": "structure",
"sight": 220,
"cost": {
@ -742,7 +873,8 @@
"buildPower": 100,
"builds": [
"infantry",
"sniper"
"sniper",
"rockettrooper"
],
"spawnOffset": {
"x": 0,
@ -761,7 +893,7 @@
"w": 3,
"h": 3
},
"hp": 3960,
"hp": 4960,
"armorClass": "structure",
"sight": 220,
"cost": {
@ -773,7 +905,8 @@
"builds": [
"jeep",
"tank",
"rockettank"
"rockettank",
"constructor"
],
"spawnOffset": {
"x": 0,
@ -792,7 +925,7 @@
"w": 1,
"h": 1
},
"hp": 1300,
"hp": 3300,
"armorClass": "structure",
"sight": 300,
"cost": {
@ -823,7 +956,7 @@
"w": 2,
"h": 2
},
"hp": 1700,
"hp": 4700,
"armorClass": "structure",
"sight": 420,
"cost": {
@ -846,6 +979,37 @@
"buildFrame": 11,
"procShape": "missileLauncher",
"icon": 15
},
{
"id": "advancedvehicleplant",
"name": "Advanced Vehicle Plant",
"footprint": {
"w": 4,
"h": 4
},
"hp": 6600,
"armorClass": "structure",
"sight": 240,
"cost": {
"energy": 2400,
"mass": 900
},
"buildTime": 55,
"buildPower": 140,
"builds": [
"jeep",
"tank",
"rockettank"
],
"spawnOffset": {
"x": 0,
"y": 2.6
},
"sheetSlot": "structureSheet",
"frame": 12,
"buildFrame": 13,
"procShape": "advancedVehiclePlant",
"icon": 16
}
],
"commandIcons": {

View File

@ -78,6 +78,7 @@ export const MANIFEST = {
],
risk: [image('risk-board', 'assets/images/risk-board.png')],
jewelquest: [image('bg-jewelquest-battle', 'assets/images/background-jewelquest.png')],
bejeweled: [image('bg-bejeweled', 'assets/images/background-bejeweledblitz.png')],
dominion: [
// Dominion card art. One 270×390 cell per card (art fills the top ~60%;
// the title/icon band is drawn at runtime). Optional — the scene falls
@ -158,6 +159,7 @@ export const MANIFEST = {
},
peggle: [
sheet('peggle-sprites', 'assets/images/peggle-sprites.png', 64, 64),
image('bg-peggle-menu', 'assets/images/background-peggle.png'),
// One board background per master, named by opponent id
// (assets/images/peggle/<masterId>.png, 1200×900).
(scene) => {
@ -244,10 +246,15 @@ export const MANIFEST = {
{ type: 'json', key: 'totalannihilation-rules', path: 'data/totalannihilation-rules.json' },
{ type: 'json', key: 'totalannihilation-campaign', path: 'data/totalannihilation-campaign.json' },
(scene) => sheetsFrom(scene, 'totalannihilation-artwork', ['sheets']),
image('ta-background', 'assets/images/ta/background.png'),
// Weapon sounds keyed by each weapon's `sound` in totalannihilation-rules.json.
...['gunfire-modern', 'tank', 'missle'].map((n) => ({ type: 'audio', key: `sfx-battle-${n}`, path: `assets/fx/battle-${n}.mp3` })),
...['tank'].map((n) => ({ type: 'audio', key: `sfx-battle-${n}`, path: `assets/fx/battle-${n}.mp3` })),
{ type: 'audio', key: 'sfx-laser-zap', path: 'assets/fx/laser-zap.mp3' },
{ type: 'audio', key: 'sfx-scifi-launch', path: 'assets/fx/scifi-launch.mp3' },
// TA-specific sfx: machine guns per weapon.sound, rocket variants (random pick between the
// two on fire, see TotalAnnihilationGame._onSimEvent), and unit/vehicle death cues.
...['50cal', 'machinegun', 'rocket-1', 'rocket-2', 'unit-loss', 'vehicle-loss']
.map((n) => ({ type: 'audio', key: `sfx-ta-${n}`, path: `assets/fx/ta-${n}.mp3` })),
(scene) => musicFrom(scene, 'hacker-music'),
],
coloradodefense: [

View File

@ -246,7 +246,8 @@ export default class BejeweledGame extends Phaser.Scene {
// ── Cosmic backdrop ───────────────────────────────────────────────────────
buildBackground() {
this.add.image(0, 0, 'bj-bg').setOrigin(0).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.bg);
const bgKey = this.textures.exists('bg-bejeweled') ? 'bg-bejeweled' : 'bj-bg';
this.add.image(0, 0, bgKey).setOrigin(0).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.bg);
const nebulas = [
{ x: 420, y: 280, tint: 0x6633ff, alpha: 0.17, scale: 9 },

View File

@ -275,13 +275,10 @@ export default class PeggleGame extends Phaser.Scene {
this.clearLayer();
const cx = GAME_WIDTH / 2;
const title = this.add.text(cx, 90, 'PEGGLE', {
fontFamily: 'Righteous', fontSize: '72px', color: COLORS.goldHex,
}).setOrigin(0.5);
const sub = this.add.text(cx, 152, 'Clear all 25 orange pegs. A friend joins every level — hit their green pegs to fire their power!', {
fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.mutedHex,
}).setOrigin(0.5);
this.layer.add([title, sub]);
if (this.textures.exists('bg-peggle-menu')) {
this.layer.add(this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, 'bg-peggle-menu')
.setDisplaySize(GAME_WIDTH, GAME_HEIGHT));
}
if (!this.manifest.length) {
const msg = this.add.text(cx, 480, 'No levels found.\nRun: node tools/genPeggleLevels.js', {
@ -293,9 +290,9 @@ export default class PeggleGame extends Phaser.Scene {
}
const nextLevel = Math.min(this.levelsCompleted + 1, this.manifest.length);
const prog = this.add.text(cx, 208, `Completed ${this.levelsCompleted} / ${this.manifest.length}`, {
const prog = this.add.text(GAME_WIDTH - 40, 208, `Completed ${this.levelsCompleted} / ${this.manifest.length}`, {
fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex,
}).setOrigin(0.5);
}).setOrigin(1, 0.5);
this.layer.add(prog);
// One row per friend: portrait + name + power on the left, that friend's

View File

@ -16,6 +16,10 @@ import { worldToTileX, worldToTileY } from './TANav.js';
/** Desired force mix per skill. Below skill 3 the AI just buys whatever it can afford. */
const COMPOSITION = {
infantry: 0.34, sniper: 0.10, jeep: 0.06, tank: 0.34, rockettank: 0.16,
// The new anti-armour infantry and the unarmed construction vehicle: a modest slice of the
// mix for the trooper, and just enough of the vehicle to occasionally replace a lost
// Commander's construction capacity — not a real combat unit, so it stays a low priority.
rockettrooper: 0.14, constructor: 0.04,
};
function memFor(state, armyIdx) {
@ -120,7 +124,15 @@ function observe(ctx) {
function gatherOwn(ctx) {
const { state, armyIdx, rules } = ctx;
const out = { commanders: [], builders: [], factories: [], buildings: [], units: [], sites: [], byDef: {} };
// Object.create(null): a unit id of "constructor" (or any other Object.prototype member) as
// a plain-object key would otherwise shadow the inherited property instead of adding one,
// so `byDef['constructor'] ?? 0` reads back the Object constructor FUNCTION — a truthy,
// non-nullish value the ?? guard doesn't catch — and every arithmetic use of it silently
// becomes NaN from tick one, which poisons every gap comparison built.reduce touches.
const out = {
commanders: [], builders: [], factories: [], buildings: [], units: [], sites: [],
byDef: Object.create(null),
};
for (const e of state.entities) {
if (e.dead || e.army !== armyIdx) continue;
const def = rules.defById[e.defId];
@ -364,6 +376,7 @@ function applyCounters(ctx, weights) {
weights.tank *= 1 + (1 - armourShare) * 0.8;
weights.rockettank *= 1 + armourShare * 1.0 + (structures > 2 ? 0.3 : 0);
weights.sniper *= 1 + (1 - armourShare) * 0.5;
weights.rockettrooper *= 1 + armourShare * 0.6;
}
// ---------------------------------------------------------------------------

View File

@ -146,6 +146,22 @@ const UNIT_SHAPES = {
ctx.restore();
},
rocketTrooper(ctx, S) {
const c = S / 2;
ctx.save(); ctx.translate(c, c);
roundRect(ctx, -8, -5, 16, 10, 5); fillStroke(ctx, BODY);
ctx.beginPath(); ctx.arc(1, 0, 4.5, 0, Math.PI * 2); fillStroke(ctx, BODY_DARK);
// shoulder-mounted launch tube, angled up off the body line so it reads distinct from
// the rifle silhouette even at a glance.
ctx.strokeStyle = OUTLINE; ctx.lineWidth = 4.5;
ctx.beginPath(); ctx.moveTo(2, -3); ctx.lineTo(17, -8); ctx.stroke();
ctx.strokeStyle = ACCENT; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(2, -3); ctx.lineTo(17, -8); ctx.stroke();
ctx.fillStyle = HOT;
ctx.beginPath(); ctx.arc(17, -8, 2.2, 0, Math.PI * 2); ctx.fill();
ctx.restore();
},
jeep(ctx, S) {
const c = S / 2;
ctx.save(); ctx.translate(c, c);
@ -199,6 +215,20 @@ const UNIT_SHAPES = {
}
ctx.restore();
},
// Unarmed — no turret frame. The hull is the same tread-vehicle base as the combat tanks,
// topped with a folded nanolathe crane instead of a gun so it reads as a builder at a glance.
constructor(ctx, S) {
tankHull(ctx, S, 32, 26);
const c = S / 2;
ctx.save(); ctx.translate(c, c);
roundRect(ctx, -6, -8, 14, 16, 3); fillStroke(ctx, BODY_DARK);
ctx.strokeStyle = ACCENT; ctx.lineWidth = 3;
ctx.beginPath(); ctx.moveTo(2, 0); ctx.lineTo(15, 0); ctx.stroke();
ctx.fillStyle = HOT;
ctx.beginPath(); ctx.arc(16, 0, 2.5, 0, Math.PI * 2); ctx.fill();
ctx.restore();
},
};
function tankHull(ctx, S, len, wid) {
@ -378,6 +408,42 @@ const STRUCT_SHAPES = {
ctx.moveTo(p + w * 0.24, p + h - 8); ctx.lineTo(p + w * 0.76, p + h - 8);
ctx.stroke();
},
// The 4x4 footprint's extra width goes to a SECOND bay door — twice the production, which
// is the whole pitch of the "advanced" tier — plus a trim line the basic plant doesn't have.
advancedVehiclePlant(ctx, S) {
const p = S * 0.06, w = S - p * 2, h = S - p * 2;
roundRect(ctx, p, p, w, h, S * 0.04); fillStroke(ctx, BODY, OUTLINE, 3);
// twin gantry rails across the roof
ctx.fillStyle = BODY_DARK;
ctx.fillRect(p + 4, p + h * 0.10, w - 8, h * 0.05);
ctx.fillRect(p + 4, p + h * 0.18, w - 8, h * 0.05);
ctx.fillStyle = '#3b3f47';
for (let i = 0; i < 7; i++) ctx.fillRect(p + 8 + i * ((w - 16) / 7), p + h * 0.10, 4, h * 0.13);
// two roll-up bay doors side by side, each slatted like the basic plant's single door
const dw = w * 0.30, dy = p + h * 0.36, dh = h * 0.46;
const doorX = [p + w * 0.16, p + w * 0.54];
for (const dx of doorX) {
ctx.fillStyle = '#2f3238';
ctx.fillRect(dx, dy, dw, dh);
ctx.strokeStyle = '#4a4e56'; ctx.lineWidth = 2;
for (let i = 1; i < 6; i++) {
const y = dy + (dh * i) / 6;
ctx.beginPath(); ctx.moveTo(dx + 2, y); ctx.lineTo(dx + dw - 2, y); ctx.stroke();
}
}
// accent trim along the roofline marks the upgraded facility
ctx.strokeStyle = ACCENT; ctx.lineWidth = 3;
ctx.beginPath(); ctx.moveTo(p + 6, p + 6); ctx.lineTo(p + w - 6, p + 6); ctx.stroke();
// floor chevron out of each mouth, same language as the basic plant
ctx.strokeStyle = HOT; ctx.lineWidth = 4;
for (const dx of doorX) {
const mx = dx + dw / 2;
ctx.beginPath();
ctx.moveTo(mx - 12, p + h - 18); ctx.lineTo(mx, p + h - 8); ctx.lineTo(mx + 12, p + h - 18);
ctx.stroke();
}
},
};
// ---------------------------------------------------------------------------

View File

@ -356,6 +356,45 @@ function buildCommand(state, rules, army, units, order, queue) {
return { ok: true, siteId: site.id };
}
/**
* Remove one order from a unit's queue by index — the missing counterpart to `stop`, which
* only ever clears the whole queue. Cancelling the active order (index 0) gets the same state
* reset stepOrders' own completion paths already do, so nothing is left chasing an order that
* is no longer there.
*
* A queued BUILD order carries a live site entity from the moment it was placed (see
* placeBuilding) — stamped into the nav grid regardless of how deep in the queue it sits.
* Cancelling it before any progress has been made tears that site back out (footprint
* unstamped, entity removed, any other builder pointed at it freed up); once work has begun,
* only the queue slot goes away — the site, and anyone else building it, are untouched.
*/
export function cancelOrder(state, rules, army, unitId, index) {
const e = entityById(state, unitId);
if (!e || e.army !== army || !Array.isArray(e.orders) || index < 0 || index >= e.orders.length) {
return { ok: false, error: 'no such queued order' };
}
const order = e.orders[index];
if (order.type === 'build') {
const site = entityById(state, order.targetId);
if (site && site.isBuilding && (site.progress ?? 0) <= 0) {
stampFootprint(state.nav, rules, site.tx, site.ty, site.fw, site.fh, false);
site.dead = true;
for (const o of state.entities) {
if (o.buildTargetId === site.id) o.buildTargetId = 0;
if (o.targetId === site.id) o.targetId = 0;
}
}
}
e.orders.splice(index, 1);
if (index === 0) {
e.path = null; e.movingTo = null; e.targetId = 0; e.buildTargetId = 0;
e.stuckTicks = 0; e.noPath = false;
}
return { ok: true };
}
/** Can this footprint go here? Checks bounds, terrain buildability and occupancy. */
export function canPlaceAt(state, rules, tx, ty, def) {
const fw = def.footprint.w, fh = def.footprint.h;
@ -671,6 +710,36 @@ function orderDestination(e, order) {
return { x: order.sx ?? order.x, y: order.sy ?? order.y };
}
/** Auto-heal priority: lower tier heals first — defensive > factory > other building > unit. */
function healPriorityTier(def) {
if (!def.isBuilding) return 3;
if (def.weapons?.length) return 0;
if (def.builds?.length) return 1;
return 2;
}
/**
* Best in-range damaged ally for `e` to auto-repair, or null. Same reach math as a player's
* own repair order (`buildRange` + target radius) — a site under construction is `assist`'s
* job, not this one, so it's excluded even though its partial hp technically reads as damaged.
*/
function findAutoHealTarget(state, rules, e, def) {
const range = def.buildRange ?? 0;
let best = null, bestTier = Infinity, bestDSq = Infinity;
for (const t of state.entities) {
if (t.dead || t.id === e.id || t.army !== e.army || t.site) continue;
if (t.hp >= t.maxHp) continue;
const reach = range + t.radius;
const dSq = (t.x - e.x) ** 2 + (t.y - e.y) ** 2;
if (dSq > reach * reach) continue;
const tier = healPriorityTier(defOf(rules, t));
if (tier < bestTier || (tier === bestTier && dSq < bestDSq)) {
best = t; bestTier = tier; bestDSq = dSq;
}
}
return best;
}
function stepOrders(state, rules) {
const ts = state.tileSize;
for (const e of state.entities) {
@ -682,6 +751,14 @@ function stepOrders(state, rules) {
if (!order) {
e.movingTo = null;
e.buildTargetId = 0;
// Auto-heal: an idle builder with something damaged in range starts repairing it on its
// own, no order needed. `auto: true` marks it as self-assigned rather than player-issued,
// so a real order the player gives afterward — pushOrder always replaces e.orders wholesale
// when not queuing — simply overwrites it like any other order, never fights it.
if (def.buildPower > 0) {
const target = findAutoHealTarget(state, rules, e, def);
if (target) e.orders.push({ type: 'repair', targetId: target.id, auto: true });
}
continue;
}
@ -693,6 +770,24 @@ function stepOrders(state, rules) {
e.buildTargetId = 0;
}
// Auto-heal keeps re-prioritising while it works, on the same staggered cadence combat
// uses for target acquisition — a defensive building taking fire should pull a builder off
// a generator it's already patching, but two similarly-urgent targets shouldn't make it
// flicker between them every time this runs.
if (order.type === 'repair' && order.auto && def.buildPower > 0) {
const due = ((state.tick + e.id) % rules.constants.retargetPeriodTicks) === 0;
if (due) {
const current = entityById(state, order.targetId);
const currentValid = !!current && !current.site && current.hp < current.maxHp
&& Math.hypot(current.x - e.x, current.y - e.y) <= (def.buildRange ?? 0) + current.radius;
const currentTier = currentValid ? healPriorityTier(defOf(rules, current)) : Infinity;
const candidate = findAutoHealTarget(state, rules, e, def);
if (candidate && (!currentValid || healPriorityTier(defOf(rules, candidate)) < currentTier)) {
order.targetId = candidate.id;
}
}
}
switch (order.type) {
case 'stop':
e.orders.length = 0;
@ -1193,7 +1288,7 @@ function fireWeapon(state, rules, e, w, target, facing, aimPt) {
if (hit) {
applyDamage(state, rules, target, w.damage * (w.armorMul?.[rules.defById[target.defId].armorClass] ?? 1), e);
if (w.aoe) applyAoe(state, rules, aim.x, aim.y, w, e);
state.events.push({ t: 'impact', x: ex, y: ey, radius: w.aoe ?? 8, style: w.fx.style });
state.events.push({ t: 'impact', x: ex, y: ey, radius: w.aoe ?? 8, style: w.fx.style, sound: w.impactSound });
}
return;
}
@ -1281,7 +1376,7 @@ function stepProjectiles(state, rules) {
}
if (detonate) {
state.events.push({ t: 'impact', x: p.x, y: p.y, radius: w.aoe ?? 12, style: w.fx.style });
state.events.push({ t: 'impact', x: p.x, y: p.y, radius: w.aoe ?? 12, style: w.fx.style, sound: w.impactSound });
if (w.aoe) applyAoe(state, rules, p.x, p.y, w, { army: p.army, id: p.ownerId });
else {
for (const e of state.entities) {

View File

@ -20,8 +20,9 @@ const SIGHT_RANGE_MARGIN_TILES = 2;
// Procedural painter shapes. A def may only name a shape TAArt knows how to draw;
// this set is duplicated there and the verify script asserts the two agree.
export const PROC_SHAPES = new Set([
'commander', 'infantry', 'sniper', 'jeep', 'tank', 'rockettank',
'commander', 'infantry', 'sniper', 'rocketTrooper', 'jeep', 'tank', 'rockettank', 'constructor',
'energyGen', 'massGen', 'barracks', 'vehiclePlant', 'laserTower', 'missileLauncher',
'advancedVehiclePlant',
]);
function fail(msg) {

View File

@ -25,12 +25,26 @@ function screen(scene, objs) {
}
function backdrop(scene, objs, title, subtitle) {
objs.push(scene.add.rectangle(0, 0, GAME_WIDTH, GAME_HEIGHT, BG, 1).setOrigin(0, 0).setDepth(900)
.setInteractive()); // swallow clicks so they never reach the world beneath
const t = scene.add.text(GAME_WIDTH / 2, 92, title, {
fontFamily: FONT, fontSize: '76px', color: TEXT,
}).setOrigin(0.5).setDepth(901);
objs.push(t);
const bg = scene.textures.exists('ta-background')
? scene.add.image(0, 0, 'ta-background').setOrigin(0, 0).setDisplaySize(GAME_WIDTH, GAME_HEIGHT)
: scene.add.rectangle(0, 0, GAME_WIDTH, GAME_HEIGHT, BG, 1).setOrigin(0, 0);
objs.push(bg.setDepth(900).setInteractive()); // swallow clicks so they never reach the world beneath
// The art is a full painted scene, not a UI colour field — every screen dims it a notch so
// loose text (no background box of its own, unlike the buttons) stays legible over it.
objs.push(scene.add.rectangle(0, 0, GAME_WIDTH, GAME_HEIGHT, BG, 0.55).setOrigin(0, 0).setDepth(900));
let t = null;
if (title) {
// The art's own "Total Annihilation" logo sits right in this band — a plain flat scrim
// isn't enough to keep a screen's own title readable over it, so screens that draw one
// get an extra band of darkening here. The main menu (no title passed) skips this and
// shows the logo at full strength instead.
objs.push(scene.add.rectangle(0, 0, GAME_WIDTH, 230, BG, 0.6).setOrigin(0, 0).setDepth(900));
t = scene.add.text(GAME_WIDTH / 2, 92, title, {
fontFamily: FONT, fontSize: '76px', color: TEXT,
}).setOrigin(0.5).setDepth(901);
objs.push(t);
}
if (subtitle) {
objs.push(scene.add.text(GAME_WIDTH / 2, 158, subtitle, {
fontFamily: FONT, fontSize: '24px', color: DIM,
@ -89,10 +103,13 @@ function cycler(scene, objs, x, y, label, options, index, onChange) {
export function mainMenu(scene, { hasSave, onSkirmish, onCampaign, onContinue, onLeave }) {
const objs = [];
backdrop(scene, objs, 'TOTAL ANNIHILATION', 'Commander — your war machine awaits');
// The background art carries its own "Total Annihilation" title card — drawing the usual
// backdrop() title/subtitle on top of it would just double up the logo.
backdrop(scene, objs, null, null);
const cx = GAME_WIDTH / 2;
let y = 330;
// Below the art's own logo, which runs down to roughly y=430.
let y = 560;
button(scene, objs, cx, y, 460, 76, 'SKIRMISH', onSkirmish); y += 100;
button(scene, objs, cx, y, 460, 76, 'CAMPAIGN', onCampaign); y += 100;
button(scene, objs, cx, y, 460, 76, 'CONTINUE', onContinue, { enabled: hasSave }); y += 100;

View File

@ -76,6 +76,7 @@ export default class TAWorldView {
this.sprites = new Map(); // entity id -> { img, turret }
this.selection = new Set();
this.queueSelection = null; // { unitId, index } — a highlighted entry in a drawn order queue
this.placement = null; // { def, tx, ty, legal }
this.showAllBars = false;
this._stamp = scene.make.image({ x: 0, y: 0, key: this.terrainKey, add: false }).setOrigin(0, 0);
@ -416,6 +417,30 @@ export default class TAWorldView {
}
}
// Idle animation for finished resource buildings (energy/mass generators): a slow
// breathing pulse plus a continuous clockwise rotation, so a base full of them reads as
// active rather than static scenery. Each pulse cycle and each quarter-turn re-rolls its
// own random duration, so buildings never fall into visible lockstep with each other.
if (def.isBuilding && def.idleAnimation && !e.site) {
const now = this.scene.time.now;
if (!s.idlePulse || now - s.idlePulse.start >= s.idlePulse.ms) {
s.idlePulse = { start: now, ms: (4 + Math.random() * 4) * 1000 };
}
const pulseT = (now - s.idlePulse.start) / s.idlePulse.ms;
const scale = 0.95 - 0.05 * Math.cos(pulseT * Math.PI * 2);
s.img.setDisplaySize(def.footprint.w * this.ts * scale, def.footprint.h * this.ts * scale);
if (!s.idleRot) s.idleRot = { start: now, ms: 8000 + Math.random() * 4000, turns: 0 };
while (now - s.idleRot.start >= s.idleRot.ms) {
s.idleRot.start += s.idleRot.ms;
s.idleRot.turns++;
s.idleRot.ms = 8000 + Math.random() * 4000;
}
const turnT = (now - s.idleRot.start) / s.idleRot.ms;
s.img.setRotation((s.idleRot.turns + turnT) * (Math.PI / 2));
}
if (s.turret) {
const tr = lerpAngle(e.pturretRot, e.turretRot, alpha);
s.turret.setPosition(x, y).setRotation(tr);
@ -498,6 +523,7 @@ export default class TAWorldView {
const g = this.gOrders;
g.clear();
if (!this.selection.size) return;
const qs = this.queueSelection;
let drawn = 0;
for (const e of this.state.entities) {
@ -523,6 +549,12 @@ export default class TAWorldView {
g.fillStyle(col, active ? 0.9 : 0.6);
g.fillCircle(pt.x, pt.y, active ? 5 : 4);
}
// A clicked-and-held queue entry gets a bright ring so its selection is unambiguous
// before the player commits to deleting it.
if (qs && qs.unitId === e.id && qs.index === i) {
g.lineStyle(2.5, 0xffffff, 0.95);
g.strokeCircle(pt.x, pt.y, o.type === 'build' ? 24 : 11);
}
px = pt.x; py = pt.y;
}
}
@ -541,6 +573,31 @@ export default class TAWorldView {
return null;
}
/**
* Hit-test a world point against the queue ghosts _drawOrderQueues just drew (same
* selected-unit iteration, same MAX_QUEUE_LINES cap, same per-type marker) so a click only
* ever grabs something the player can actually see. Returns the closest { unitId, index }
* within tolerance, or null.
*/
hitTestQueue(wx, wy) {
let best = null, bestD = Infinity;
let drawn = 0;
for (const e of this.state.entities) {
if (e.dead || e.isBuilding || !this.selection.has(e.id)) continue;
if (!e.orders.length) continue;
if (++drawn > MAX_QUEUE_LINES) break;
for (let i = 0; i < e.orders.length; i++) {
const o = e.orders[i];
const pt = this._orderPoint(o);
if (!pt) continue;
const d = Math.hypot(pt.x - wx, pt.y - wy);
const tol = o.type === 'build' ? 20 : 14;
if (d <= tol && d < bestD) { best = { unitId: e.id, index: i }; bestD = d; }
}
}
return best;
}
_drawPlacementGhost() {
const g = this.gGhost;
g.clear();
@ -590,6 +647,19 @@ export default class TAWorldView {
this.worldRoot.destroy(true);
this.uiRoot.destroy(true);
if (this.uiCam) this.scene.cameras.remove(this.uiCam);
// _setupCameras() bounded, zoomed and re-tinted the scene's MAIN camera for the match —
// that camera is shared with (not owned by) this view and outlives it, so whatever menu
// screen comes next inherits it as-is. Without this, the menu's full-screen rectangles
// (built assuming a camera at scroll (0,0), zoom 1) end up positioned outside whatever
// stale scroll/bounds gameplay left behind — the menu is technically there and clickable,
// just scrolled off into empty space, which reads as a black, unresponsive screen.
const cam = this.scene.cameras.main;
cam.removeBounds?.();
cam.setZoom(1);
cam.setScroll(0, 0);
const bg = this.scene.game?.config?.backgroundColor;
if (bg) cam.setBackgroundColor(bg);
}
}

View File

@ -13,6 +13,7 @@ import * as Phaser from 'phaser';
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { MusicPlayer } from '../../ui/MusicPlayer.js';
import { getGameSoundtrack } from '../../services/soundtrack.js';
import { playSound } from '../../ui/Sounds.js';
import { api } from '../../services/api.js';
import { compileRules } from './TARules.js';
import { generateMap, decodeMap } from './TAMapGen.js';
@ -46,6 +47,7 @@ export default class TotalAnnihilationGame extends Phaser.Scene {
this.pendingCommand = null; // 'attackMove' | 'patrol' | 'guard' | 'attack'
this.simSpeed = 1;
this.settings = readJson(SETTINGS_KEY, { edgeScroll: true, fog: true });
this.lastSfxAt = {}; // per-sound-key gate — see _throttledSfx
}
create() {
@ -254,6 +256,16 @@ export default class TotalAnnihilationGame extends Phaser.Scene {
_onSimEvent(ev) {
this.fx.onEvent(ev, this.rules);
// A weapon's fire/impact sound may be a single key or a list of variants (e.g. a weapon
// that alternates between two clips) — resolve to one key before it reaches the throttle
// gate, so each variant is throttled independently rather than the array being treated as
// one key.
if (ev.t === 'weaponFired' && ev.sound) this._throttledSfx(this._pickSound(ev.sound), 90);
if (ev.t === 'impact' && ev.sound) this._throttledSfx(this._pickSound(ev.sound), 90);
if (ev.t === 'unitDestroyed' && !ev.isBuilding) {
const moveClass = this.rules.defById[ev.defId]?.moveClass;
if (moveClass) this._throttledSfx(moveClass === 'foot' ? 'sfx-ta-unit-loss' : 'sfx-ta-vehicle-loss', 120);
}
if (ev.t === 'buildingComplete' && ev.army === this.playerArmy) {
// Terrain under a finished structure changes, so its chunk has to be restamped.
this.view.repaintArea(ev.x - 128, ev.y - 128, ev.x + 128, ev.y + 128);
@ -272,6 +284,20 @@ export default class TotalAnnihilationGame extends Phaser.Scene {
}
}
/** A sound field is either one key or a list of variants to pick between at random. */
_pickSound(sound) {
return Array.isArray(sound) ? sound[Math.floor(Math.random() * sound.length)] : sound;
}
/** Gate repeated plays of the same sound key so a volley of units firing at once doesn't
* stack a dozen overlapping instances of the same clip. */
_throttledSfx(key, gapMs) {
const now = this.time.now;
if ((this.lastSfxAt[key] ?? -1e9) + gapMs > now) return;
this.lastSfxAt[key] = now;
playSound(this, key);
}
_finish(over) {
this.phase = 'result';
const won = over.winner === this.playerArmy;
@ -399,6 +425,7 @@ export default class TotalAnnihilationGame extends Phaser.Scene {
case 'q': this.view.zoomBy(-1, GAME_WIDTH / 2, GAME_HEIGHT / 2); break;
case 'e': this.view.zoomBy(1, GAME_WIDTH / 2, GAME_HEIGHT / 2); break;
case ' ': this._jumpToAction(); break;
case 'delete': case 'backspace': this._deleteQueueSelection(); break;
default: break;
}
if (ev.ctrlKey && code === 'a') this._selectAll();
@ -414,7 +441,14 @@ export default class TotalAnnihilationGame extends Phaser.Scene {
// CTRL is the queue modifier, as in the original: hold it and every order appends to the
// unit's queue instead of replacing it. SHIFT stays on selection (add to selection) and
// on the factory buttons (x5), so the two never fight over the same click.
if (p.rightButtonDown()) { this._issueContextual(w, queueHeld(p)); return; }
if (p.rightButtonDown()) {
// Right-clicking an existing queue ghost cancels that order instead of stacking a
// redundant new one on top of it.
const hit = this.view.hitTestQueue(w.x, w.y);
if (hit) { this._cancelQueueOrder(hit); return; }
this._issueContextual(w, queueHeld(p));
return;
}
if (this.placement) { this._commitPlacement(w, queueHeld(p)); return; }
if (this.pendingCommand) { this._applyPendingCommand(w, queueHeld(p)); return; }
@ -429,8 +463,21 @@ export default class TotalAnnihilationGame extends Phaser.Scene {
const d = this._dragStart;
this._dragStart = null;
const w = this.view.worldPoint(p.x, p.y);
if (this._dragging) this._selectInBox(d.wx, d.wy, w.x, w.y, d.add);
else this._selectAt(w.x, w.y, d.add, !!p.event?.detail && p.event.detail > 1);
if (this._dragging) {
this.view.queueSelection = null;
this._selectInBox(d.wx, d.wy, w.x, w.y, d.add);
} else {
// A plain click landing on a queue ghost just highlights it — it no longer sends the
// unit straight there / puts it straight to work, which used to be indistinguishable
// from "the order didn't register."
const hit = this.view.hitTestQueue(w.x, w.y);
if (hit) {
this.view.queueSelection = hit;
} else {
this.view.queueSelection = null;
this._selectAt(w.x, w.y, d.add, !!p.event?.detail && p.event.detail > 1);
}
}
this._dragging = false;
}
@ -473,6 +520,14 @@ export default class TotalAnnihilationGame extends Phaser.Scene {
if (!e || e.dead) this.selection.delete(id);
}
this.view.selection = this.selection;
// A highlighted queue entry goes stale the moment its unit leaves the selection, dies, or
// the order itself is consumed/cancelled out from under it (queue shrinks past its index).
const qs = this.view.queueSelection;
if (qs) {
const e = this.selection.has(qs.unitId) ? Logic.entityById(this.match, qs.unitId) : null;
if (!e || qs.index >= e.orders.length) this.view.queueSelection = null;
}
}
_selectAt(x, y, add, double) {
@ -569,6 +624,19 @@ export default class TotalAnnihilationGame extends Phaser.Scene {
this._order({ type: 'move', x: w.x, y: w.y }, queue);
}
/** Remove one highlighted/clicked entry from a unit's order queue. */
_cancelQueueOrder(hit) {
const r = Logic.cancelOrder(this.match, this.rules, this.playerArmy, hit.unitId, hit.index);
if (r.ok) this.view.queueSelection = null;
else if (r.error) this.hud.toast(r.error, '#ff9a6b');
}
_deleteQueueSelection() {
const qs = this.view.queueSelection;
if (!qs) return;
this._cancelQueueOrder(qs);
}
_applyPendingCommand(w, queue) {
const cmd = this.pendingCommand;
this.pendingCommand = null;

View File

@ -58,6 +58,8 @@ let the scale do the work.
| 7 | Tank turret | turret + barrel | 54 |
| 8 | Rocket Tank | hull + tracks | 56 |
| 9 | Rocket Tank turret | rocket pod | 56 |
| 10 | Rocket Trooper | whole figure, shoulder-mounted launch tube | 30 |
| 11 | Construction Vehicle | tracked hull, folded nanolathe crane, no gun | 50 |
**Turret frames** are drawn as a separate image stacked on the hull and rotated
independently, so the unit aims while it drives. Rules:
@ -65,10 +67,11 @@ independently, so the unit aims while it drives. Rules:
- The turret's **pivot is the centre of the cell** — draw the turret so its rotation point
sits at (32, 32), with the barrel extending to the **right**.
- Leave the rest of the turret cell transparent. The hull shows through it.
- A unit with no turret (infantry, sniper) simply has no turret frame; its whole sprite
rotates to face its target.
- A unit with no turret (infantry, sniper, rocket trooper, construction vehicle) simply has
no turret frame; its whole sprite rotates to face its target. The Construction Vehicle is
unarmed, so it never turns to aim regardless — it just rotates to face wherever it's moving.
Frames 10–63 are free. Add a unit by appending a definition to `units[]` in
Frames 12–63 are free. Add a unit by appending a definition to `units[]` in
`data/totalannihilation-rules.json` with its `frame` (and optional `turretFrame`) — no code.
---
@ -99,12 +102,14 @@ build completes; the finished frame crossfades in underneath starting at 20% pro
| 9 | Laser Tower — under construction | 1×1 | |
| 10 | Missile Launcher | 2×2 | bunker + launch rack; draw it pointing **up** |
| 11 | Missile Launcher — under construction | 2×2 | |
| 12 | Advanced Vehicle Plant | 4×4 | wider bay, **two** doors side by side |
| 13 | Advanced Vehicle Plant — under construction | 4×4 | |
Defensive structures never rotate, and their mount traverses freely in the simulation — they
shoot in every direction regardless of how the art is drawn. Draw them facing **up** and do not
imply a firing arc.
Frames 12–35 are free.
Frames 14–35 are free.
---

View File

@ -739,8 +739,11 @@ section('6b. Commander self-repair');
run(st4, 120);
check('regeneration stops at full health', c4.hp === c4.maxHp, `${c4.hp}/${c4.maxHp}`);
// Well outside any builder's repair range, so this isolates passive selfHeal regen from the
// auto-heal nanolathe mechanic (an idle builder now auto-repairs damaged allies in range —
// a real, separate source of healing, not a regression of this one).
const st5 = fresh();
const tank = L.spawnUnit(st5, hr, 0, 'tank', c4.x + 200, c4.y);
const tank = L.spawnUnit(st5, hr, 0, 'tank', c4.x + 2000, c4.y);
tank.hp = tank.maxHp * 0.5;
const tankHp = tank.hp;
run(st5, 60);