-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcivSimTribes_tribe.go
617 lines (552 loc) · 20.4 KB
/
civSimTribes_tribe.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
package genworldvoronoi
import (
"fmt"
"log"
"math"
"math/rand"
"sort"
"github.com/Flokey82/go_gens/genlanguage"
)
type TribeType int
const (
TribeTypeNomadic TribeType = iota
TribeTypeSettling
TribeTypeCity
TribeTypeCityState
TribeTypeEmpire
)
// We start with one tribe. This tribe will be nomadic, and will move around.
// After a while, the tribe might be big enough to split into two tribes.
//
// A tribe can split due to:
// - Survival reasons (not enough food, etc. in the regions in their proximity).
// - Religious reasons (a new vision from the gods, etc.).
// - TODO: Cultural reasons (a different culture type preference, etc.).
// - TODO: Unhappiness (a string of bad events, deaths, famine, etc.).
//
// When a tribe splits, the new tribe will have a part of the population of the original tribe
// and retain some of the culture, religion, etc. of the original tribe. (In the future, we might
// want to consider that we fork the culture, religion, etc. of the original tribe as soon as the
// new tribe is created, not only when the tribe settles.).
//
// Settled Tribes:
//
// Tribes can either be settled or nomadic. Once a tribe has developed enough
// skills to permanently survive sustainably in a region type, it will look for
// a region to settle in within a certain radius. The radius depends on the
// form of discovery (e.g. a vision from the gods might have a larger radius,
// while a region discovered by the tribe itself through scouting might have a
// smaller radius).
// The tribe will then move to the region and settle there, if it is not already
// occupied by another tribe.
//
// If the region is already occupied, the tribe will either:
// - try to find another region to settle in
// - TODO: fight for the region
// - TODO: merge with the other tribe if the conditions are right
//
// Once the tribe has settled in a region, it will develop a new culture and a religion.
// If the tribe has inherited a religion or culture from the parent tribe, it will fork
// the culture and religion and develop a new one based on the preferences of the tribe.
// The tribe's language will be also become independent from the parent tribe from this point on.
// The tribe will also create a settlement in the region, which will be the cultural and religious
// center of the tribe.
//
// Nomadic Tribes:
//
// Tribes can also be nomadic. Nomadic tribes will move around, always looking for the most
// prosperous / suitable region to settle in. If the most prosperous region cannot sustain the
// entire tribe, the tribe will split into two or more tribes. The new tribes will move to the
// most suitable regions, while the original tribe will try to survive in the current region.
//
// The tribe will gain skills and preferences based on the regions it has been in. The tribe will
// start to prefer the types of regions (biomes, water proximity, mountain proximity, etc.) it has
// been in the most. The tribe will also develop skills based on the regions it has been in.
//
// Skills:
//
// Skills should provide a bonus to the tribe's sustainability in a region. Skills can be developed
// based on the region type, the tribe's preferences, and influence the tribe's culture.
//
// Skills can be developed based on:
// - Biome type and tribe preference for the biome
// - Water proximity
// - Mountain proximity
// - Existing skills of the tribe
// - TODO: Culture of the tribe
// - TODO: Religion of the tribe
// - TODO: Available resources in the region
// - TODO: Available species in the region
// - Grains (wheat, barley, etc.) for farming, beer, bread, etc.
// - Animals (cows, buffalos, etc.) for herding, milk, meat, etc.
// - Fish (salmon, trout, etc.) for fishing, food, etc.
//
// TODO: Happiness:
//
// The happiness of the tribe will depend on various factors:
//
// - Growth rate of the tribe
// - The tribe's preferences (if the tribe is in a region it prefers or not)
// - Deaths (from conflicts, famine, etc.)
// - Randomized events like:
// - Corrupt leaders
// - Famine
// - Disease
// - Natural disasters
// - Accidents
//
// TODO:
// - Keep track of the type of regions we are at and at some point adjust
// the culture to prefer certain regions.
// - Keep note of skills and knowledge of the tribe (e.g. farming, mining, etc.)
// Skills can develop based on the biome and region type the tribe is in.
// TODO: Based on the counts, we can evaluate the chances of the tribe
// discovering new skills, knowledge, etc.
// TODO: Keep track of water proximity, etc.
type Tribe struct {
ID int // Unique ID for the tribe.
RegionID int // The region the tribe is currently in.
Population int // The population of the tribe.
Type TribeType // The type of the tribe (nomadic, settled, city state, empire, etc.)
Parent *Tribe // The parent tribe of the tribe.
Language *genlanguage.Language // The language of the tribe.
Settlement *City // The city the tribe has settled in.
Culture *Culture // Culture that the tribe might have developed.
Religion *Religion // Religion that the tribe might have developed.
CityState *CityState // City state that the tribe might have developed.
Empire *Empire // Empire that the tribe might have developed.
// TODO: Change this to a running average.
Satisfaction ClampedVal // Happiness of the tribe overall.
SatisfactionAvg *RunningAverageLimit // Running average of the tribe's satisfaction.
Leadership *Faction // Current leadership of the tribe.
Factions []*Faction // Factions within the tribe / opposition, etc.
Skills map[*Skill]bool // Skills of the tribe.
// Preferences of the tribe.
TribePreference
*Path // Pathfinding for migrating tribes.
gotVision bool // If the tribe got their destination to settle from a vision from the gods.
doneSettling bool // If the tribe has settled in a region.
regionMaxPop int // The max pop of the region the tribe is in.
currentRegionMaxPop int // The current max pop of the region the tribe is in.
*ResourceStorage // Resources the tribe has.
*dumbStorage // Resources the tribe has, but dumb.
}
func (m *Civ) getNextTribeID() int {
id := m.TribeCount
m.TribeCount++
return id
}
func (m *Civ) newTribeAtRegion(r int, pop int) *Tribe {
t := NewTribe(m.getNextTribeID(), r, pop)
m.Tribes = append(m.Tribes, t)
log.Println("TODO: Generate culture.")
return t
}
// NewTribe returns a new tribe with the given population.
func NewTribe(id, regionID, population int) *Tribe {
// Initialize the last 10 biomes with the current as -1.
var last100Biomes [100]int
for i := range last100Biomes {
last100Biomes[i] = -1
}
t := &Tribe{
ID: id,
RegionID: regionID,
Population: population,
TribePreference: newTribePreference(),
Skills: make(map[*Skill]bool),
Type: TribeTypeNomadic,
Satisfaction: 1.0,
SatisfactionAvg: NewRunningAverageLimit(100),
Language: GenLanguage(int64(regionID)),
ResourceStorage: newResourceStorage(10),
dumbStorage: newDumbStorage(),
}
// Generate leadership.
t.Leadership = genFaction(t.Language)
return t
}
func (t *Tribe) compare(other *Tribe) float64 {
// Positive is good, negative is bad.
// We compare:
// - Preferences
// - Skills
// - Culture
// - Religion
// - Language
// Compare preferences.
prefValue := t.TribePreference.compare(&other.TribePreference)
// Compare skills.
var skillValue float64
for _, s := range Skills {
if t.Skills[s] && other.Skills[s] {
skillValue += 0.1
} else if t.Skills[s] || other.Skills[s] {
skillValue -= 0.1
}
}
languageValue := compareLanguage(t.Language, other.Language)
religionValue := t.Religion.compare(other.Religion)
cultureValue := t.Culture.compare(other.Culture)
// Calculate the similarity.
similarity := prefValue + skillValue + cultureValue + religionValue + languageValue
return similarity
}
// Ref returns the object reference of the city.
func (t *Tribe) Ref() ObjectReference {
return ObjectReference{
ID: t.ID,
Type: ObjectTypeTribe,
}
}
func (t *Tribe) SetPath(path *Path) {
t.Path = path
if path != nil && t.Path.Peek() == t.RegionID {
t.Path.Next() // Skip the current region.
}
}
func (t *Tribe) hasPath() bool {
return t.Path != nil
}
// makeNomadic will make the tribe nomadic.
func (t *Tribe) makeNomadic() {
// TODO: If the tribe is in charge of a city state or empire, we'd need to handle that.
// Will we let the empire collapse, or do we allow the tribe to control the empire nomadically?
t.Type = TribeTypeNomadic
t.SetPath(nil)
t.doneSettling = false
delete(t.Skills, SSkillSettling)
delete(t.Skills, SSkillSettlingHighland)
delete(t.Skills, SSkillSettlingWetlands)
log.Println("!!!Tribe", t.ID, "has become nomadic.")
}
func (t *Tribe) changeSatisfaction(diff float64) {
origSat := t.Satisfaction
t.Satisfaction.Add(diff)
t.SatisfactionAvg.Add(float64(t.Satisfaction))
log.Printf("Tribe %d satisfaction changed from %.2f to %.2f (rnng avg %.2f)", t.ID, origSat, t.Satisfaction, t.SatisfactionAvg.Current())
// If the satisfaction has decreased, the leadership popularity should decrease,
// and the faction popularity should increase... and vice versa if the satisfaction
// has increased.
t.Leadership.Popularity.Add(diff)
// We distribute the satisfaction change to the factions based on their influence.
var sumPop float64
for _, f := range t.Factions {
sumPop += float64(f.Leadership.Popularity)
}
// Now we distribute the satisfaction change to the factions.
// TODO:
// There should be some additional randomness in the distribution,
// or the popularity should change through random events, etc.
// Also it should depend on the event type and the individual faction
// if the faction would benefit from the event or not.
for _, f := range t.Factions {
f.Popularity.Add(diff * float64(f.Popularity) / sumPop) // Clamp to [0, 1]
}
}
func (t *Tribe) String() string {
// Assemble the preferred proximity string.
proxStr := t.TribePreference.String()
var cultureStr string
if t.Culture != nil {
cultureStr = " " + t.Culture.Type.String()
}
var leaderStr string
if t.Leadership != nil {
leaderStr = " " + t.Leadership.String()
}
return fmt.Sprintf("Tribe %d (%s) in region %d with population %d; satisfaction %f (%q)%s%s", t.ID, proxStr, t.RegionID, t.Population, t.Satisfaction, t.GetCultureType(), cultureStr, leaderStr)
}
// Grow the population of the tribe for one year.
func (t *Tribe) Grow() {
// Calculate the population growth rate for the tribe.
// Use the exponential growth model.
newPop := float64(t.Population) * math.Pow(math.E, growthRate)
if diff := newPop - float64(t.Population); diff < 1 {
// Use rand to potentially grow the population by one.
if rand.Float64() < diff {
t.Population++
}
} else {
t.Population = int(newPop)
}
// Update the population of the settlement.
if t.Settlement != nil {
t.Settlement.Population = t.Population
}
}
// GetCultureType returns the culture type of the tribe.
func (t *Tribe) GetCultureType() CultureType {
preferredBiome, score := t.LastBiomes.Preferred()
if !(t.Skills[SSkillSettling] || t.Skills[SSkillSettlingWetlands] || t.Skills[SSkillSettlingHighland]) && isAnyOf(int(preferredBiome), nomadicBiomes) && score > 0.5 {
return CultureTypeNomadic
}
if t.MountainProximity.Current() && t.RiverProximity.Current() {
if t.MountainProximity.avg > t.RiverProximity.avg {
return CultureTypeHighland
}
return CultureTypeRiver
} else if t.MountainProximity.Current() {
return CultureTypeHighland
} else if t.RiverProximity.Current() {
return CultureTypeRiver
}
// TODO:
// - Culture lake
if t.LakeProximity.Current() {
return CultureTypeLake
}
// - Culture naval
if t.OceanProximity.Current() {
return CultureTypeNaval
}
// Check if we have hunters.
if t.Skills[SSkillHunting] && isAnyOf(int(preferredBiome), huntingBiomes) {
return CultureTypeHunting
}
return CultureTypeGeneric
}
func isAnyOf(b int, biomes []int) bool {
for _, bb := range biomes {
if b == bb {
return true
}
}
return false
}
// Split the tribe into two tribes with a new one with the given population.
func (t *Tribe) Split(id int, newPopulation int) *Tribe {
t.Population -= newPopulation
nt := NewTribe(id, t.RegionID, newPopulation) // TODO: Generate a unique ID.
nt.Type = t.Type
nt.Parent = t
nt.Satisfaction = t.Satisfaction // Maybe that should be different?
t.SatisfactionAvg.CopyTo(nt.SatisfactionAvg)
// Copy the last biomes and cultures to the new tribe.
t.TribePreference.CopyTo(&nt.TribePreference)
// TODO: If we have a culture, we should copy it to the new tribe.
// We should also track religion and we either mutate the religion or
// or the culture of the new tribe.
log.Println("TODO: Mutate religion or culture and find a better way to fork language")
nt.Language = t.Language
nt.Religion = t.Religion // For now, we use the same religion.
nt.Culture = t.Culture // For now, we use the same culture.
// Copy the skills to the new tribe.
for s := range t.Skills {
nt.Skills[s] = true
}
// Generate leadership if no other faction exists.
if len(t.Factions) == 0 {
nt.Leadership = genFaction(nt.Language)
} else {
// Promote the most popular faction to the new tribe.
// TODO: The population of the new tribe should depend on the popularity of the faction.
sort.Slice(t.Factions, func(i, j int) bool {
return t.Factions[i].Leadership.Popularity > t.Factions[j].Leadership.Popularity
})
nt.Leadership = t.Factions[0]
t.Factions = t.Factions[1:]
}
return nt
}
func (t *Tribe) RandomSplit(nextID int) *Tribe {
// The tribe is unhappy and might split.
nt := t.Split(nextID, rand.Intn(t.Population)/2)
// If the original tribe satisfaction was low, we increase the satisfaction of the new tribe.
if t.Satisfaction < 0.3 {
nt.changeSatisfaction(tribeSplitVoluntarySatisfaction)
}
// There is a random chance that the tribe will leave due to a vision or a spiritual calling.
nt.gotVision = rand.Intn(100) < 50
if rand.Intn(100) < 10 {
// There is a chance that the new tribe will revert to being nomadic.
// TODO: Find a way to have a religion that doesn't require a spiritual center.
// One way to solve this is to have a place of pilgrimage that the tribe can visit
// but then we'd have to make sure that the religion doesn't really spread from there
// but rather from the practitioners (tribes, etc.).
nt.makeNomadic()
} else {
// Make sure the tribe will look for a new region to settle in.
nt.Type = TribeTypeSettling
nt.SetPath(nil)
nt.doneSettling = false
}
// There is a chance that the new tribe will have some preferences reset.
nt.TribePreference.RandomReset()
log.Printf("!!!%s has split into %s and %s.", t.String(), t.String(), nt.String())
return nt
}
// DevelopSkills develops the skills of the tribe based on the biome and region type.
func (t *Tribe) DevelopSkills(curRegProp *RegionProp, resPres *ResourcePresence) {
// Check all possible skills and check if we can develop them.
SkillLoop:
for _, s := range Skills {
if t.Skills[s] {
continue // The tribe already has this skill.
}
// Check if we have the required skills to develop this skill.
for _, r := range s.Requires {
if !t.Skills[r] {
continue SkillLoop
}
}
if s.CanDevelopIn(curRegProp, resPres) && s.DevelopAt(t.LastBiomes.GetScoreOf(curRegProp.Biome)) {
t.Skills[s] = true
s.EffectOnTribe(t)
log.Printf("Tribe %d developed the skill %s", t.ID, s.Name)
}
}
}
func (t *Tribe) printTribePreferences() {
log.Printf("Tribe %d preferences:", t.ID)
curTribePref := t.getPreferredRegionProp()
curTribePref.Log()
}
func (t *Tribe) SustainabilityFactor(curRegProp *RegionProp, resPres *ResourcePresence) float64 {
// TODO: This should depend on the region (whether it's a desert, etc.)
// Depending on the skills and knowledge of the tribe, we can calculate
// the sustainability factor of the tribe.
factor := 1.0
for _, s := range Skills {
if !t.Skills[s] {
continue
}
if s.CanDevelopIn(curRegProp, resPres) {
factor += 0.1
}
}
return factor
}
type TribePreference struct {
LastBiomes *Last100[HackyBiome] // The last 1000 biomes the tribe has been in.
LastCultures *Last100[CultureType] // The last 1000 cultures the tribe has been in.
RiverProximity *RunningBool
LakeProximity *RunningBool
OceanProximity *RunningBool
MountainProximity *RunningBool
}
func newTribePreference() TribePreference {
return TribePreference{
LastBiomes: newLast100[HackyBiome]("biome"),
LastCultures: newLast100[CultureType]("culture"),
RiverProximity: NewRunningBool(),
LakeProximity: NewRunningBool(),
OceanProximity: NewRunningBool(),
MountainProximity: NewRunningBool(),
}
}
func (t *TribePreference) String() string {
var proxStr string
if t.RiverProximity.Current() {
proxStr += "R"
} else {
proxStr += "-"
}
if t.LakeProximity.Current() {
proxStr += "L"
} else {
proxStr += "-"
}
if t.OceanProximity.Current() {
proxStr += "O"
} else {
proxStr += "-"
}
if t.MountainProximity.Current() {
proxStr += "M"
} else {
proxStr += "-"
}
return proxStr
}
// RandomReset resets some of the tribe preferences randomly.
func (t *TribePreference) RandomReset() {
if rand.Intn(100) < 50 {
t.LastBiomes.Reset()
}
if rand.Intn(100) < 50 {
t.RiverProximity.Reset()
}
if rand.Intn(100) < 50 {
t.LakeProximity.Reset()
}
if rand.Intn(100) < 50 {
t.OceanProximity.Reset()
}
if rand.Intn(100) < 50 {
t.MountainProximity.Reset()
}
}
func (t *TribePreference) CopyTo(other *TribePreference) {
t.LastBiomes.CopyTo(other.LastBiomes)
t.LastCultures.CopyTo(other.LastCultures)
t.RiverProximity.CopyTo(other.RiverProximity)
t.LakeProximity.CopyTo(other.LakeProximity)
t.OceanProximity.CopyTo(other.OceanProximity)
t.MountainProximity.CopyTo(other.MountainProximity)
}
func (t *TribePreference) addRegionProp(curRegProp *RegionProp) {
// Set the current biome of the tribe and get the preferred biome of the tribe.
t.LastBiomes.Add(curRegProp.Biome)
// Set water proximity and get the preferred water proximity.
t.RiverProximity.Add(curRegProp.River)
// Set lake proximity and get the preferred lake proximity.
t.LakeProximity.Add(curRegProp.Lake)
// Set ocean proximity and get the preferred ocean proximity.
t.OceanProximity.Add(curRegProp.Ocean)
// Set mountain proximity and get the preferred mountain proximity.
t.MountainProximity.Add(curRegProp.Mountain)
}
func (t *TribePreference) getPreferredRegionProp() *RegionProp {
preferredBiome, _ := t.LastBiomes.Preferred()
return &RegionProp{
Biome: preferredBiome,
RegionProximity: RegionProximity{
River: t.RiverProximity.Current(),
Lake: t.LakeProximity.Current(),
Ocean: t.OceanProximity.Current(),
Mountain: t.MountainProximity.Current(),
},
}
}
func (t *TribePreference) compare(other *TribePreference) float64 {
// Compare preferences.
var prefValue float64
// TODO: Instead let's compare the aversion to the other tribe's preferred biome.
tBiome, tScore := t.LastBiomes.Preferred()
oBiome, oScore := other.LastBiomes.Preferred()
if tBiome != oBiome {
prefValue -= float64(tScore) + float64(oScore)
}
prefValue -= math.Abs(t.MountainProximity.avg - other.MountainProximity.avg)
prefValue -= math.Abs(t.RiverProximity.avg - other.RiverProximity.avg)
prefValue -= math.Abs(t.LakeProximity.avg - other.LakeProximity.avg)
prefValue -= math.Abs(t.OceanProximity.avg - other.OceanProximity.avg)
return prefValue
}
// Calculate the "attractiveness" multiplier for the region and the tribe.
// This will return a multiplier signifying how well the tribe can extract resources
// or value from the region.
func (t *TribePreference) compareSuitability(gotProp RegionProp) float64 {
wantProp := t.getPreferredRegionProp()
multiplier := 1.0
// Penalize if the biome doesn't match the preferred biome.
if wantProp.Biome != gotProp.Biome {
multiplier -= 0.2 * (1 - t.LastBiomes.GetScoreOf(gotProp.Biome))
}
// If there is a specific preference for the region, we penalize
// if the region doesn't match the preference.
if wantProp.River && !gotProp.River {
multiplier -= 0.2 * t.RiverProximity.avg
}
if wantProp.Lake && !gotProp.Lake {
multiplier -= 0.2 * t.LakeProximity.avg
}
if wantProp.Ocean && !gotProp.Ocean {
multiplier -= 0.2 * t.OceanProximity.avg
}
if wantProp.Mountain && !gotProp.Mountain {
multiplier -= 0.2
}
return multiplier
}