-
Notifications
You must be signed in to change notification settings - Fork 1
/
civSimTribes.go
2935 lines (2617 loc) · 99.7 KB
/
civSimTribes.go
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
package genworldvoronoi
import (
"fmt"
"log"
"math"
"math/rand"
"sort"
"strings"
"github.com/Flokey82/genbiome"
"github.com/Flokey82/genworldvoronoi/geo"
"github.com/Flokey82/go_gens/genlanguage"
"github.com/Flokey82/go_gens/genreligion"
goastar "github.com/beefsack/go-astar"
)
// combatSuccessSatisfaction is the value that will be added to the satisfaction of the tribes
// after a combat outcome.
const combatSuccessSatisfaction = 0.5
// settlingSuccessSatisfaction is the value that will be added to the satisfaction of the tribes
// after a settling outcome.
const settlingSuccessSatisfaction = 0.5
// starvationSatisfaction is the value that will be added to the satisfaction of the tribes if people are starving.
const starvationSatisfaction = -0.5
// migrationSuccessSatisfaction is the value that will be added to the satisfaction of the tribes if they migrate.
const migrationSuccessSatisfaction = 0.2
// tribeSplitForcedSatisfaction is the value that will be added to the satisfaction of the tribes if they split
// because of overpopulation.
const tribeSplitForcedSatisfaction = -0.5
// tribeSplitVoluntarySatisfaction is the value that will be added to the satisfaction of the nwe tribe if one splits.
const tribeSplitVoluntarySatisfaction = 0.2
// Convert the distance between two regions to kilometers.
const unitDistToKm = 6371.0 // km
func (m *Civ) InitSimTribes() {
// Set up the suitability of the regions for population growth.
m.calculateSuitability()
// Initialize exhaustion of resources.
// This will keep track of the exhaustion of resources for each region.
m.SoilExhaustion = make([]float64, m.NumRegions)
// Find the best place for the cradle of civilization.
// Since we only have one species for now (humans), we will just start
// with a 'steppe' region, and then expand from there incrementally.
// Now we pick a suitable region to start with (steppe/grassland).
bestRegion := m.pickCradleOfCivilization(genbiome.WhittakerModBiomeTemperateGrassland)
if bestRegion == -1 {
panic("no suitable region found")
}
// Initial population.
const initialPopulation = 100
m.Tribes = make([]*Tribe, 0, 1)
// Start with one tribe.
t := NewTribe(m.getNextTribeID(), bestRegion, initialPopulation)
m.Tribes = append(m.Tribes, t)
}
func (m *Civ) LogTribes() {
for _, t := range m.Tribes {
if t.hasPath() {
log.Printf("%s f%d -> t%d (%d rem)", t.String(), t.Path.From, t.Path.To, t.Path.NumRemaining())
} else {
log.Printf("%s", t.String())
}
// Log current leadership.
if t.Leadership != nil {
log.Printf(" Leader: %s", t.Leadership.String())
}
// Log all factions.
for _, f := range t.Factions {
log.Printf(" Faction: %s", f.String())
}
// Log all skills.
for sk := range t.Skills {
log.Printf(" %s", sk.Name)
}
if t.Settlement != nil {
log.Printf(" Settlement: %s", t.Settlement.String())
}
if t.CityState != nil {
log.Printf(" City state: %s", t.CityState.String())
}
if t.Empire != nil {
log.Printf(" Empire: %s", t.Empire.String())
}
// Log preferred biome
preferredBiome, preferredStrength := t.LastBiomes.Preferred()
log.Printf(" Preferred biome: %s (%.2f)", preferredBiome, preferredStrength)
// Log current region max population.
log.Printf(" Current Max population: %d", t.currentRegionMaxPop)
log.Printf(" Max population: %d", t.regionMaxPop)
log.Printf(" Resources (local):")
localRes := m.getResources(t.RegionID, false)
localRes.Log()
log.Printf(" Resources (regional):")
regRes := m.getResources(t.RegionID, true)
regRes.remove(localRes).Log()
log.Printf(" Resouces (storage):")
t.ResourceStorage.Log()
}
// Log the city states.
for _, cs := range m.CityStates {
cs.Log()
}
// Log the empires.
for _, e := range m.Empires {
e.Log()
}
}
type regionProp struct {
biome HackyBiome
riverProx bool
lakeProx bool
oceanProx bool
mountainProx bool
}
func (r *regionProp) Log() {
log.Printf(" biome: %s", r.biome)
log.Printf(" river proximity: %v", r.riverProx)
log.Printf(" lake proximity: %v", r.lakeProx)
log.Printf(" ocean proximity: %v", r.oceanProx)
log.Printf(" mountain proximity: %v", r.mountainProx)
}
type ResourceStorage struct {
maxStorage int
Wood [geo.ResMaxWoods]int
Stone [geo.ResMaxStones]int
Metal [geo.ResMaxMetals]int
Gem [geo.ResMaxGems]int
Various [geo.ResMaxVarious]int
}
func newResourceStorage(maxStorage int) *ResourceStorage {
return &ResourceStorage{
maxStorage: maxStorage,
}
}
func (rs *ResourceStorage) add(r localResouces) {
for _, w := range r.getWood() {
rs.Wood[w]++
if rs.Wood[w] > rs.maxStorage {
rs.Wood[w] = rs.maxStorage
}
}
for _, s := range r.getStones() {
rs.Stone[s]++
if rs.Stone[s] > rs.maxStorage {
rs.Stone[s] = rs.maxStorage
}
}
for _, m := range r.getMetals() {
rs.Metal[m]++
if rs.Metal[m] > rs.maxStorage {
rs.Metal[m] = rs.maxStorage
}
}
for _, g := range r.getGems() {
rs.Gem[g]++
if rs.Gem[g] > rs.maxStorage {
rs.Gem[g] = rs.maxStorage
}
}
for _, v := range r.getVarious() {
rs.Various[v]++
if rs.Various[v] > rs.maxStorage {
rs.Various[v] = rs.maxStorage
}
}
}
func (rs *ResourceStorage) Log() {
log.Printf(" Resources:")
log.Printf(" Wood:")
for i, w := range rs.Wood {
if w > 0 {
log.Printf(" %s: %d", geo.WoodToString(i), w)
}
}
log.Printf(" Stone:")
for i, s := range rs.Stone {
if s > 0 {
log.Printf(" %s: %d", geo.StoneToString(i), s)
}
}
log.Printf(" Metal:")
for i, m := range rs.Metal {
if m > 0 {
log.Printf(" %s: %d", geo.MetalToString(i), m)
}
}
log.Printf(" Gem:")
for i, g := range rs.Gem {
if g > 0 {
log.Printf(" %s: %d", geo.GemToString(i), g)
}
}
log.Printf(" Various:")
for i, v := range rs.Various {
if v > 0 {
log.Printf(" %s: %d", geo.VariousToString(i), v)
}
}
}
type localResouces struct {
wood, stones, metals, gems, various byte
}
func (r localResouces) isAny() bool {
return r.wood != 0 || r.stones != 0 || r.metals != 0 || r.gems != 0 || r.various != 0
}
func getResources(res byte, max int) []int {
var resSlice []int
for i := 0; i < max; i++ {
if res&(1<<uint(i)) != 0 {
resSlice = append(resSlice, i)
}
}
return resSlice
}
func (r localResouces) getGems() []int {
return getResources(r.gems, geo.ResMaxGems)
}
func (r localResouces) getMetals() []int {
return getResources(r.metals, geo.ResMaxMetals)
}
func (r localResouces) getStones() []int {
return getResources(r.stones, geo.ResMaxStones)
}
func (r localResouces) getWood() []int {
return getResources(r.wood, geo.ResMaxWoods)
}
func (r localResouces) getVarious() []int {
return getResources(r.various, geo.ResMaxVarious)
}
func (r localResouces) String() string {
var s string
resToString := func(label string, res byte, max int, strFunc func(int) string) string {
if res == 0 {
return ""
}
var resStr string
resStr += label + ": "
for i := 0; i < max; i++ {
if res&(1<<uint(i)) != 0 {
resStr += strFunc(i) + " "
}
}
return resStr
}
s += resToString("Wood", r.wood, geo.ResMaxWoods, geo.WoodToString)
s += resToString("Stone", r.stones, geo.ResMaxStones, geo.StoneToString)
s += resToString("Metal", r.metals, geo.ResMaxMetals, geo.MetalToString)
s += resToString("Gem", r.gems, geo.ResMaxGems, geo.GemToString)
s += resToString("Various", r.various, geo.ResMaxVarious, geo.VariousToString)
return s
}
func (r localResouces) add(other localResouces) localResouces {
r.wood |= other.wood
r.stones |= other.stones
r.metals |= other.metals
r.gems |= other.gems
r.various |= other.various
return r
}
func (r localResouces) remove(other localResouces) localResouces {
r.wood &^= other.wood
r.stones &^= other.stones
r.metals &^= other.metals
r.gems &^= other.gems
r.various &^= other.various
return r
}
func (r localResouces) Log() {
logEntry := func(name string, res byte, max int, strFunc func(int) string) {
for i := 0; i < max; i++ {
if res&(1<<uint(i)) != 0 {
log.Printf(" %s: %s", name, strFunc(i))
}
}
}
logEntry("Wood", r.wood, geo.ResMaxWoods, geo.WoodToString)
logEntry("Stone", r.stones, geo.ResMaxStones, geo.StoneToString)
logEntry("Metal", r.metals, geo.ResMaxMetals, geo.MetalToString)
logEntry("Gem", r.gems, geo.ResMaxGems, geo.GemToString)
logEntry("Various", r.various, geo.ResMaxVarious, geo.VariousToString)
}
func (m *Civ) getResources(r int, incNeighbors bool) localResouces {
var rsc localResouces
rsc.wood = m.Geo.Resources.Wood[r]
rsc.stones = m.Geo.Resources.Stones[r]
rsc.metals = m.Geo.Resources.Metals[r]
rsc.gems = m.Geo.Resources.Gems[r]
rsc.various = m.Geo.Resources.Various[r]
if incNeighbors {
for _, nb := range m.R_circulate_r(rNbs, r) {
rsc.wood |= m.Geo.Resources.Wood[nb]
rsc.stones |= m.Geo.Resources.Stones[nb]
rsc.metals |= m.Geo.Resources.Metals[nb]
rsc.gems |= m.Geo.Resources.Gems[nb]
rsc.various |= m.Geo.Resources.Various[nb]
}
}
return rsc
}
// Take note of the cultures, city states, empires that need to be updated.
type simState struct {
m *Civ
newTribes []*Tribe
tribeAtRegion []*Tribe
isCity map[int]bool
cities []*City
nodeCache map[int]*MigrationTile
// visitedPathSeg will store how often path segments (neighboring regions connected by a trade route)
// have been used
visitedPathSeg map[[2]int]int
maxElevation float64
steepness []float64
biomeFunc func(int) int
arableLandFunc func(int) float64
climateFunc func(int) float64
}
// wasVisited returns how often the path segment between the two given regions has been used.
func (s *simState) wasVisited(i, j int) int {
return s.visitedPathSeg[getSegment(i, j)]
}
func (s *simState) getTile(i int) *MigrationTile {
// Make sure we re-use pre-existing nodes.
n, ok := s.nodeCache[i]
if ok {
return n
}
// If we have no cached node for this index,
// create a new one.
n = &MigrationTile{
steepness: s.steepness,
r: s.m,
index: i,
getTile: s.getTile,
wasVisited: s.wasVisited,
maxElevation: s.maxElevation,
isCity: s.isCity,
tribeAtRegion: s.tribeAtRegion,
}
s.nodeCache[i] = n
return n
}
// moveTribe moves the tribe to the new region.
func (s *simState) moveTribe(t *Tribe, r int) {
// If the tribe is at the old region, remove it.
if s.tribeAtRegion[t.RegionID] == t {
s.tribeAtRegion[t.RegionID] = nil
}
// Move the tribe to the new region.
t.RegionID = r
if s.tribeAtRegion[r] != nil && s.tribeAtRegion[r] != t {
log.Printf("Tribe %s has moved to region %d, but it is already occupied by tribe %s", t.String(), r, s.tribeAtRegion[r].String())
panic(fmt.Sprintf("region %d is already occupied by tribe %s", r, s.tribeAtRegion[r].String()))
}
s.tribeAtRegion[t.RegionID] = t
}
// switchTribes switches the current regions of the two tribes.
func (s *simState) switchTribes(t1, t2 *Tribe) {
// Switch the regions of the two tribes.
region1 := t1.RegionID
region2 := t2.RegionID
// HACK: Nil the tribe at the old region.
// This will prevent a panic in moveTribe.
// We need to debug duplicate tribes at the same region.
if s.tribeAtRegion[region1] != t1 {
panic(fmt.Sprintf("tribe %s is not at region %d", t1.String(), region1))
}
if s.tribeAtRegion[region2] != t2 {
panic(fmt.Sprintf("tribe %s is not at region %d", t2.String(), region2))
}
s.tribeAtRegion[region1] = nil
s.tribeAtRegion[region2] = nil
s.moveTribe(t1, region2)
s.moveTribe(t2, region1)
}
// getRegionProp returns the properties of the region.
func (s *simState) getRegionProp(r int) regionProp {
// TODO: Find better way to determine mountain proximity. 0.3 is very low.
return regionProp{
biome: HackyBiome(s.biomeFunc(r)),
riverProx: s.m.IsRegRiver(r),
lakeProx: s.m.lakeProxFunc(r),
oceanProx: s.m.oceanProxFunc(r),
mountainProx: s.m.Elevation[r] > 0.3,
}
}
func (s *simState) printRegionInfo(r int) {
log.Printf("Region %d:", r)
rProp := s.getRegionProp(r)
rProp.Log()
// Print Gems.
res := s.m.getResources(r, true)
res.Log()
}
// getRegMultiplier returns the suitability of the region for the tribe.
// This takes in account the preferences of the tribe.
// A higher overlap between the region properties and the tribe preferences
// will result in a higher multiplier, since their survival chances are higher.
func (s *simState) getRegMultiplier(t *Tribe, r int) float64 {
return t.compareSuitability(s.getRegionProp(r))
}
// Calculate the economic value of the region.
// TODO: Direct neighbors should also be taken into account.
func (s *simState) getRegEconomicMultiplier(r int) float64 {
multiplier := 0.0
// Take into account arable land, which allows for agriculture.
multiplier = max(multiplier, s.arableLandFunc(r))
// Alternative we should allow for livestock to be a viable option.
// TODO: Create a fitness function for livestock in general.
multiplier = max(multiplier, s.climateFunc(r))
multiplier = max(multiplier, 0.5) // Minimum value.
res := s.m.getResources(r, true)
// Add a bonus for non-essential resources.
// NOTE: These optional resources should give a base bonus if present.
if res.metals != 0 {
val := float64(res.metals) / (1 << geo.ResMaxMetals)
val = math.Sqrt(val) // Sqrt to make it less linear.
val += 0.2 // Base bonus.
val = min(val, 1.0) // Limit to 1.0.
multiplier = max(multiplier, val)
}
if res.gems != 0 {
val := float64(res.gems) / (1 << geo.ResMaxGems)
val = math.Sqrt(val) // Sqrt to make it less linear.
val += 0.2 // Base bonus.
val = min(val, 1.0) // Limit to 1.0.
multiplier = max(multiplier, val)
}
if res.various != 0 {
val := float64(res.various) / (1 << geo.ResMaxVarious)
val = math.Sqrt(val) // Sqrt to make it less linear.
val += 0.2 // Base bonus.
val = min(val, 1.0) // Limit to 1.0.
multiplier = max(multiplier, val)
}
// Penalize if the region doesn't have resources the tribe needs.
// We need wood for fuel, construction, and tools.
if res.wood == 0 {
multiplier -= 0.2
}
// We need stones for construction and tools.
if res.stones == 0 {
multiplier -= 0.2
}
return multiplier
}
// Calculate the maximum sustainable population for the region.
//
// This depends on:
// - max population for the region
// - soil exhaustion
// - preferences (via multiplier)
//
// TODO: This should also depend on ...
// - skills
// - culture
// - settlement (nomadic, settled, etc.)
func (s *simState) calcMaxPopPerRegion(t *Tribe, r int) int {
baseVal := float64(s.m.maxPopReg(r) - int(s.m.SoilExhaustion[r]))
if baseVal <= 0 {
return 0
}
multiplier := s.getRegMultiplier(t, r)
return int(baseVal * multiplier)
}
// calcTheoreticalMaxPopPerRegion calculates the theoretical maximum population for the region.
// This is the same as calcMaxPopPerRegion, but without the soil exhaustion.
func (s *simState) calcTheoreticalMaxPopPerRegion(t *Tribe, r int) int {
baseVal := float64(s.m.maxPopReg(r))
if baseVal <= 0 {
return 0
}
multiplier := s.getRegMultiplier(t, r)
return int(baseVal * multiplier)
}
func (s *simState) handleTrade(t *Tribe) {
// TODO: Figure out what we actually need and what we have in excess.
const tradeRadius = 900.0 // km
// Create a list of cities that are close enough to trade with.
type cityTrade struct {
city *City
dist float64
}
var tradeCities []*cityTrade
for _, c := range s.cities {
if c.ID == t.RegionID {
continue
}
dist := s.m.Geo.GetDistance(t.RegionID, c.ID) * unitDistToKm
if dist < tradeRadius {
tradeCities = append(tradeCities, &cityTrade{city: c, dist: dist})
}
}
// Sort the trade cities by distance.
sort.Slice(tradeCities, func(i, j int) bool {
return tradeCities[i].dist < tradeCities[j].dist
})
// NOTE: This is only about resources.
type cityTradeProposal struct {
city *City
dist float64 // Distance to the city.
exp localResouces // Resources that are subject to trade.
imp localResouces // Resources that are needed.
}
compareResources := func(a, b int) (exp, imp localResouces) {
// Determine what resources we have and what resources we need.
aRes := s.m.getResources(a, true)
bRes := s.m.getResources(b, true)
imp = bRes.remove(aRes)
exp = aRes.remove(bRes)
return
}
var tradeProposals []*cityTradeProposal
// Loop through all the trade cities and propose trades.
// If we have resources that the other city needs, we propose a trade for export.
// If the other city has resources that we need, we propose a trade for import.
for _, tc := range tradeCities {
// Determine what resources we have and what resources we need.
exp, imp := compareResources(t.RegionID, tc.city.ID)
tradeProposals = append(tradeProposals, &cityTradeProposal{
city: tc.city,
exp: exp,
imp: imp,
dist: tc.dist,
})
}
// Log the trade proposals.
for _, tp := range tradeProposals {
log.Printf("!!!%s has proposed a trade with %s, dist %.2f", t.String(), tp.city.String(), tp.dist)
if tp.exp.isAny() {
log.Printf(" Export: %s", tp.exp.String())
}
if tp.imp.isAny() {
log.Printf(" Import: %s", tp.imp.String())
}
score := t.Settlement.compare(tp.city)
log.Printf(" Score: %.2f", score)
}
}
func (s *simState) handleResources(t *Tribe) {
// Here is what we could do:
// - Feed our people.
// - Produce weapons for hunting.
// - Produce tools for crafting.
// TODO:
// - Calculate suitability for hunting, gathering, herding, farming, etc.
biome := HackyBiome(s.biomeFunc(t.RegionID))
precipitation := s.m.Geo.Rainfall
_, maxElev := minMax(s.m.Elevation)
getGatheringScore := func(r int) float64 {
regSteepness := s.steepness[r]
regPrecipitation := precipitation[r] * geo.MaxPrecipitation * 100
regTemperature := s.m.GetRegTemperature(r, maxElev)
// Gathering is scored from 0 to 1.0.
// Less steepness is better for gathering.
// - at 1.0 steepness, the gathering score will be the minimum.
// - at 0.0 steepness, the gathering score will be (up to) the maximum.
gatheringSteepnessVal := 1.0 - regSteepness
// Gathering gets worse with lower precipitation.
// - at 0mm precipitation, the gathering score will be the minimum.
// - at 1000mm (and above), the gathering score will be (possibly) the maximum.
gatheringPrecipitationVal := min(regPrecipitation, 1000) / 1000
// Gathering gets worse with lower temperature.
// - at 0°C, the gathering score will be the minimum.
// - at 30°C, the gathering score will be (possibly) the maximum.
// - above 30°C, the gathering score will reduce again.
gatheringTemperatureVal := max(regTemperature, 0) / 30
if regTemperature > 30 {
gatheringTemperatureVal = 1.0 - min((regTemperature-30)/30, 1.0)
}
// The base value is 0.2.
regGathering := 0.2 + 0.8*gatheringSteepnessVal*gatheringPrecipitationVal*gatheringTemperatureVal
// There is a disadvantage in snow, desert, cold desert.
if biome == genbiome.WhittakerModBiomeSnow || biome == genbiome.WhittakerModBiomeSubtropicalDesert || biome == genbiome.WhittakerModBiomeColdDesert {
regGathering *= 0.5
}
return regGathering
}
getHuntingScore := func(r int) float64 {
regSteepness := s.steepness[r]
regPrecipitation := precipitation[r] * geo.MaxPrecipitation * 100
regTemperature := s.m.GetRegTemperature(r, maxElev)
// Hunting is scored from 0 to 1.0.
// Less steepness is better for hunting, but the minimum is higher than for gathering.
// - at 1.0 steepness, the hunting score will be the minimum.
// - at 0.0 steepness, the hunting score will be (up to) the maximum.
huntingSteepnessVal := 1.0 - regSteepness
// Hunting gets a little worse with lower precipitation.
// - at 0mm precipitation, the hunting score will be a little lower (40%).
// - at 1000mm, the hunting score will be (possibly) the maximum.
// - above 1000mm, the hunting score will reduce again.
huntingPrecepVal := 1.0
if regPrecipitation <= 1000 {
huntingPrecepVal = (regPrecipitation / 1000)
} else {
huntingPrecepVal = 1.0 - min(((regPrecipitation-1000)/1000), 1.0)
}
// Hunting gets a little worse with lower temperature.
// - at 0°C, the hunting score will be a little lower (40%).
// - at 30°C, the hunting score will be (possibly) the maximum.
// - above 30°C, the hunting score will reduce again.
huntingTempVal := 1.0
if regTemperature <= 30 {
huntingTempVal = (max(regTemperature, 0) / 30)
} else {
huntingTempVal = 1.0 - min(((regTemperature-30)/30), 1.0)
}
// The base value is 0.4.
regHunting := 0.4 + 0.6*huntingSteepnessVal*huntingPrecepVal*huntingTempVal
// There is a disadvantage in (dense) forests.
if biome == genbiome.WhittakerModBiomeTemperateRainforest || biome == genbiome.WhittakerModBiomeTropicalRainforest {
regHunting *= 0.5
}
return regHunting
}
regHunting := getHuntingScore(t.RegionID)
possibleFoodHuntingPerPersonMax := 5.0
possibleFoodHuntingPerPersonMin := 1.0
regGathering := getGatheringScore(t.RegionID)
possibleFoodGatheringPerPersonMax := 3.0
possibleFoodGatheringPerPersonMin := 1.0
// Calculate the food production for hunting and gathering.
foodHuntingPerPerson := possibleFoodHuntingPerPersonMin + (possibleFoodHuntingPerPersonMax-possibleFoodHuntingPerPersonMin)*regHunting
foodGatheringPerPerson := possibleFoodGatheringPerPersonMin + (possibleFoodGatheringPerPersonMax-possibleFoodGatheringPerPersonMin)*regGathering
log.Printf("!!!%s is hunting: %.2f, gathering: %.2f.", t.String(), regHunting, regGathering)
// Calculate how much food the tribe can produce.
// Half of the population is available for hunting.
// The rest might be too young, too old.
//availablePopulationHunter := float64(t.Population) * 0.5
// 90% of the population is available for gathering since
// gathering is less dangerous or physically demanding.
availablePopulationGatherer := float64(t.Population) * 0.9
// The ratio of the scores will determine how many are spent on hunting and how many on gathering.
// The rest will be spent on farming.
// huntingToGatheringRatio := regHunting / regGathering
// TODO: Also weigh the composition by the preference of the tribe.
popHunting := float64(t.Population) / (foodHuntingPerPerson + availablePopulationGatherer - foodGatheringPerPerson)
popGathering := availablePopulationGatherer - popHunting
foodHunting := popHunting * foodHuntingPerPerson
foodGathering := popGathering * foodGatheringPerPerson
// Calculate the food production for gathering.
log.Printf("!!!%s is producing food: %d total; %d from hunting (%d people), %d from gathering (%d people).", t.String(), int(foodHunting+foodGathering), int(foodHunting), int(popHunting), int(foodGathering), int(popGathering))
// Produce food, mainly to feed our population, but also keep some in storage.
// m.Suitability[t.RegionID]
// Check if we have enough resources to build what we want to build.
// How do we know what we need?
// - Ongoing consumption of goods and resources?
// - What do we need to produce?
// - What do we need to trade?
// TODO: We also need a resource sink. What do we spend resources on?
// - Food
// - Tools
// - Weapons
// - Buildings
// - Trade
// - Diplomacy
// Produce goods?
// - Tools
// - Weapons
// - Buildings
// Generate resources based on the local resources.
// If we aren't settled, we only can gather resources from the region we are in.
if t.Type == TribeTypeNomadic {
res := s.m.getResources(t.RegionID, false)
t.ResourceStorage.add(res)
return
}
// TODO: Introduce storage for settlements, city states, and empires.
res := s.m.getResources(t.RegionID, true)
t.ResourceStorage.add(res)
}
// HANDLE NOMADIC TRIBES HERE.
//
// Nomadic tribes will move around and settle in different regions, depending on their preferences
// and suitability of the regions (what population can be sustained in the region).
//
// If the most prosperous neighbor region cannot sustain the entire tribe, the tribe will split into
// two or more tribes.
func (s *simState) handleNomadicTribe(t *Tribe) {
// We look at all neighboring regions and move to the most suitable region.
// Considerations:
// - We do not move into a region that is already occupied.
// - We do not move into a region that is not suitable for the tribe.
// Calculate the max population for each neighboring region.
neigbors := s.m.R_circulate_r(rNbs, t.RegionID)
maxPopPerRegion := make([]int, len(neigbors))
neighborIndices := make([]int, len(neigbors))
for i, nb := range neigbors {
neighborIndices[i] = i
// We only consider regions that are not ocean regions and are unoccupied.
if s.m.Elevation[nb] > 0 && s.tribeAtRegion[nb] == nil {
maxPopPerRegion[i] = s.calcMaxPopPerRegion(t, nb)
}
}
// Sort the neighbor indices by max population.
sort.Slice(neighborIndices, func(i, j int) bool {
return maxPopPerRegion[neighborIndices[i]] > maxPopPerRegion[neighborIndices[j]]
})
// Start with the most suitable region and check if the entire tribe can move there.
// If not, we need to split the tribe into two tribes and move the remaining tribe to the next suitable region.
tCurrent := t
for _, idx := range neighborIndices {
nb := neigbors[idx]
if s.tribeAtRegion[nb] != nil {
continue // The region is already occupied.
}
// Get the max population for the region.
nbMaxPop := maxPopPerRegion[idx]
if nbMaxPop <= 0 {
break // We ran out of suitable regions.
}
// Check if the entire tribe can move to the new region.
if nbMaxPop >= tCurrent.Population {
// Move the tribe here and be done.
s.moveTribe(tCurrent, nb)
// TODO: The satisfaction should depend on the prosperity of the region
// copared to the current region, etc.
tCurrent.changeSatisfaction(migrationSuccessSatisfaction)
s.newTribes = append(s.newTribes, tCurrent)
tCurrent = nil
break
}
// The max population for the region is less than the population of the tribe.
// Get the number of people that we leave behind (a minimum of 50 people, if the tribe is large enough).
diff := min(max(50, tCurrent.Population-nbMaxPop), tCurrent.Population/2)
log.Println("Tribe ", tCurrent.String(), "is splitting into two tribes. Population:", tCurrent.Population, "Max population:", nbMaxPop, "Diff:", diff)
// Split the tribe into two tribes. The new tribe will be placed in the original region.
newTribe := tCurrent.Split(s.m.getNextTribeID(), diff)
// Move the remaining (the original) tribe to the new region
// and the new tribe to the original region.
currentReg := tCurrent.RegionID
s.moveTribe(tCurrent, nb)
s.moveTribe(newTribe, currentReg)
// TODO: Make these constants.
newTribe.changeSatisfaction(tribeSplitForcedSatisfaction)
tCurrent.changeSatisfaction(tribeSplitForcedSatisfaction)
s.newTribes = append(s.newTribes, tCurrent)
// Set the new tribe as the current tribe.
tCurrent = newTribe
}
// If there is still remaining population, check if they can survive in the current region.
if tCurrent != nil {
log.Println("Tribe ", tCurrent.String(), "is trying to survive in the current region. Population:", tCurrent.Population, "Max population:", t.currentRegionMaxPop)
// Check if the tribe can survive in the current region (or at least part of it can survive).
if maxPop := s.calcMaxPopPerRegion(t, tCurrent.RegionID); maxPop <= 0 {
log.Println("Tribe ", tCurrent.String(), "has died out.")
// TODO: Optionally attack other tribes to move into their regions.
if s.tribeAtRegion[tCurrent.RegionID] == tCurrent {
s.tribeAtRegion[tCurrent.RegionID] = nil
} else {
// DEBUG: Check if the tribe is in the right region.
log.Println("Tribe ", tCurrent.String(), "is in the wrong region?????!!!")
}
} else {
// Check if the tribe lost some of its population.
if maxPop < tCurrent.Population {
t.changeSatisfaction(starvationSatisfaction)
log.Println("Tribe ", tCurrent.String(), " lost some of its population.", tCurrent.Population-maxPop, "people died.", maxPop, "people survived.")
tCurrent.Population = maxPop
} else {
t.changeSatisfaction(migrationSuccessSatisfaction)
}
// DEBUG: Check if the tribe is in the right region.
if s.tribeAtRegion[tCurrent.RegionID] != tCurrent {
log.Println("Tribe", tCurrent.String(), "is in the wrong region.")
}
// Re-assign the tribe to the region.
s.moveTribe(tCurrent, tCurrent.RegionID)
// We can survive in the current region, retain the tribe.
s.newTribes = append(s.newTribes, tCurrent)
}
}
}
// findNewPath will find a new path to the destination region and assign it to the tribe.
func (s *simState) findNewPath(t *Tribe, destination int) bool {
newPath, found := planPath(s.getTile(t.RegionID), s.getTile(destination))
if found {
if len(newPath.Steps) == 1 {
panic("path length is 1")
}
t.SetPath(newPath)
}
return found
}
// findNewRegionToSettle will find a new region to settle in and set a new path to the region.
func (s *simState) findNewRegionToSettle(t *Tribe, avoidRegs []int) bool {
// Find the best region to settle in.
settleRegionScore := s.getSettleScoreFunc(t, t.gotVision)
bestRegion, score := s.findBestRegion(t, t.RegionID, settleRegionScore, avoidRegs)
if bestRegion == -1 {
log.Println("!!!Tribe", t.ID, "couldn't find a suitable region to settle in.")
return false // Couldn't find a suitable region to settle in.
}
log.Println("!!!Tribe", t.ID, "has found a region to settle in:", bestRegion, "with a score of", score)
// We have found a new region to settle in, so plot a path to the region
// and return the outcome of the pathfinding.
s.printRegionInfo(bestRegion)
t.printTribePreferences()
if !s.findNewPath(t, bestRegion) {
log.Println("!!!Tribe", t.ID, "couldn't find a path to the new region.")
return false
}
return true
}
func (s *simState) handleSettlingTribe(t *Tribe) {
// Check if the tribe has a path set. If not, we need to find a suitable region to settle in.
if !t.hasPath() {
t.gotVision = rand.Intn(100) < 99
// Check if we could find a suitable region to settle in.
if !s.findNewRegionToSettle(t, nil) {
log.Println("Tribe", t.ID, "couldn't find a new region to settle or a path to the new region.")
}
}
// Couldn't find a path to a new region, so we need to try again next turn.
if !t.hasPath() {
return
}
// We have a path set, so we need to move the tribe to the next region in the path.
// In general, if we want to move to the next region, check if the region is already occupied.
//
// So we just "peek" at the next region to see if it's occupied and either:
// - choose combat
// - find a way around
//
// If the next region would be our destination and it is occupied we can:
// - choose combat
// - merge with the other tribe
// - find a new region
nextRegion := t.Path.Peek()
// fightForRegion will execute a fight between the attacking and defending tribe.
// If the attacking tribe wins, the function will return true.
fightForRegion := func(attacking, defending *Tribe) bool {
// TODO:
// - The defending tribe should have a higher chance of inflicting losses on the attacking tribe.
// - The losses should depend on the population of the opponent.
// - The losses should depend on the culture of the tribes.
// - The losses should depend on the skills of the tribes.
// Calculate the losses for each tribe.
lossesDefendingTribe := rand.Intn(defending.Population)
defending.Population -= lossesDefendingTribe
lossesAttackingTribe := rand.Intn(attacking.Population)
attacking.Population -= lossesAttackingTribe
// The tribe with the largest remaining population wins.
return attacking.Population > defending.Population
}
// chooseCombat will determine if the tribe will choose to fight for the region.
chooseCombat := func(isDestination bool, attacking, defending *Tribe) bool {
// Determine if the tribe will sack the settlement at the destination
// if there is a tribe settled there and it is our destination.
disallowSacking := false
// For now we don't allow sacking of capitals.
if defending.CityState != nil && defending.CityState.Capital == defending.Settlement ||
defending.Empire != nil && defending.Empire.Capital == defending.Settlement {
log.Printf("Tribe %d is trying to sack the capital of tribe %d.", attacking.ID, defending.ID)
return false
}
// Check if the defending tribe has settled there:
if defending.Type > TribeTypeSettling && defending.doneSettling && (disallowSacking || !isDestination) {
return false
}
// Depending on our aggressiveness, the strength of the other tribe,
// and if this is our destination, we might choose to fight for the region.
multiplier := 1.0
// This is where we want to settle.
if isDestination {
multiplier += 0.1
}
// Religion might be a powerful motivator for combat.
// TODO: Some religions might be peaceful, while others might be more aggressive.
if attacking.gotVision {
multiplier += 0.1
}
// Consider culture.
// TODO: Consider expansionism, aggressiveness, etc.
// We multiply our own strength by the multiplier.
confidence := float64(attacking.Population) * multiplier
return confidence > float64(defending.Population)