-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame_engine_v2_homeostatic.js
More file actions
4164 lines (3564 loc) · 168 KB
/
game_engine_v2_homeostatic.js
File metadata and controls
4164 lines (3564 loc) · 168 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MORTALITY LOTTERY - Game Engine v2: Homeostatic State System
// Replaces simple tag-based model with rich, interconnected state
// Enables complex event chains, realistic progression, and emergent gameplay
const { getGlobalBaseline, getAdjustedProbability, getSuicideMethodsForRegion } = require('./systems/global_statistics_v2.js');
const { shouldBeEmployed, getUnemploymentPenalty } = require('./systems/employment_by_region.js');
const { calculateHouseholdCost, calculateHouseholdIncome, calculateHouseholdCashFlow, getPovertyStatus } = require('./systems/cost_of_living.js');
const { getEducationStage, shouldAttendEducation, getEducationCost, getStressFromIncome } = require('./systems/education_system.js');
const { getCancerIncidence, getStageProgression, getCancerPenalties, shouldDieFromCancer, checkRemission } = require('./systems/cancer_system.js');
const { getAccidentIncidence, getAccidentDisability, shouldDieFromAccident } = require('./systems/accidents_system.js');
const { getSubstanceInitiation, getStageProgression: getSubstanceStageProgression, getSubstancePenalties, checkOverdose, checkTreatmentSuccess } = require('./systems/substance_abuse_system.js');
const { processRetirement } = require('./systems/retirement_system.js');
const {
checkChronicDiseaseOnset,
checkCongenitalCondition,
checkAcuteCrisis,
applyAcuteCrisis,
applyDiagnosisToRelationships,
applyCaregiverBurden,
RELATIONSHIP_IMPACTS,
CHRONIC_DISEASES,
CONGENITAL_CONDITIONS
} = require('./systems/health_crisis_system.js');
const DeathTracer = require('./systems/death_trace_system.js');
const { TemporalEffectsSystem } = require('./systems/temporal_effects_system.js');
const RelationshipsSystem = require('./systems/relationships_system.js');
const HousingSystem = require('./systems/housing_system.js');
class MortalityGameV2 {
constructor(birthCards, familyCards, eventCards, deathCards, tracer = null) {
this.birthCards = birthCards;
this.familyCards = familyCards;
this.eventCards = eventCards;
this.deathCards = deathCards;
this.player = null;
this.deathTracer = tracer || new DeathTracer(); // Enable death tracing by default
this.temporalEffects = new TemporalEffectsSystem(); // Temporal effects system
this.relationshipsSystem = new RelationshipsSystem(); // Relationships system
this.housingSystem = new HousingSystem(); // NEW: Housing system
}
/**
* Enable or replace the death tracer
*/
setDeathTracer(tracer) {
this.deathTracer = tracer;
}
/**
* Disable death tracing (for performance)
*/
disableDeathTracing() {
this.deathTracer = null;
}
// ============================================================================
// REALISTIC DEMOGRAPHICS DATA
// ============================================================================
// Regional marriage age statistics (UN/World Bank data)
getMarriageAgeStats(birthCardName) {
const stats = {
"Nordic Country": { median: 31, min: 22, max: 45 },
"Western Europe": { median: 30, min: 22, max: 45 },
"Japan/South Korea": { median: 31, min: 25, max: 45 },
"North America - Middle Class": { median: 28, min: 20, max: 45 },
"Eastern Europe": { median: 26, min: 20, max: 40 },
"Urban China": { median: 27, min: 23, max: 42 },
"Urban Latin America": { median: 25, min: 18, max: 38 },
"Southeast Asia": { median: 23, min: 15, max: 35 },
"Rural India": { median: 21, min: 14, max: 32 },
"Sub-Saharan Africa": { median: 19, min: 12, max: 30 },
"Middle East / North Africa": { median: 22, min: 15, max: 35 },
"Rural Southeast Asia": { median: 21, min: 12, max: 32 }
};
return stats[birthCardName] || { median: 24, min: 18, max: 40 }; // Default fallback
}
// Calculate marriage probability for given age and region
getMarriageProbabilityAtAge(birthCardName, age) {
const stats = this.getMarriageAgeStats(birthCardName);
const { median, min, max } = stats;
// Outside realistic range = 0% probability
if (age < min || age > max) return 0;
// Gaussian-ish curve centered on median
const distanceFromMedian = Math.abs(age - median);
const maxDistance = Math.max(median - min, max - median);
const probability = Math.pow(1 - (distanceFromMedian / maxDistance), 2);
return Math.max(0, probability);
}
// Get regional starting wealth variation (Phase 2A calibration)
// Poorest regions: 2-5 resources, middle: 10-15, wealthy: 20-30
getRegionalWealthRange(birthCardName) {
const wealthMap = {
// Poorest (subsistence)
"Sub-Saharan Africa": { min: 2, max: 8 },
"Rural South Asia": { min: 3, max: 10 },
"Active War Zone": { min: 1, max: 5 },
"Fragile/Post-Conflict State": { min: 2, max: 8 },
// Middle income (developing)
"Urban South Asia": { min: 8, max: 15 },
"Urban Latin America": { min: 10, max: 18 },
"Southeast Asia": { min: 8, max: 15 },
"Urban Sub-Saharan Africa": { min: 8, max: 12 },
"Rural Latin America": { min: 5, max: 12 },
"Middle East - Stable": { min: 10, max: 18 },
// Upper middle (developed)
"Eastern Europe": { min: 12, max: 22 },
"Urban China": { min: 15, max: 25 },
"Rural Southeast Asia": { min: 8, max: 15 },
"Japan/South Korea": { min: 20, max: 30 },
// Wealthy (high development)
"North America - Middle Class": { min: 20, max: 35 },
"Western Europe": { min: 22, max: 35 },
"Nordic Country": { min: 25, max: 40 }
};
return wealthMap[birthCardName] || { min: 12, max: 20 }; // Default middle
}
// Get random wealth value in regional range
getRegionalWealth(birthCardName) {
const range = this.getRegionalWealthRange(birthCardName);
return Math.max(0, range.min + Math.floor(Math.random() * (range.max - range.min + 1)));
}
// ============================================================================
// PHASE 1: PLAYER STATE INITIALIZATION
// ============================================================================
createPlayer(birthCard, familyCard, demographics = {}) {
const sex = demographics.sex || (Math.random() > 0.5 ? "male" : "female");
const birthYear = new Date().getFullYear();
this.player = {
// ========== DEMOGRAPHICS (Immutable after birth) ==========
demographics: {
sex: sex, // "male" | "female"
birthYear: birthYear,
age: 0,
birthRegion: birthCard.name,
ethnicity: demographics.ethnicity || null,
lifeExpectancy: birthCard.lifeExpectancy || 73
},
// ========== HEALTH (Homeostatic systems) ==========
health: {
physical: {
current: birthCard.effects?.statSet?.survival || 75,
baseline: birthCard.effects?.statSet?.survival || 75,
drift: 3, // Recovery rate per year
chronic: [] // ["diabetes", "asthma"]
},
mental: {
// Mental health baseline varies by age - children born with clean slate
// Ages 0-5: 88 (healthy childhood baseline)
// Ages 6-11: 82 (pre-adolescence, still resilient)
// Ages 12-17: 75 (adolescence, mental health onset period)
// Ages 18+: 65 (adult baseline with more vulnerability)
current: this.getMentalHealthBaseline(0), // Age 0 at birth
baseline: this.getMentalHealthBaseline(0),
drift: 4, // Recover 4 points per year toward baseline (faster recovery)
chronic: [], // ["depression", "ptsd", "anxiety", "bipolar"]
episodeDuration: 0, // Months in current episode
treatmentStatus: "none", // "none" | "medicated" | "therapy" | "hospitalized"
suicideRisk: 0, // 0-100, separate tracking
lastCrisisAge: null, // When last acute crisis occurred
suicideHistory: [] // [{age, method, survived}]
},
reproductive: {
fertile: true, // Both men and women start fertile
pregnant: false,
childrenBorn: 0,
menarche: sex === "female" ? false : null,
menopause: false
},
// ========== CANCER SYSTEM ==========
cancer: {
active: false, // Currently diagnosed with cancer
type: null, // "breast", "lung", "colon", "prostate", "cervical", "liver", "pancreas", "ovarian"
stage: 0, // 1-4, or 0 if no active cancer
yearsSinceDiagnosis: 0, // Years since diagnosis
inRemission: false, // In remission but not cured
remissionYears: 0, // Years in remission (resets to 0 if recurrence)
treatmentAccess: false, // Can access treatment
hasRecurred: false, // Has cancer recurred before
complications: [], // ["metastasis", "treatmentToxicity", "recurrence"]
lastStageProgression: 0, // Last year stage progressed
history: [] // [{type, stage, yearsSinceDiagnosis, outcome}]
},
// ========== CHRONIC DISEASES SYSTEM ==========
chronic: {
active: [], // [{disease, onsetAge, severity, complications: []}]
diabetes: null, // {type, stage, yearsSinceDiagnosis, medicated}
heartDisease: null, // {stage, yearsSinceDiagnosis, complications}
autoimmune: null, // {type, flareFrequency}
chronicPain: null, // {severity, location, medications}
treatmentAccess: false, // Can access treatment for chronic diseases
history: [] // [{disease, onsetAge, resolved}]
},
// ========== CONGENITAL CONDITIONS SYSTEM ==========
congenital: {
hasCondition: false, // True if born with condition
condition: null, // "cerebralPalsy", "downSyndrome", "autism", etc
severity: null, // "mild", "moderate", "severe"
requiresCaregiver: false, // Does condition require ongoing care
impacts: {
physical: 0, // Reduction in physical capacity
employment: 0, // Employment disadvantage multiplier
education: 0, // Education barrier
mobility: null, // null, "restricted", "severe"
intellectual: 0 // Intellectual disability impact
},
treatmentAccess: false, // Can access treatment/accommodation
surgeryNeeded: false, // For conditions like cleft palate
surgeryCompleted: false
}
},
// ========== ADDICTION SYSTEM ==========
addiction: {
substance: null, // "alcohol", "opioids", "cannabis", "stimulants", null
stage: "none", // "none" | "casual" | "regular" | "dependent"
monthsDuration: 0,
frequencyPerMonth: 0,
treatmentStatus: "none", // "none" | "inpatient" | "outpatient" | "recovered"
craving: 0, // 0-100
history: [] // [{substance, stagedSince, yearsActive}]
},
// ========== CRIME/LEGAL SYSTEM ==========
legal: {
citizenship: true,
documented: true,
criminalRecord: false,
convictionCount: 0,
imprisonmentHistory: [], // [{age, duration, crime}]
currentlyImprisoned: false,
imprisonmentEndAge: null,
reoffenseRisk: 0 // 0-100, reset after time out of prison
},
// ========== RELATIONSHIPS (State machine) ==========
relationships: {
birthFamily: {
// Track birth family conditions for cascade analysis
income: null, // Will be set based on regional wealth
education: null, // Will be estimated from birth card
stability: familyCard.name.includes("Stable") ? "stable" : familyCard.name.includes("Conflict") ? "conflict" : "moderate",
resources: this.getRegionalWealth(birthCard.name) // Birth family starting resources
},
parents: {
mother: {
alive: true,
present: Math.random() > 0.1, // 90% have mother present
ageAtBirth: 15 + Math.floor(Math.random() * 35), // 15-50 years old at player birth
currentAge: null, // Set after birth age is known
relationship: 70 + Math.random() * 20
},
father: {
alive: true,
present: Math.random() > 0.25, // 75% have father present
ageAtBirth: 18 + Math.floor(Math.random() * 40), // 18-58 years old at player birth
currentAge: null, // Set after birth age is known
relationship: 60 + Math.random() * 20
}
},
bestFriend: null, // Single best friend (can die)
siblings: this.generateSiblings(),
partner: {
exists: false,
married: false,
relationship: 0,
since: null,
children: [] // Biologically with this partner
},
children: [], // All children (biological, adopted, step)
social: {
friends: 1,
community: 50, // 0-100 integration into community
isolation: false,
married: false
}
},
// ========== ECONOMICS (Homeostatic) ==========
economics: {
income: {
current: 0, // Per-year income
baseline: birthCard.effects?.resourceMod || 10,
employed: false,
occupation: null,
unemploymentMonths: 0, // Months spent unemployed
lastEmploymentChange: 0 // Age when employment status last changed
},
resources: {
// Regional wealth variation for Phase 2A calibration
current: this.getRegionalWealth(birthCard.name),
baseline: this.getRegionalWealth(birthCard.name),
drift: -5 // Negative = expenses exceed income (modifies yearly)
},
debt: 0,
assets: [] // ["home", "vehicle"]
},
// ========== DEVELOPMENT (Progressive) ==========
development: {
education: {
literate: false,
yearsCompleted: 0,
level: "none", // none, primary, secondary, tertiary, university
inSchool: false,
schoolQuality: 0, // 0-100, affects learning speed
stages: [], // Track education stages: [{stage: "primary", completed: true, years: 6}]
cost: 0, // Annual education cost
stress: 0, // Stress from being in school
familyBudgetAtAge18: null, // Frozen at age 18: represents total family wealth available for tertiary education decisions
},
skills: [], // ["farming", "trade", "music", "medicine"]
cognitive: {
current: 70,
baseline: 70,
developmentPhase: "infancy", // infancy, childhood, adolescent, adult, decline
decline: 0 // Cognitive decline in old age
}
},
// ========== CIRCUMSTANCES (State flags) ==========
circumstances: {
location: {
urban: birthCard.profileTags?.includes("urban") || false,
displaced: false,
refugee: false,
migrant: false,
climate: "temperate" // Affects disease/survival
},
housing: {
status: "stable", // stable, unstable, homeless
ownership: false,
quality: 50 // 0-100
},
vulnerability: {
disabled: false,
elderly: false,
dependent: true, // Age-based, initially true for children
caregiver: false,
orphan: false, // Both parents dead
halfOrphan: false // One parent dead
}
},
// ========== SURVIVAL & LEGACY ==========
survival: birthCard.effects?.statSet?.survival || 75,
alive: true,
folded: false,
causeOfDeath: null,
lifeExpectancy: birthCard.lifeExpectancy || 73,
// ========== GAME STATE ==========
birthCards: [birthCard, familyCard],
eventHistory: [],
profileTags: [...(birthCard.profileTags || [])],
// ========== AGENCY (For compatibility) ==========
agency: 0
};
// Apply family card effects to initial state
this.applyFamilyCardEffects(familyCard);
// Apply birth card base effects
this.applyBirthCardEffects(birthCard);
// ========== CHECK FOR CONGENITAL CONDITIONS AT BIRTH ==========
const region = this.mapRegionForStatistics(birthCard.name);
const maternalAge = this.player.relationships.parents.mother.ageAtBirth || 30;
const congenitalCheck = checkCongenitalCondition(this.player, region, maternalAge);
if (congenitalCheck.hasCondition) {
const condition = CONGENITAL_CONDITIONS[congenitalCheck.condition];
this.player.health.congenital.hasCondition = true;
this.player.health.congenital.condition = congenitalCheck.condition;
this.player.health.congenital.severity = condition.severity;
this.player.health.congenital.requiresCaregiver = condition.requiresCaregiver;
// Apply impacts to player
if (condition.impacts) {
this.player.health.congenital.impacts = { ...condition.impacts };
// Apply physical health impact if present
if (condition.impacts.physical) {
this.player.health.physical.current = Math.max(10, this.player.health.physical.current + condition.impacts.physical);
this.player.health.physical.baseline = Math.max(10, this.player.health.physical.baseline + condition.impacts.physical);
}
// Apply lifespan reduction
if (condition.impacts.lifespan) {
this.player.demographics.lifeExpectancy = Math.max(30, this.player.demographics.lifeExpectancy + condition.impacts.lifespan);
}
}
// Set treatment access based on region
const treatmentAccess = condition.treatmentAccess || {};
this.player.health.congenital.treatmentAccess = treatmentAccess[region] || 0;
// Flag surgery needs for specific conditions
if (congenitalCheck.condition === 'cleftPalateLip') {
this.player.health.congenital.surgeryNeeded = true;
}
}
// Initialize parent current ages (same as age at birth initially since player is age 0)
this.player.relationships.parents.mother.currentAge = this.player.relationships.parents.mother.ageAtBirth;
this.player.relationships.parents.father.currentAge = this.player.relationships.parents.father.ageAtBirth;
// Initialize death tracing if enabled
if (this.deathTracer) {
this.deathTracer.initializeLifeLog(this.player);
}
return this.player;
}
// ============================================================================
// HELPER: Generate initial siblings
// Based on regional demographics (UN data on average children per woman)
// ============================================================================
generateSiblings() {
const birthRegion = this.player?.demographics?.birthRegion || "North America - Middle Class";
// Average family sizes by region (UN World Population data)
const familySizes = {
"Nordic Country": { avg: 1.4, max: 4 },
"Western Europe": { avg: 1.5, max: 4 },
"Japan/South Korea": { avg: 1.1, max: 3 },
"North America - Middle Class": { avg: 1.9, max: 5 },
"Eastern Europe": { avg: 1.4, max: 4 },
"Urban China": { avg: 1.3, max: 2 }, // One-child policy legacy
"Urban Latin America": { avg: 1.8, max: 5 },
"Southeast Asia": { avg: 2.3, max: 6 },
"Urban South Asia": { avg: 2.1, max: 7 },
"Rural South Asia": { avg: 3.8, max: 12 },
"Rural Sub-Saharan Africa": { avg: 5.2, max: 15 },
"Urban Sub-Saharan Africa": { avg: 3.1, max: 10 },
"Middle East / North Africa": { avg: 2.9, max: 10 },
"Sub-Saharan Africa": { avg: 4.7, max: 14 },
"Active War Zone": { avg: 3.5, max: 12 }
};
const stats = familySizes[birthRegion] || familySizes["North America - Middle Class"];
// Generate sibling count using Poisson-like distribution around regional average
let siblingCount = Math.max(0, Math.round(stats.avg + (Math.random() - 0.5) * 2));
siblingCount = Math.min(siblingCount, stats.max); // Cap at regional maximum
const siblings = [];
let playerBirthOrder = Math.floor(Math.random() * (siblingCount + 1)); // 0 = oldest, siblingCount = youngest
for (let i = 0; i < siblingCount; i++) {
// Age gap: if player is oldest, all siblings are younger
// if player is youngest, all siblings are older
// if player is middle, mix of older and younger
let ageGap;
if (i < playerBirthOrder) {
// Older siblings
ageGap = -(Math.floor(Math.random() * 6) + 1); // 1-6 years older
} else if (i >= playerBirthOrder) {
// Younger siblings
ageGap = Math.floor(Math.random() * 6) + 1; // 1-6 years younger
}
// Age-appropriate survival rates (higher child mortality in poor regions)
let survivalRate = 0.95;
if (["Rural Sub-Saharan Africa", "Sub-Saharan Africa", "Rural South Asia", "Active War Zone"].includes(birthRegion)) {
survivalRate = 0.85; // 15% infant/child mortality in high-mortality regions
} else if (["Urban South Asia", "Southeast Asia", "Urban Sub-Saharan Africa"].includes(birthRegion)) {
survivalRate = 0.90;
}
siblings.push({
age: ageGap,
alive: Math.random() < survivalRate,
relationship: 70 + Math.random() * 20,
sex: Math.random() > 0.5 ? "male" : "female",
birthOrder: i // 0 = oldest, increasing for younger
});
}
return siblings;
}
// ============================================================================
// HELPER: Apply family card effects to base state
// ============================================================================
applyFamilyCardEffects(familyCard) {
if (!familyCard.effects) return;
// Adjust survival
if (familyCard.effects.survivalMod) {
this.player.health.physical.baseline += familyCard.effects.survivalMod;
this.player.health.physical.current += familyCard.effects.survivalMod;
this.player.survival += familyCard.effects.survivalMod;
}
// Adjust resources
if (familyCard.effects.resourceMod) {
this.player.economics.resources.current += familyCard.effects.resourceMod;
this.player.economics.resources.baseline += familyCard.effects.resourceMod;
}
// Set birth family income (estimate based on region + resource modifier)
const birthRegion = this.player.demographics.birthRegion;
const resourceMod = familyCard.effects?.resourceMod || 0;
// Base income by region
let birthFamilyIncome = 30; // Default middle-income
if (birthRegion.includes('Nordic')) {
birthFamilyIncome = 50 + (resourceMod * 2); // Higher baseline for Nordic
} else if (birthRegion.includes('Western Europe') || birthRegion.includes('North America')) {
birthFamilyIncome = 45 + (resourceMod * 2);
} else if (birthRegion.includes('Sub-Saharan') || birthRegion.includes('Fragile')) {
birthFamilyIncome = 10 + resourceMod;
} else {
birthFamilyIncome = 30 + (resourceMod * 1.5);
}
// Add variance
birthFamilyIncome *= (0.7 + Math.random() * 0.6); // 70%-130% variation
this.player.relationships.birthFamily.income = Math.round(Math.max(5, birthFamilyIncome));
// Estimate parent education (correlated with income)
if (birthFamilyIncome > 60) {
this.player.relationships.birthFamily.education = "tertiary";
} else if (birthFamilyIncome > 30) {
this.player.relationships.birthFamily.education = "secondary";
} else if (birthFamilyIncome > 15) {
this.player.relationships.birthFamily.education = "primary";
} else {
this.player.relationships.birthFamily.education = "none";
}
// Adjust relationships based on family structure
if (familyCard.name.includes("Single")) {
const parent = Math.random() > 0.5 ? "mother" : "father";
const otherParent = parent === "mother" ? "father" : "mother";
this.player.relationships.parents[otherParent].present = false;
this.player.relationships.parents[otherParent].alive = Math.random() > 0.3;
// Single parent families typically have lower income
this.player.relationships.birthFamily.income *= 0.6;
}
if (familyCard.name.includes("Orphan")) {
this.player.relationships.parents.mother.alive = false;
this.player.relationships.parents.father.alive = false;
this.player.health.mental.current -= 20;
this.player.health.mental.baseline -= 10;
// Orphans have very low family support
this.player.relationships.birthFamily.income = Math.min(10, this.player.relationships.birthFamily.income);
}
if (familyCard.name.includes("Abuse")) {
this.player.health.mental.current -= 25;
this.player.relationships.parents.mother.relationship = Math.random() * 30;
this.player.relationships.parents.father.relationship = Math.random() * 30;
this.player.health.mental.chronic.push("trauma");
}
// Set initial employment status based on age/gender/region
this.player.economics.income.employed = shouldBeEmployed(
this.player.demographics.age,
this.player.demographics.sex,
this.mapRegionForStatistics(this.player.demographics.birthRegion)
);
// Clamp values
this.clampPlayerStats();
}
applyBirthCardEffects(birthCard) {
if (birthCard.profileTags) {
this.player.circumstances.location.urban = birthCard.profileTags.includes(
"urban"
);
}
}
clampPlayerStats(player = this.player) {
const p = player;
p.health.physical.current = Math.max(
0,
Math.min(100, p.health.physical.current)
);
p.health.physical.baseline = Math.max(
1,
Math.min(100, p.health.physical.baseline)
);
p.health.mental.current = Math.max(
0,
Math.min(100, p.health.mental.current)
);
p.health.mental.baseline = Math.max(
1,
Math.min(100, p.health.mental.baseline)
);
p.survival = Math.max(1, Math.min(99, p.survival));
p.economics.resources.current = Math.max(
0,
p.economics.resources.current
);
// Update orphan status based on parent state
const motherAlive = p.relationships.parents.mother.alive;
const fatherAlive = p.relationships.parents.father.alive;
if (!motherAlive && !fatherAlive) {
p.circumstances.vulnerability.orphan = true;
p.circumstances.vulnerability.halfOrphan = false;
} else if (!motherAlive || !fatherAlive) {
p.circumstances.vulnerability.halfOrphan = true;
p.circumstances.vulnerability.orphan = false;
} else {
p.circumstances.vulnerability.orphan = false;
p.circumstances.vulnerability.halfOrphan = false;
}
}
// ============================================================================
// PHASE 2: PREREQUISITE EVALUATION ENGINE
// ============================================================================
canEventOccur(event, player = this.player) {
if (!event.requires) return true;
return this.evaluateRequirements(event.requires, player);
}
evaluateRequirements(reqs, player) {
if (reqs.all) {
return reqs.all.every((req) => this.evaluateSingleRequirement(req, player));
}
if (reqs.any) {
return reqs.any.some((req) => this.evaluateSingleRequirement(req, player));
}
return this.evaluateSingleRequirement(reqs, player);
}
evaluateSingleRequirement(req, player) {
// Handle simple key-value requirements: { "demographics.sex": "female" }
for (const [key, value] of Object.entries(req)) {
const playerValue = this.getNestedValue(player, key);
// Handle range checks (e.g., "age": "15-45")
if (typeof value === "string" && value.includes("-")) {
const [min, max] = value.split("-").map(Number);
if (playerValue < min || playerValue > max) return false;
continue;
}
// Handle comparison operators (e.g., "age": ">18", "resources": "<10")
if (typeof value === "string" && value.match(/^[<>=]/)) {
const match = value.match(/^([<>=]+)(.+)$/);
if (!match) return false;
const [, operator, compareValue] = match;
const numValue = isNaN(compareValue) ? compareValue : Number(compareValue);
if (!this.compareValues(playerValue, operator, numValue)) return false;
continue;
}
// Handle array checks (e.g., "health.physical.chronic": "has diabetes")
if (typeof value === "string" && value.startsWith("has ")) {
const item = value.replace("has ", "");
if (!Array.isArray(playerValue) || !playerValue.includes(item))
return false;
continue;
}
// Handle younger sibling checks
if (typeof value === "string" && value === "has younger") {
if (!Array.isArray(playerValue)) return false;
const hasYounger = playerValue.some((sib) => sib.age > 0);
if (!hasYounger) return false;
continue;
}
// Handle parent death eligibility: "relationships.parents.mother.canDie": true
// A parent can only die if they're alive AND statistically plausible for their age
if (key === "relationships.parents.mother.canDie" || key === "relationships.parents.father.canDie") {
const parent = key.includes("mother") ? player.relationships.parents.mother : player.relationships.parents.father;
const parentDead = !parent.alive;
// Get survival odds for parent's current age
const survivalOdds = this.getParentSurvivalOdds(parent.currentAge);
const mortalityOdds = 1 - survivalOdds; // Probability parent dies this year
// If value is true, parent can die only if:
// - Parent is alive, AND
// - We pass the mortality probability check (probabilistic)
if (value === true) {
if (parentDead || Math.random() > mortalityOdds) return false;
} else if (value === false) {
// Parent cannot die if already dead OR if we fail the mortality check
if (!parentDead && Math.random() <= mortalityOdds) return false;
}
continue;
}
// Handle divorce eligibility: "relationships.partner.canDivorce": true
// Marriage can only end if married AND probabilistically (based on duration)
if (key === "relationships.partner.canDivorce") {
const partner = player.relationships.partner;
const isMarried = partner.exists && partner.married;
if (!isMarried) return false; // Can't divorce if not married
// Calculate marriage duration
const marriageDuration = player.demographics.age - (partner.since || player.demographics.age);
// Get survival odds for marriage (complement = divorce odds)
const survivalOdds = this.getMarriageSurvivalOdds(marriageDuration);
const divorceOdds = 1 - survivalOdds; // Probability divorce happens this year
// If value is true, divorce can happen only if:
// - Marriage exists AND
// - We pass the divorce probability check (probabilistic)
if (value === true) {
if (!isMarried || Math.random() > divorceOdds) return false;
} else if (value === false) {
// Divorce cannot happen if not married OR if we fail the divorce check
if (isMarried && Math.random() <= divorceOdds) return false;
}
continue;
}
// Handle marriage eligibility: "relationships.partner.canMarry": true
// Can only marry at realistic age for region, AND not already married
if (key === "relationships.partner.canMarry") {
const partner = player.relationships.partner;
const isAlreadyMarried = partner.exists && partner.married;
if (isAlreadyMarried) return false; // Can't marry twice
// Get marriage probability for this age and region
const marriageProbability = this.getMarriageProbabilityAtAge(
player.demographics.birthRegion,
player.demographics.age
);
// If value is true, can marry only if:
// - Not already married, AND
// - Age is within realistic range for region AND probabilistically
if (value === true) {
if (marriageProbability === 0 || Math.random() > marriageProbability) return false;
} else if (value === false) {
// Cannot marry if already married OR if in an age where marriage is realistic
if (!isAlreadyMarried && Math.random() <= marriageProbability) return false;
}
continue;
}
// Direct equality
if (playerValue !== value) return false;
}
return true;
}
getNestedValue(obj, path) {
const keys = path.split(".");
let value = obj;
for (const key of keys) {
if (value === null || value === undefined) return undefined;
value = value[key];
}
return value;
}
compareValues(playerValue, operator, compareValue) {
switch (operator) {
case ">":
return playerValue > compareValue;
case "<":
return playerValue < compareValue;
case ">=":
return playerValue >= compareValue;
case "<=":
return playerValue <= compareValue;
case "==":
case "===":
return playerValue === compareValue;
case "!=":
case "!==":
return playerValue !== compareValue;
default:
return false;
}
}
setNestedValue(obj, path, value) {
const keys = path.split(".");
const lastKey = keys.pop();
let target = obj;
for (const key of keys) {
if (!(key in target)) target[key] = {};
target = target[key];
}
target[lastKey] = value;
}
// ============================================================================
// PHASE 3: HOMEOSTATIC DRIFT SYSTEMS
// ============================================================================
processYearEnd(player = this.player) {
if (!player.alive) return { alive: false };
// 1. Age up
player.demographics.age++;
player.age = player.demographics.age; // Keep in sync
// 1a. Update mental health baseline as they age (childhood resilience → adolescent vulnerability → adult baseline)
const newBaseline = this.getMentalHealthBaseline(player.demographics.age);
if (newBaseline !== player.health.mental.baseline) {
player.health.mental.baseline = newBaseline;
// Gradually move toward new baseline (don't shock them with huge changes)
player.health.mental.current = Math.max(
newBaseline - 20, // Allow some variance from baseline
Math.min(100, player.health.mental.current + (newBaseline - player.health.mental.baseline) * 0.5)
);
}
// 1b. Age parents
if (player.relationships.parents.mother.ageAtBirth !== null) {
player.relationships.parents.mother.currentAge =
player.relationships.parents.mother.ageAtBirth + player.demographics.age;
}
if (player.relationships.parents.father.ageAtBirth !== null) {
player.relationships.parents.father.currentAge =
player.relationships.parents.father.ageAtBirth + player.demographics.age;
}
// 1c. Update employment status based on age/gender/region and random turnover
// DEBUG DISABLED - uncomment to trace income changes
if (player.demographics.age >= 18 && player.demographics.age <= 25) {
console.log(`[${player.demographics.age}] Before updateEmploymentStatus: employed=${player.economics.income.employed}, income=${player.economics.income.current}`);
}
this.updateEmploymentStatus(player);
if (player.demographics.age >= 18 && player.demographics.age <= 25) {
console.log(`[${player.demographics.age}] After updateEmploymentStatus: employed=${player.economics.income.employed}, income=${player.economics.income.current}`);
}
// 1c2. Process retirement (NEW: retirement decisions, pension income, living standards)
const region = this.mapRegionForStatistics(player.demographics.birthRegion);
// if (player.demographics.age >= 19 && player.demographics.age <= 26) {
// console.log(`[${player.demographics.age}] Before processRetirement: income=${player.economics.income.current}`);
// }
processRetirement(player, region);
// if (player.demographics.age >= 19 && player.demographics.age <= 26) {
// console.log(`[${player.demographics.age}] After processRetirement: income=${player.economics.income.current}`);
// }
// 1c3. Check for chronic disease onset (age 15+)
if (player.demographics.age >= 15) {
const diseaseCheck = checkChronicDiseaseOnset(player, region);
if (diseaseCheck.hasDiease) {
// NEW DIAGNOSIS
const disease = CHRONIC_DISEASES[diseaseCheck.disease];
// Only diagnose if not already have this disease
const alreadyHas = player.health.chronic.active.some(d => d.disease === diseaseCheck.disease);
if (!alreadyHas) {
// Add to active diseases
player.health.chronic.active.push({
disease: diseaseCheck.disease,
onsetAge: player.demographics.age,
severity: diseaseCheck.severity || 'moderate',
yearsSinceDiagnosis: 0,
complications: []
});
// Record in history
player.health.chronic.history.push({
disease: diseaseCheck.disease,
onsetAge: player.demographics.age,
resolved: false
});
// Initial mental health hit from diagnosis
player.health.mental.current = Math.max(10, player.health.mental.current - 15);
// Apply relationship impacts (family stress, caregiver decisions, etc)
applyDiagnosisToRelationships([player], player);
}
}
}
// 1c4. Check for acute crises (stroke, heart attack, kidney injury - age 30+)
if (player.demographics.age >= 30) {
const crisisCheck = checkAcuteCrisis(player, region);
if (crisisCheck.hasCrisis) {
// ACUTE EVENT
const crisisName = crisisCheck.crisis;
const outcome = crisisCheck.outcome;
// Record acute crisis
if (!player.health.crises) {
player.health.crises = {};
}
if (!player.health.crises[crisisName]) {
player.health.crises[crisisName] = {
count: 0,
lastOutcome: null
};
}
player.health.crises[crisisName].count++;
player.health.crises[crisisName].lastOutcome = outcome;
player.health.crises[crisisName].lastAge = player.demographics.age;
// Apply crisis impacts based on outcome
if (outcome === 'death') {
// Will be caught in death check below
player.alive = false;
player.causeOfDeath = crisisCheck.crisis === 'stroke' ? 'Stroke' :
crisisCheck.crisis === 'heartAttack' ? 'Heart Attack' : 'Kidney Failure';
return { alive: false, cause: player.causeOfDeath };
}
// Non-fatal outcomes
if (crisisCheck.disabilityImpacts) {
if (crisisCheck.disabilityImpacts.physical) {
player.health.physical.current = Math.max(5,
player.health.physical.current + crisisCheck.disabilityImpacts.physical);
}
if (crisisCheck.disabilityImpacts.lifespan) {
player.demographics.lifeExpectancy = Math.max(30,
player.demographics.lifeExpectancy + crisisCheck.disabilityImpacts.lifespan);
}
}
if (crisisCheck.healthImpacts) {
if (crisisCheck.healthImpacts.physical) {
player.health.physical.current = Math.max(5,
player.health.physical.current + crisisCheck.healthImpacts.physical);
}
if (crisisCheck.healthImpacts.lifespan) {
player.demographics.lifeExpectancy = Math.max(30,
player.demographics.lifeExpectancy + crisisCheck.healthImpacts.lifespan);
}
}
// Mental health trauma from crisis
player.health.mental.current = Math.max(10,
player.health.mental.current - 25);
// Disability means employment may change
if (outcome === 'permanent_disability' || outcome === 'chronic_heart_failure') {
if (player.employment?.status === 'employed') {
player.employment.status = 'unemployed';
}
} else if (outcome === 'partial_recovery') {
if (player.employment?.status === 'employed') {
// 60% chance of downgrade to part-time
if (Math.random() < 0.6) {
player.employment.status = 'part-time';
}
}
}
// If crisis causes caregiver needs, family may step in
if (crisisCheck.causesCaregiver) {
applyDiagnosisToRelationships([player], player);
}
}
}
// 1d. Update education status (compulsory until 16, optional after)
this.updateEducationStatus(player);
// 1e. Process temporal effects (NEW: event duration system)
const temporalMods = this.temporalEffects.processEffects(player);
// Apply temporal effect modifications to player stats
if (temporalMods.mentalHealth !== 0) {
player.health.mental.current = Math.max(0, Math.min(100,