publicstring commited on
Commit
dfca5e5
Β·
verified Β·
1 Parent(s): d8ee931

Create mechanics.js

Browse files
Files changed (1) hide show
  1. mechanics.js +432 -0
mechanics.js ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // src/lib/mechanics.js
2
+ // ============================================================================
3
+ // LEVEL EVOLUTION β€” MECHANICS ENGINE (Pure JavaScript ES Module)
4
+ // ============================================================================
5
+
6
+ // ─── composition ─────────────────────────────────────────────────
7
+ export const COMPOSITION_ORDER = [ 'ANIMALIA', 'CHITINARIA', 'PLANTAE', 'CNIDARIA', 'MYCELIUM', 'MINERALIS' ];
8
+
9
+ export const COMPOSITION_META = {
10
+ ANIMALIA: { label: 'Animalia', blurb: 'Balanced baseline β€” no free strengths, no hard weaknesses.', accent: '#94a3b8', glow: '#64748b' },
11
+ CHITINARIA:{ label: 'Chitinaria', blurb: 'Free ARMOR at β‰₯30%. Periodic molt window drops defense briefly.', freeStructure: 'ARMOR', accent: '#d97706', glow: '#f59e0b' },
12
+ PLANTAE: { label: 'Plantae', blurb: 'Passive energy regen in light; free ACID resistance. Neural capped at 4.', accent: '#22c55e', glow: '#4ade80' },
13
+ CNIDARIA: { label: 'Cnidaria', blurb: 'Free SOFT structure; toxin Features cost less. CONDUCTIVE β€” vulnerable to Electric.', freeStructure: 'SOFT', accent: '#06b6d4', glow: '#22d3ee' },
14
+ MYCELIUM: { label: 'Mycelium', blurb: 'Free REGEN; nullifies DOT. Speed capped at 4. Fragile HP.', accent: '#a855f7', glow: '#c084fc' },
15
+ MINERALIS: { label: 'Mineralis', blurb: 'Free BRITTLE; zero food need. Immune to TOXIN/ACID. Cannot regenerate.', freeStructure: 'BRITTLE', accent: '#e2e8f0', glow: '#f1f5f9' },
16
+ };
17
+
18
+ export function dominantComposition(c) {
19
+ const e = COMPOSITION_ORDER.map(k => [k, c[k]]).filter(([, v]) => v >= 30).sort((a, b) => b[1] - a[1]);
20
+ return e.length ? e[0][0] : null;
21
+ }
22
+
23
+ export function setCompositionLinked(comps, key, value) {
24
+ const clamped = Math.max(0, Math.min(100, Math.round(value)));
25
+ const others = COMPOSITION_ORDER.filter(k => k !== key);
26
+ const oldSum = others.reduce((s, k) => s + comps[k], 0);
27
+ const residual = 100 - clamped;
28
+ const next = { ...comps, [key]: clamped };
29
+
30
+ if (oldSum === 0) {
31
+ const each = Math.floor(residual / others.length);
32
+ others.forEach((k, i) => { next[k] = i === 0 ? residual - each * (others.length - 1) : each; });
33
+ } else {
34
+ let assigned = 0;
35
+ others.forEach((k, i) => {
36
+ const share = i === others.length - 1 ? residual - assigned : Math.round((comps[k] / oldSum) * residual);
37
+ next[k] = Math.max(0, share);
38
+ assigned += next[k];
39
+ });
40
+ }
41
+ const total = COMPOSITION_ORDER.reduce((s, k) => s + next[k], 0);
42
+ if (total !== 100) next[key] = Math.max(0, next[key] + (100 - total));
43
+ return next;
44
+ }
45
+
46
+ // ─── attribute caps ─────────────────────────────────────────────
47
+ export function attributeCap(attr, comps) {
48
+ const plant = comps.PLANTAE >= 30;
49
+ const mycel = comps.MYCELIUM >= 30;
50
+ const mineral = comps.MINERALIS >= 30;
51
+ const chitin = comps.CHITINARIA >= 30;
52
+
53
+ if (attr === 'NEURAL_COMPLEXITY') { if (plant) return 4; if (mycel) return 3; if (mineral) return 2; }
54
+ if (attr === 'METABOLIC_RATE') { if (mycel) return 4; if (mineral) return 0; }
55
+ if (attr === 'REGENERATION') { if (mineral) return 0; }
56
+ if (attr === 'MUSCLE_DENSITY') { if (mineral) return 2; }
57
+ if (attr === 'BUOYANCY') { if (mineral) return 1; }
58
+ if (attr === 'WATER_RETENTION') { if (chitin) return 6; }
59
+ return 10;
60
+ }
61
+
62
+ // ─── features ────────────────────────────────────────────────────
63
+ export const FEATURE_META = [
64
+ { type:'TOXIN_GLANDS', label:'Toxin Glands', category:'Offense', tags:['TOXIN'], baseCost:10, costMult:{CNIDARIA:0.5}, blurb:'DOT injection on hit. ARMOR resists; NUMB immune.' },
65
+ { type:'PIERCING_MOUTHPARTS', label:'Piercing Mouthparts', category:'Offense', tags:['PIERCE'], baseCost:10, blurb:'Burst damage; bypasses between-fight REGEN. ARMOR resists.' },
66
+ { type:'CRUSHING_MANDIBLES', label:'Crushing Mandibles', category:'Offense', tags:['CRUSH'], baseCost:10, blurb:'Bonus vs hard structures. SOFT absorbs; BRITTLE shatters (Γ—2.5).' },
67
+ { type:'SLASHING_BLADES', label:'Slashing Blades', category:'Offense', tags:['SLASH'], baseCost:10, blurb:'Strong vs unarmored. ARMOR resists.' },
68
+ { type:'ACID_SPRAY', label:'Acid Spray', category:'Offense', tags:['ACID'], baseCost:12, requires:{CNIDARIA:20}, blurb:'Ranged; ignores GRAPPLE range. REGEN out-heals; Mineralis immune.' },
69
+ { type:'ELECTRIC_DISCHARGE', label:'Electric Discharge', category:'Offense', tags:['ELECTRIC'], baseCost:15, requires:{ANIMALIA:20}, blurb:'Ignores ARMOR. INSULATED resists; CONDUCTIVE extra-vulnerable.' },
70
+ { type:'SONIC_SHRIEK', label:'Sonic Shriek', category:'Offense', tags:['SONIC'], baseCost:14, requires:{ANIMALIA:25}, blurb:'Ranged; uncounterable by Camouflage. Shatter (Γ—2.5) vs BRITTLE. SOFT absorbs.' },
71
+ { type:'GRAPPLE_TENDRILS', label:'Grapple Tendrils', category:'Offense', tags:['GRAPPLE'], baseCost:11, requires:{CNIDARIA:20}, blurb:'Locks target; negates Speed evasion. ARMOR and SLIME slip free.' },
72
+ { type:'SNAKE_FANGS', label:'Snake Fangs', category:'Offense', tags:['TOXIN','PIERCE'], baseCost:12, requires:{ANIMALIA:20}, blurb:'Toxin + pierce hybrid burst. Good vs most things except ARMOR.' },
73
+ { type:'SCORPION_TAIL', label:'Scorpion Tail', category:'Offense', tags:['TOXIN','PIERCE'], baseCost:13, requires:{CHITINARIA:20}, blurb:'Stinger with toxin. Reaches over armor joints.' },
74
+ { type:'BOMBADIER_SPRAY', label:'Bombardier Spray', category:'Offense', tags:['ACID'], baseCost:13, requires:{CHITINARIA:25}, blurb:'Boiling chemical acid. Bonus vs ARMOR; Mineralis immune.' },
75
+ { type:'DESERT_WORM_MAW', label:'Desert Worm Maw', category:'Offense', tags:['CRUSH','PIERCE'], baseCost:14, requires:{ANIMALIA:30}, blurb:'Ring of inward-curling teeth. Crush+pierce; terrifying vs FLESH and SOFT.' },
76
+ { type:'HARD_SHELL', label:'Hard Shell', category:'Defense', tags:[], baseCost:10, costMult:{CHITINARIA:0}, blurb:'Forces ARMOR. CRUSH and ACID are its weaknesses.' },
77
+ { type:'GELATINOUS_BODY', label:'Gelatinous Body', category:'Defense', tags:[], baseCost:10, costMult:{CNIDARIA:0}, blurb:'Forces SOFT. Absorbs CRUSH/SONIC; PIERCE/SLASH/TOXIN punish it.' },
78
+ { type:'SLIME_COATING', label:'Slime Coating', category:'Defense', tags:[], baseCost:8, requires:{CNIDARIA:15}, blurb:'SLIME modifier β€” escape chance vs GRAPPLE; small general dodge.' },
79
+ { type:'DUST_COATING', label:'Dust Coating', category:'Defense', tags:[], baseCost:9, blurb:'One guaranteed dodge per encounter. Skipped if attacker out-speeds; cleared by SONIC/ACID.' },
80
+ { type:'REGENERATIVE_FLESH', label:'Regenerative Flesh', category:'Defense', tags:[], baseCost:11, requires:{MYCELIUM:15}, blurb:'REGEN modifier β€” nullifies toxin/DOT between rounds. Useless vs single burst hits.' },
81
+ { type:'BIOLUMINESCENT_DETERRENT', label:'Bioluminescent Deterrent', category:'Defense', tags:[], baseCost:9, requires:{CNIDARIA:20}, blurb:'Flinch chance to interrupt attacker. Ignored by high Neural Complexity.' },
82
+ { type:'SPINY_RIDGE', label:'Spiny Ridge', category:'Defense', tags:[], baseCost:8, requires:{CHITINARIA:20}, blurb:'Reflects chunk of melee CRUSH/SLASH back. Piercing/ranged ignore it.' },
83
+ { type:'CAMOUFLAGE_PATTERNS', label:'Camouflage Patterns', category:'Defense', tags:[], baseCost:9, blurb:'Shrinks detection radius; dodge chance vs low-Neural attackers. Costs offense.' },
84
+ { type:'DRAGONFLY_WINGS', label:'Dragonfly Wings', category:'Mobility', tags:[], baseCost:15, requires:{ANIMALIA:30}, blurb:'AERIAL β€” immune to ground-only non-ranged attackers. Other fliers/ranged still hit.' },
85
+ { type:'MOTH_DUST_WINGS', label:'Moth Dust Wings', category:'Mobility', tags:[], baseCost:14, requires:{ANIMALIA:25}, blurb:'AERIAL + dust evasion. Softer than dragonfly wings but harder to lock onto.' },
86
+ { type:'BURROWING_CLAWS', label:'Burrowing Claws', category:'Mobility', tags:[], baseCost:10, blurb:'BURROWING β€” skip one encounter per phase. -Speed on open ground.' },
87
+ { type:'WEBBED_LIMBS', label:'Webbed Limbs', category:'Mobility', tags:[], baseCost:8, blurb:'AQUATIC β€” +speed in water; -speed on land/desert.' },
88
+ { type:'CILIA_PROPULSION', label:'Cilia Propulsion', category:'Mobility', tags:[], baseCost:6, requires:{CNIDARIA:20}, blurb:'AQUATIC-only microswimmer; useless on land.' },
89
+ { type:'JET_PROPULSION', label:'Jet Propulsion', category:'Mobility', tags:[], baseCost:11, requires:{CNIDARIA:30}, blurb:'AQUATIC burst-dash; brief high-speed with cooldown.' },
90
+ { type:'FLOWER_HEAD_LURE', label:'Flower Head Lure', category:'Sensory', tags:[], baseCost:10, requires:{PLANTAE:30}, blurb:'LURE β€” act first regardless of Speed, once per encounter. High-Neural attackers ignore it.' },
91
+ { type:'ECHINATION_PALPS', label:'Echination Palps', category:'Sensory', tags:[], baseCost:7, blurb:'Sees through Camouflage; +1 effective Neural Complexity for detection only.' },
92
+ { type:'THERMAL_PITS', label:'Thermal Pits', category:'Sensory', tags:[], baseCost:8, requires:{ANIMALIA:20}, blurb:'Detect warm-blooded prey in any visibility. Nullifies Camouflage vs warm targets.' },
93
+ { type:'VOMERO_NASAL_ORGAN', label:'Vomero-Nasal Organ', category:'Sensory', tags:[], baseCost:7, requires:{ANIMALIA:15}, blurb:'Scent-tracking; +detection radius. Mating gas detection.' },
94
+ ];
95
+
96
+ export const FEATURE_LOOKUP = Object.fromEntries(FEATURE_META.map(m => [m.type, m]));
97
+
98
+ export function featureGateReason(feat, comps) {
99
+ const meta = FEATURE_LOOKUP[feat];
100
+ if (!meta) return 'Unknown feature';
101
+ if (meta.requires) {
102
+ for (const [k, v] of Object.entries(meta.requires)) {
103
+ if ((comps[k] ?? 0) < v) return `Requires ${k} β‰₯ ${v}`;
104
+ }
105
+ }
106
+ if (meta.forbids) {
107
+ for (const [k, v] of Object.entries(meta.forbids)) {
108
+ if ((comps[k] ?? 0) >= v) return `Forbidden by ${k} β‰₯ ${v}`;
109
+ }
110
+ }
111
+ return null;
112
+ }
113
+
114
+ export function featureCost(feat, comps) {
115
+ const meta = FEATURE_LOOKUP[feat];
116
+ let cost = meta.baseCost;
117
+ if (meta.costMult) {
118
+ for (const [k, mult] of Object.entries(meta.costMult)) {
119
+ if ((comps[k] ?? 0) >= 30) cost *= mult;
120
+ }
121
+ }
122
+ return Math.round(cost);
123
+ }
124
+
125
+ // ─── structural type & modifiers ────────────────────────────────
126
+ export function determineStructuralType(state) {
127
+ if (state.features.includes('HARD_SHELL')) return 'ARMOR';
128
+ if (state.features.includes('GELATINOUS_BODY')) return 'SOFT';
129
+ const dom = dominantComposition(state.compositions);
130
+ if (dom) {
131
+ const free = COMPOSITION_META[dom].freeStructure;
132
+ if (free) return free;
133
+ }
134
+ return 'FLESH';
135
+ }
136
+
137
+ export function activeModifiers(state) {
138
+ const mods = new Set();
139
+ if (state.attributes.TOXIN_RESISTANCE >= 5) mods.add('NUMB');
140
+ if (state.attributes.INSULATION >= 5) mods.add('INSULATED');
141
+ if (state.compositions.CNIDARIA >= 30) mods.add('CONDUCTIVE');
142
+ if (state.compositions.MYCELIUM >= 30 || state.features.includes('REGENERATIVE_FLESH')) mods.add('REGEN');
143
+ if (state.features.includes('SLIME_COATING')) mods.add('SLIME');
144
+ if (state.features.includes('DRAGONFLY_WINGS') || state.features.includes('MOTH_DUST_WINGS')) mods.add('AERIAL');
145
+ if (state.features.includes('BURROWING_CLAWS')) mods.add('BURROWING');
146
+ if (state.features.includes('WEBBED_LIMBS') || state.features.includes('CILIA_PROPULSION') || state.features.includes('JET_PROPULSION')) mods.add('AQUATIC');
147
+ if (state.features.includes('FLOWER_HEAD_LURE')) mods.add('LURE');
148
+ return mods;
149
+ }
150
+
151
+ // ─── evolution points ───────────────────────────────────────────
152
+ export function getEvolutionPoints(state) {
153
+ let used = 0;
154
+ for (const [attrStr, val] of Object.entries(state.attributes)) {
155
+ const attr = attrStr;
156
+ const cap = attributeCap(attr, state.compositions);
157
+ const effectiveVal = Math.min(val, cap);
158
+ let costMult = 1;
159
+ if (state.compositions.PLANTAE >= 30 && attr === 'REGENERATION') costMult = 0.5;
160
+ if (state.compositions.MINERALIS >= 30 && attr === 'BONE_DENSITY') costMult = 0.5;
161
+ if (state.compositions.CHITINARIA >= 30 && attr === 'WATER_RETENTION') costMult = 0.8;
162
+ if (state.compositions.ANIMALIA >= 30 && attr === 'NEURAL_COMPLEXITY') costMult = 0.8;
163
+ if (state.compositions.CNIDARIA >= 30 && attr === 'BUOYANCY') costMult = 0.5;
164
+ if (state.compositions.MYCELIUM >= 30 && attr === 'REGENERATION') costMult = 0.5;
165
+ used += effectiveVal * 2 * costMult;
166
+ }
167
+ for (const f of state.features) { used += featureCost(f, state.compositions); }
168
+ let max = 100;
169
+ const dom = dominantComposition(state.compositions);
170
+ if (dom) max += Math.round((state.compositions[dom] - 30) * 0.5);
171
+ return { used: Math.round(used), max };
172
+ }
173
+
174
+ // ─── derived stats β€” with environment effects ─────────────────
175
+ export function getDerivedStats(state, biome) {
176
+ let offense = 10, defense = 10, speed = 20, hp = 100;
177
+ let weight = 20, energyDemand = 10, detection = 80, matingSpeed = 1.0;
178
+ let desiccationRate = 1.0, heatTolerance = 50, coldTolerance = 50;
179
+
180
+ const A = state.attributes;
181
+ offense += A.MUSCLE_DENSITY * 2;
182
+ weight += A.MUSCLE_DENSITY * 2;
183
+ energyDemand += A.MUSCLE_DENSITY * 1.5;
184
+
185
+ defense += A.BONE_DENSITY * 2;
186
+ weight += A.BONE_DENSITY * 2.5;
187
+ speed -= A.BONE_DENSITY * 1.5;
188
+
189
+ speed += A.METABOLIC_RATE * 2;
190
+ energyDemand += A.METABOLIC_RATE * 2;
191
+ heatTolerance += A.METABOLIC_RATE * 3;
192
+
193
+ hp += A.FAT_RESERVES * 5;
194
+ weight += A.FAT_RESERVES * 1.5;
195
+ speed -= A.FAT_RESERVES * 0.5;
196
+
197
+ energyDemand += A.NEURAL_COMPLEXITY * 1.5;
198
+ matingSpeed -= A.NEURAL_COMPLEXITY * 0.04;
199
+ detection += A.NEURAL_COMPLEXITY * 6;
200
+
201
+ energyDemand += A.REGENERATION * 2;
202
+ hp -= A.REGENERATION * 1;
203
+
204
+ coldTolerance += A.INSULATION * 5;
205
+ heatTolerance -= A.INSULATION * 2;
206
+ energyDemand += A.INSULATION;
207
+ speed -= A.INSULATION * 0.3;
208
+
209
+ weight += A.WATER_RETENTION * 0.5;
210
+ speed -= A.WATER_RETENTION * 0.2;
211
+ desiccationRate -= A.WATER_RETENTION * 0.08;
212
+
213
+ energyDemand += A.THERMAL_REGULATION * 0.8;
214
+ heatTolerance += A.THERMAL_REGULATION * 3;
215
+ coldTolerance += A.THERMAL_REGULATION * 3;
216
+
217
+ offense -= A.CAMOUFLAGE * 0.5;
218
+ detection -= A.CAMOUFLAGE * 4;
219
+ defense -= A.BUOYANCY * 0.4;
220
+
221
+ // composition
222
+ if (state.compositions.PLANTAE >= 30) hp += 20;
223
+ if (state.compositions.MYCELIUM >= 30) { hp -= 10; matingSpeed += 0.5; }
224
+ if (state.compositions.MINERALIS >= 30) { energyDemand = 0; weight += 30; speed -= 10; }
225
+
226
+ const mods = activeModifiers(state);
227
+ const isAerial = mods.has('AERIAL');
228
+ const isAquatic = mods.has('AQUATIC');
229
+
230
+ // biome effects
231
+ if (biome === 'UNDERWATER') {
232
+ speed += A.BUOYANCY * 2;
233
+ if (isAquatic) speed += 15;
234
+ if (isAerial) speed -= 15;
235
+ if (!isAquatic && state.compositions.CNIDARIA < 30 && A.BUOYANCY < 3) { hp -= 30; desiccationRate += 2; }
236
+ coldTolerance += 10;
237
+ } else {
238
+ if (isAquatic && !isAerial) speed -= 5;
239
+ if (isAerial) speed += 10;
240
+ if (biome === 'DESERT') {
241
+ if (A.WATER_RETENTION < 5) hp -= 20;
242
+ if (mods.has('SLIME')) { hp -= 15; desiccationRate += 0.5; }
243
+ if (state.compositions.CNIDARIA >= 30 && A.WATER_RETENTION < 5) { hp -= 40; desiccationRate += 1; }
244
+ heatTolerance += 10; coldTolerance -= 20;
245
+ }
246
+ if (biome === 'RAINFOREST') {
247
+ if (state.compositions.PLANTAE >= 30) hp += 20;
248
+ coldTolerance += 5;
249
+ }
250
+ }
251
+
252
+ if (weight > 50) {
253
+ speed -= (weight - 50) * 0.5;
254
+ energyDemand += (weight - 50) * 0.5;
255
+ }
256
+
257
+ const struct = determineStructuralType(state);
258
+ if (struct === 'ARMOR') { defense += 25; weight += 15; matingSpeed -= 0.1; }
259
+ if (struct === 'SOFT') { hp += 20; defense -= 5; }
260
+ if (struct === 'BRITTLE') { defense += 30; hp -= 10; }
261
+
262
+ if (energyDemand > 40 && state.compositions.PLANTAE < 30) {
263
+ hp -= (energyDemand - 40) * 2;
264
+ }
265
+
266
+ return {
267
+ offense: Math.round(offense), defense: Math.round(defense),
268
+ speed: Math.max(2, Math.round(speed)),
269
+ hp: Math.max(1, Math.round(hp)), weight: Math.round(weight),
270
+ energyDemand: Math.round(energyDemand), detection: Math.max(20, Math.round(detection)),
271
+ matingSpeed: Math.max(0.1, Math.round(matingSpeed * 100) / 100),
272
+ aquatic: isAquatic, aerial: isAerial,
273
+ desiccationRate: Math.max(0, Math.round(desiccationRate * 100) / 100),
274
+ heatTolerance: Math.round(heatTolerance), coldTolerance: Math.round(coldTolerance),
275
+ };
276
+ }
277
+
278
+ // ─── counter chart ──────────────────────────────────────────────
279
+ const COUNTER_CHART = {
280
+ TOXIN: { ARMOR: 0.4, SOFT: 1.6, BRITTLE: 1.0, FLESH: 1.0 },
281
+ PIERCE: { ARMOR: 0.4, SOFT: 1.6, BRITTLE: 1.0, FLESH: 1.0 },
282
+ CRUSH: { ARMOR: 1.6, SOFT: 0.4, BRITTLE: 2.5, FLESH: 1.0 },
283
+ SLASH: { ARMOR: 0.4, SOFT: 1.6, BRITTLE: 1.0, FLESH: 1.0 },
284
+ ACID: { ARMOR: 1.6, SOFT: 1.0, BRITTLE: 1.0, FLESH: 1.0 },
285
+ ELECTRIC: { ARMOR: 1.0, SOFT: 1.0, BRITTLE: 1.0, FLESH: 1.0 },
286
+ SONIC: { ARMOR: 1.0, SOFT: 0.4, BRITTLE: 2.5, FLESH: 1.0 },
287
+ GRAPPLE: { ARMOR: 0.4, SOFT: 1.0, BRITTLE: 0.4, FLESH: 1.6 },
288
+ };
289
+
290
+ // ─── combat resolution ─────────────────────────────────────────
291
+ export function resolveCombat(attacker, defender, biome, rng = Math.random) {
292
+ const att = getDerivedStats(attacker, biome);
293
+ const def = getDerivedStats(defender, biome);
294
+ const defStruct = determineStructuralType(defender);
295
+ const defMods = activeModifiers(defender);
296
+ const attMods = activeModifiers(attacker);
297
+ const notes = [];
298
+
299
+ let attackerFirst = true;
300
+ if (defMods.has('LURE') && attacker.attributes.NEURAL_COMPLEXITY < 5) {
301
+ attackerFirst = false; notes.push('Defender LURE overrides Speed');
302
+ } else if (def.speed > att.speed) {
303
+ attackerFirst = false;
304
+ }
305
+
306
+ const speedDiff = def.speed - att.speed;
307
+ let evasionChance = Math.max(0, Math.min(0.35, speedDiff / 40));
308
+ const attIsGroundOnly = !attMods.has('AERIAL');
309
+ const attHasRanged = attacker.features.some(f => {
310
+ const t = FEATURE_LOOKUP[f]?.tags ?? [];
311
+ return t.includes('SONIC') || t.includes('ACID') || t.includes('GRAPPLE');
312
+ });
313
+
314
+ if (defMods.has('AERIAL') && attIsGroundOnly && !attHasRanged) {
315
+ evasionChance = 1.0; notes.push('Defender AERIAL β€” ground attacker cannot reach');
316
+ }
317
+ if (defender.features.includes('DUST_COATING') && speedDiff > -10) {
318
+ evasionChance = Math.max(evasionChance, 0.9); notes.push('Dust coating pre-deployed');
319
+ } else if (defender.features.includes('DUST_COATING')) {
320
+ notes.push('Dust coating skipped β€” attacker too fast');
321
+ }
322
+
323
+ const evaded = rng() < evasionChance;
324
+ if (evaded) {
325
+ return {
326
+ won: false,
327
+ breakdown: {
328
+ attackerFirst, evasionChance, evaded,
329
+ effectiveOffense: 0, effectiveDefense: 0,
330
+ winProbability: 0, roll: 0, attackerWon: false,
331
+ tagsUsed: [], notes: [...notes, 'Evaded before contact'],
332
+ primaryTag: null, isShatter: false
333
+ },
334
+ };
335
+ }
336
+
337
+ const tagsUsed = [];
338
+ for (const f of attacker.features) {
339
+ const meta = FEATURE_LOOKUP[f];
340
+ if (meta?.tags.length) tagsUsed.push(...meta.tags);
341
+ }
342
+ const uniqueTags = Array.from(new Set(tagsUsed));
343
+
344
+ let bestEffOffense = att.offense;
345
+ let bestTag = null;
346
+ let bestMult = 1;
347
+
348
+ for (const tag of uniqueTags) {
349
+ let mult = COUNTER_CHART[tag][defStruct];
350
+ if (tag === 'TOXIN') {
351
+ if (defMods.has('NUMB')) { mult = 0; notes.push('Defender NUMB β€” Toxin negated'); }
352
+ else if (defMods.has('REGEN')) { mult *= 0.5; notes.push('Defender REGEN halves Toxin'); }
353
+ }
354
+ if (tag === 'ELECTRIC') {
355
+ if (defMods.has('INSULATED')) { mult *= 0.4; notes.push('Defender INSULATED resists Electric'); }
356
+ else if (defMods.has('CONDUCTIVE')) { mult *= 1.6; notes.push('Defender CONDUCTIVE vulnerable to Electric'); }
357
+ }
358
+ if (tag === 'ACID') {
359
+ if (defender.compositions.MINERALIS >= 30) { mult = 0; notes.push('Mineralis immune to Acid'); }
360
+ else if (defMods.has('REGEN')) { mult *= 0.5; notes.push('REGEN out-heals Acid'); }
361
+ }
362
+ if (tag === 'GRAPPLE') {
363
+ if (defMods.has('SLIME')) { mult *= 0.4; notes.push('Defender SLIME slips Grapple'); }
364
+ }
365
+ const eff = att.offense * mult;
366
+ if (eff > bestEffOffense) { bestEffOffense = eff; bestTag = tag; bestMult = mult; }
367
+ }
368
+ if (bestTag) notes.push(`Best attack tag: ${bestTag} (Γ—${bestMult.toFixed(2)})`);
369
+ else notes.push('No offensive tags β€” bare-body clash');
370
+
371
+ let effDefense = def.defense;
372
+ if (bestTag === 'ELECTRIC' && !defMods.has('INSULATED') && defStruct === 'ARMOR') {
373
+ effDefense = Math.max(0, effDefense - 25); notes.push('Electric ignores ARMOR bonus');
374
+ }
375
+ if (defender.features.includes('SPINY_RIDGE') && (bestTag === 'CRUSH' || bestTag === 'SLASH')) {
376
+ bestEffOffense *= 0.7; notes.push('Spiny Ridge reflects 30% melee');
377
+ }
378
+ if (defender.features.includes('BIOLUMINESCENT_DETERRENT') && attacker.attributes.NEURAL_COMPLEXITY < 5 && rng() < 0.3) {
379
+ bestEffOffense *= 0.4; notes.push('Bioluminescent flinch interrupted attack');
380
+ }
381
+
382
+ const winProbability = bestEffOffense / (bestEffOffense + effDefense || 1);
383
+ const roll = rng();
384
+ const attackerWon = attackerFirst ? roll < winProbability : roll < winProbability * 0.85;
385
+
386
+ const isShatter = bestTag !== null && bestMult >= 2.0 && defStruct === 'BRITTLE';
387
+
388
+ return {
389
+ won: attackerWon,
390
+ breakdown: {
391
+ attackerFirst, evasionChance, evaded,
392
+ effectiveOffense: Math.round(bestEffOffense),
393
+ effectiveDefense: Math.round(effDefense),
394
+ winProbability: Math.round(winProbability * 1000) / 1000,
395
+ roll: Math.round(roll * 1000) / 1000, attackerWon, tagsUsed: uniqueTags, notes,
396
+ primaryTag: bestTag, isShatter
397
+ },
398
+ };
399
+ }
400
+
401
+ // ─── breeding ───────────────────────────────────────────────────
402
+ export function breedOffspring(a, b) {
403
+ const mix = (x, y) => Math.round(((x + y) / 2) * 0.85);
404
+ const avgComp = {};
405
+ for (const k of COMPOSITION_ORDER) avgComp[k] = mix(a.compositions[k], b.compositions[k]);
406
+
407
+ const sum = COMPOSITION_ORDER.reduce((s, k) => s + avgComp[k], 0);
408
+ if (sum > 0) for (const k of COMPOSITION_ORDER) avgComp[k] = Math.round((avgComp[k] / sum) * 100);
409
+ const total = COMPOSITION_ORDER.reduce((s, k) => s + avgComp[k], 0);
410
+ if (total !== 100) avgComp.ANIMALIA = Math.max(0, avgComp.ANIMALIA + (100 - total));
411
+
412
+ return {
413
+ compositions: avgComp,
414
+ attributes: Object.fromEntries(
415
+ Object.keys(a.attributes).map(k => [k, mix(a.attributes[k], b.attributes[k])])
416
+ ),
417
+ features: a.features.length >= b.features.length ? a.features.slice() : b.features.slice(),
418
+ socialType: a.socialType,
419
+ };
420
+ }
421
+
422
+ // ─── initial state ──────────────────────────────────────────────
423
+ export const INITIAL_STATE = {
424
+ compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
425
+ attributes: {
426
+ WATER_RETENTION: 0, INSULATION: 0, MUSCLE_DENSITY: 0, BONE_DENSITY: 0,
427
+ FAT_RESERVES: 0, METABOLIC_RATE: 0, NEURAL_COMPLEXITY: 0, THERMAL_REGULATION: 0,
428
+ BUOYANCY: 0, CAMOUFLAGE: 0, REGENERATION: 0, TOXIN_RESISTANCE: 0,
429
+ },
430
+ features: [],
431
+ socialType: 'SOLITARY',
432
+ };