-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplanisuss_world.py
1819 lines (1531 loc) · 76.5 KB
/
planisuss_world.py
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
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.colors as colors
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import random
import time
import math
import tkinter as tk
from tkinter import font as tkFont
from PIL import Image, ImageTk
# World constants
NUMCELLS = 50 # Size of the grid
NUMDAYS = random.randint(50, 500) # Number of days the simulation will run
# Species constants: the following parameters are customizable in the GUI
MAX_HERD = 100 # Maximum number of Erbast in a cell
MAX_PRIDE = 100 # Maximum number of Carviz in a cell
AGING_ERBAST = 5 # Energy lost each month (10 days)
AGING_CARVIZ = 5 # Energy lost each month
VEGETOB_GROWTH = 2 # Vegetob growth rate
NEIGHBORHOOD = 4 # Neighborhood size, that is, how many cells around are evaluated
LIFETIME_ERBAST = 25 # Erbast lifetime
LIFETIME_CARVIZ = 30 # Carviz lifetime
ENERGY_THRESHOLD_ERBAST = 5 # Erbast energy threshold for moving
ENERGY_THRESHOLD_CARVIZ = 2 # Carviz energy threshold for moving
SA_THRESHOLD_ERBAST = 0.2 # Erbast social attitude threshold for moving
SA_THRESHOLD_CARVIZ = 0.1 # Carviz social attitude threshold for moving
# World class
class World:
def __init__(self, size, ground_ratio):
'''
World initialization:
- size: size of the world grid
- ground_ratio: ratio of ground cells to total cells
The __init__ function initializes the world grid, ground cells, and species.
'''
self.size = size
self.grid = np.zeros((size, size), dtype=int)
self.ground_cells = int(ground_ratio * (size * size))
self.initialize_grid()
# Initializing species
self.vegetob = Vegetob(self)
self.erbast = Erbast(self)
self.carviz = Carviz(self)
# Initializing day counter
self.day = 0
# Placing species randomly in the world
self.vegetob.place_randomly(int(0.8*self.ground_cells))
self.erbast.place_randomly(int(random.uniform(0.2, 0.5)*self.ground_cells))
self.carviz.place_randomly(int(random.uniform(0.2, 0.5)*self.ground_cells))
def initialize_grid(self):
'''
Function to initialize the world grid. It creates a central block of ground cells and then expands it
in layers of decreasing density. It also ensures cell connectivity by calling ensure_neighbors().
'''
# Setting the boundary cells to water
self.grid[0, :] = self.grid[-1, :] = 0
self.grid[:, 0] = self.grid[:, -1] = 0
# Creating a central block of ground cells
center = self.size // 2
core_size = int(self.size * 0.45)
core_start = center - core_size // 2
core_end = center + core_size // 2
for i in range(core_start, core_end):
for j in range(core_start, core_end):
if self.ground_cells > 0:
self.grid[i, j] = 1
self.ground_cells -= 1
# Expanding ground cells from center outward, more sparsely as we go
for layer in range(1, (self.size - core_size) // 2):
num_cells_in_layer = max(1, int((self.size - layer) * random.uniform(0.3, 0.6)))
layer_cells = []
# Defining the boundary of this layer
for i in range(core_start - layer, core_end + layer):
for j in range(core_start - layer, core_end + layer):
if 0 < i < self.size-1 and 0 < j < self.size-1 and self.grid[i, j] == 0:
layer_cells.append((i, j))
# Randomly choosing some cells in this layer for ground
selected_cells = random.sample(layer_cells, min(num_cells_in_layer, len(layer_cells)))
for (i, j) in selected_cells:
if self.ground_cells > 0:
self.grid[i, j] = 1
self.ground_cells -= 1
self.ensure_neighbors()
def count_neighbors(self, x, y):
'''
Counts the number of neighbors for a cell in the grid.
'''
neighbors = 0
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
if 0 <= x + dx < self.size and 0 <= y + dy < self.size:
neighbors += self.grid[x + dx, y + dy]
return neighbors
def ensure_neighbors(self):
'''
Ensures that each ground cell has at least 3 neighbors.
'''
to_relocate = []
# Checking for ground cells with less than 3 neighbors and marking them for relocation
for i in range(1, self.size - 1):
for j in range(1, self.size - 1):
if self.grid[i, j] == 1 and self.count_neighbors(i, j) < 3:
to_relocate.append((i, j))
self.grid[i, j] = 0
# Reallocating ground cells starting from the inner regions
for (x, y) in to_relocate:
while True:
new_x = random.randint(1, self.size - 2)
new_y = random.randint(1, self.size - 2)
if self.grid[new_x, new_y] == 0 and self.count_neighbors(new_x, new_y) >= 3:
self.grid[new_x, new_y] = 1
break
def get_neighborhood_positions(self, x, y, neighborhood_size):
'''
Returns the positions of the cells in the neighborhood of the cell (x, y).
'''
neighborhood = []
for i in range(x - neighborhood_size, x + neighborhood_size + 1):
for j in range(y - neighborhood_size, y + neighborhood_size + 1):
if 1 <= i < self.size-1 and 1 <= j < self.size-1:
neighborhood.append((i, j))
return neighborhood
def evaluate_cell(self, x, y, species_type):
'''
Evaluates the cell based on the species type.
'''
if species_type == 'Erbast':
return self.vegetob.intensity.get((x, y), 0) # Erbast prefers Vegetob-rich cells
elif species_type == 'Carviz':
return self.erbast_density((x, y)) # Carviz prefers Erbast-rich cells
def erbast_density(self, pos):
'''
Returns the number of Erbast creatures in a given cell.
'''
x, y = pos
return sum(1 for erbast in self.erbast.creature_pop if erbast['position'] == (x, y))
def carviz_density(self, pos):
'''
Returns the number of Carviz creatures in a given cell.
'''
x, y = pos
return sum(1 for carviz in self.carviz.creature_pop if carviz['position'] == (x, y))
def check_cell_limits(self, x, y):
'''
Ensures herd and pride limits for the cell.
'''
if self.erbast_density((x, y)) > MAX_HERD or self.carviz_density((x, y)) > MAX_PRIDE:
return False # Cell is full
return True
def is_valid_move(self, x, y):
'''
Ensures the move is within the grid limits and on a ground cell.
'''
if 0 <= x < self.size and 0 <= y < self.size:
is_valid = self.grid[x, y] == 1
return is_valid
return False
def validate_creature_positions(self):
'''
Validates the creature positions.
Prints a warning if a creature is found at an invalid position.
'''
for species in [self.erbast, self.carviz]:
species_name = species.__class__.__name__
for creature in species.creature_pop:
x, y = creature['position']
if not self.is_valid_move(x, y):
print(f"Warning: {species_name} at invalid position {(x, y)}")
print(f"Grid value: {self.grid[x, y]}")
def update(self):
'''
Updates the world for the next time step (day).
'''
self.day += 1
print(f"Day {self.day}")
# Moving creatures, grazing, and updating social groups.
self.vegetob.grow()
self.erbast.move()
self.erbast.graze()
self.carviz.move()
self.erbast.fuse_herds()
self.carviz.fuse_prides_or_fight()
self.carviz.pride_hunt(self.erbast)
self.erbast.spawn()
self.carviz.spawn()
self.erbast.overwhelmed()
self.carviz.overwhelmed()
self.validate_creature_positions()
print(f"After update: {len(self.erbast.creature_pop)} Erbast and {len(self.carviz.creature_pop)} Carviz")
# Superclass
class Species:
def __init__(self, world):
'''
Species initialization.
- world: reference to the world object
- positions: set of tuples representing positions on the grid
- memory: dictionary to store memory data for strategic decisions
- creature_pop: list of individual creature attributes per position
'''
self.world = world
self.positions = set()
self.memory = {}
self.creature_pop = []
def place_randomly(self, count, create_creature_data):
'''
Places creatures randomly in the world.
'''
placed = 0
while placed < count:
x, y = random.randint(1, self.world.size-2), random.randint(1, self.world.size-2)
if self.world.is_valid_move(x, y) and self.world.check_cell_limits(x, y):
creature_data = create_creature_data(self, x, y)
self.add_creature(creature_data)
self.positions.add((x, y))
placed += 1
print(f"Placed {count} creatures of {self.__class__.__name__}")
def add_creature(self, creature_data):
'''
Adds a creature to the creature population.
'''
self.creature_pop.append(creature_data)
def group_by_position(self, filter_func=None, group_by_time=False):
'''
Group creatures by their positions, optionally filtering and grouping by time.
- param filter_func: optional function to filter creatures before grouping
- param group_by_time: if True, group by both position and move_time
- return: dictionary with positions as keys and lists of creatures (or time-grouped creatures) as values
'''
groups = {}
for creature in self.creature_pop:
if filter_func is None or filter_func(creature):
pos = tuple(creature['position'])
if group_by_time:
move_time = creature.get('move_time', 0)
if pos not in groups:
groups[pos] = {}
if move_time not in groups[pos]:
groups[pos][move_time] = []
groups[pos][move_time].append(creature)
else:
if pos not in groups:
groups[pos] = []
groups[pos].append(creature)
return groups
def move(self, evaluate_cell_with_memory, energy_threshold, social_attitude_threshold):
'''
Moves the creatures in the world. Decisions are initially made collectively by groups of creatures,
but individual creatures may choose to move independently if they have enough energy and social attitude.
Cells are evaluated based on their suitability, determined by the evaluate_cell_with_memory function.
The neighborhood size determines the size of the area evaluated for decision making. Creatures are able
to look past their immediate neighborhood to evaluate the larger area and follow a trajectory towards
the most suitable cell.
'''
to_remove = []
groups_by_pos = self.group_by_position()
new_pop = []
for pos, group in groups_by_pos.items():
x, y = pos
info_neighborhood = self.world.get_neighborhood_positions(x, y, NEIGHBORHOOD)
move_neighborhood = self.world.get_neighborhood_positions(x, y, 1)
valid_moves = [
pos for pos in move_neighborhood if self.world.is_valid_move(*pos) and self.world.check_cell_limits(*pos)
and pos not in group[0]['memory']['last_visited']]
if valid_moves:
cell_values = {pos: evaluate_cell_with_memory(group[0], pos) for pos in info_neighborhood}
best_direction = max(cell_values, key=cell_values.get)
best_position = max(valid_moves, key=lambda pos: (
abs(pos[0] - best_direction[0]) + abs(pos[1] - best_direction[1]),
cell_values.get(pos, float('-inf'))
))
current_value = cell_values.get((x, y), float('-inf'))
best_value = cell_values.get(best_direction, float('-inf'))
group_decision = best_position if best_value > current_value else None
for creature in group:
if creature['energy'] <= 0:
to_remove.append(creature)
continue
if group_decision:
if creature['energy'] >= energy_threshold or creature['social_attitude'] >= social_attitude_threshold:
creature['position'] = group_decision
creature['energy'] -= 1
creature['energy'] = max(creature['energy'], 0)
creature['memory']['last_visited'].add((x, y))
if hasattr(self, 'moved_erbast'):
self.moved_erbast.add(id(creature))
if hasattr(creature, 'move_time'):
creature['move_time'] = self.world.day
else:
# Increasing the threshold ensures that individual creatures are less likely to move
if creature['energy'] >= energy_threshold * 3 and creature['social_attitude'] >= social_attitude_threshold * 3:
individual_best = max(valid_moves, key=lambda pos: cell_values.get(pos, float('-inf')))
creature['position'] = individual_best
creature['energy'] -= 1
creature['energy'] = max(creature['energy'], 0)
creature['memory']['last_visited'].add((x, y))
if hasattr(self, 'moved_erbast'):
self.moved_erbast.add(id(creature))
if hasattr(creature, 'move_time'):
creature['move_time'] = self.world.day
new_pop.append(creature)
else:
for creature in group:
new_pop.append(creature)
for member in to_remove:
self.creature_pop.remove(member)
if member['position'] in self.positions:
self.positions.remove(member['position'])
self.creature_pop = new_pop
self.creature_pop = [creature for creature in self.creature_pop if self.world.is_valid_move(*creature['position'])]
self.positions = set(tuple(creature['position']) for creature in self.creature_pop)
if hasattr(self, 'moved_erbast'):
return self.moved_erbast
def spawn(self, aging, lifetime, max_size):
'''
Spawns new creatures upon death of the parent, distributing its attributes between the offspring.
'''
new_pop = []
to_remove = []
groups_by_pos = self.group_by_position()
for pos, group in groups_by_pos.items():
cell_new_pop = []
for parent in group:
parent['age'] += 1
if parent['age'] % 10 == 0:
parent['energy'] -= aging
parent['energy'] = max(parent['energy'], 0)
if parent['age'] == lifetime:
to_remove.append(parent)
random_distribution = random.random()
offspring = [parent.copy() for _ in range(2)]
for i, off in enumerate(offspring):
off.update({
'age': 0,
'energy': parent['energy'] // 2,
'social_attitude': parent['social_attitude'] * 2 * (random_distribution if i == 0 else 1-random_distribution),
'memory': parent['memory'].copy(),
'position': parent['position']
})
cell_new_pop.extend(offspring)
else:
cell_new_pop.append(parent)
cell_new_pop = cell_new_pop[:max_size]
new_pop.extend(cell_new_pop)
for parent in to_remove:
self.creature_pop.remove(parent)
if parent['position'] in self.positions:
self.positions.remove(parent['position'])
self.creature_pop = new_pop
self.positions = set(member['position'] for member in self.creature_pop)
def overwhelmed(self):
'''
Removes creatures from the world when their cell is completely eaten by Vegetob.
'''
to_remove = []
for creature in self.creature_pop:
x, y = creature['position']
neighborhood_positions = self.world.get_neighborhood_positions(x, y, 1)
if all(self.world.evaluate_cell(pos[0], pos[1], 'Erbast') == 100 for pos in neighborhood_positions):
to_remove.append(creature)
for member in to_remove:
self.creature_pop.remove(member)
if member['position'] in self.positions:
self.positions.remove(member['position'])
# Subclasses
class Vegetob(Species):
def __init__(self, world):
'''
Vegetob initialization.
- intensity: dictionary to store the intensity of Vegetob in each cell
'''
super().__init__(world)
self.intensity = {}
def place_randomly(self, count):
'''
Places Vegetob randomly in the world, initializing their attributes.
'''
def create_vegetob_data(self, x, y):
return {
'position': (x, y),
'intensity': random.randint(0, 100)
}
super().place_randomly(count, create_vegetob_data)
def add_creature(self, creature_data):
'''
Adds Vegetob to the creature population.
'''
pos = creature_data['position']
self.intensity[pos] = creature_data['intensity']
self.positions.add(pos)
def grow(self):
'''
Simulates vegetob growth, increasing intensity for each cell it inhabits.
'''
for x in range(self.world.size):
for y in range(self.world.size):
pos = (x, y)
if self.world.grid[pos] == 1:
if not pos in self.intensity:
self.intensity[pos] = 0
self.intensity[pos] += VEGETOB_GROWTH
self.intensity[pos] = min(100, self.intensity[pos])
if pos not in self.positions and self.intensity[pos] > 0:
self.positions.add(pos)
def move(self):
pass
def spawn(self):
pass
def overwhelmed(self):
pass
class Erbast(Species):
def __init__(self, world):
'''
Erbast initialization.
- moved_erbast: set to keep track of Erbast that moved
- memory: strategic decisions are based on the last visited cells, and dangerous cells.
'''
super().__init__(world)
self.moved_erbast = set()
self.memory = {
"last_visited": set(),
"dangerous_cells": set()
}
def place_randomly(self, count):
'''
Places Erbast randomly in the world, initializing their attributes.
'''
def create_erbast_data(self, x, y):
return {
'position': (x, y),
'energy': random.randint(50, 100),
'lifetime': LIFETIME_ERBAST,
'age': 0,
'social_attitude': random.uniform(0, 1),
'memory': {
"last_visited": set(),
"dangerous_cells": set()
}
}
super().place_randomly(count, create_erbast_data)
def add_creature(self, creature_data):
'''
Adds Erbast to the creature population.
'''
self.creature_pop.append(creature_data)
def move(self):
'''
Moves the Erbast in the world.
'''
super().move(self.evaluate_cell_with_memory, ENERGY_THRESHOLD_ERBAST, SA_THRESHOLD_ERBAST)
def evaluate_cell_with_memory(self, herd_member, position):
'''
Evaluates the cell based on Vegetob availability, depletion avoidance, and dangerous cells.
'''
vegetob_availability = 3 if self.world.evaluate_cell(position[0], position[1], 'Erbast') > 30 else 0
depletion_penalty = 1 if self.world.evaluate_cell(position[0], position[1], 'Erbast') < 10 else 0
dangerous_memory = 2 if position in herd_member['memory']['dangerous_cells'] else 0
return max(0, vegetob_availability - dangerous_memory - depletion_penalty)
def graze(self):
'''
Lets stationary Erbast graze on Vegetob, increasing energy and adjusting
social attitude based on availability.
'''
def stationary_filter(erbast):
return id(erbast) not in self.moved_erbast
herds_by_pos = self.group_by_position(filter_func=stationary_filter)
for pos, herd in herds_by_pos.items():
vegetob_density = self.world.evaluate_cell(pos[0], pos[1], 'Erbast')
herd.sort(key=lambda member: member['energy'])
for erbast in herd:
if vegetob_density > 0:
energy_gain = min(1, vegetob_density)
erbast['energy'] += energy_gain
erbast['energy'] = min(erbast['energy'], 100)
vegetob_density -= energy_gain
else:
break
self.world.vegetob.intensity[pos] = vegetob_density
# Decreasing social attitude for Erbast that did not receive energy
for erbast in herd:
if vegetob_density <= 0 and erbast['energy'] < 50:
erbast['social_attitude'] -= 0.1
erbast['social_attitude'] = max(0, erbast['social_attitude'])
def fuse_herds(self):
'''
Fuses herds when multiple herds move to the same cell.
'''
herds_by_pos = self.group_by_position()
new_pop = []
for pos, herd_members in herds_by_pos.items():
if len(herd_members) > 1:
# Sorting herd members by energy to prioritize stronger members
herd_members.sort(key=lambda x: x['energy'], reverse=True)
# Fusing herds up to MAX_HERD size
fused_herd = herd_members[:MAX_HERD]
# Combining memories and adapting social attitudes
combined_memory = {}
for herd_member in fused_herd:
combined_memory.update(herd_member['memory'])
herd_member['social_attitude'] = sum([m['social_attitude'] for m in fused_herd]) / len(fused_herd)
for herd_member in herd_members:
herd_member['memory'] = combined_memory
new_pop.extend(fused_herd)
# Handling excess members
if not self.world.check_cell_limits(pos[0], pos[1]):
excess_members = herd_members[MAX_HERD:]
self.handle_excess_members(excess_members, pos)
else:
new_pop.extend(herd_members)
self.creature_pop = new_pop
self.positions = set(member['position'] for member in self.creature_pop)
def handle_excess_members(self, excess_members, current_pos):
'''
Finds a nearby empty cell for excess Erbast members.
If no empty cell is found, the member is removed from the population.
'''
for member in excess_members:
nearby_cells = self.world.get_neighborhood_positions(current_pos[0], current_pos[1], 1)
empty_cells = [cell for cell in nearby_cells if cell not in [m['position'] for m in self.creature_pop]]
if empty_cells:
new_pos = random.choice(empty_cells)
if self.world.is_valid_move(*new_pos) and self.world.check_cell_limits(*new_pos):
member['position'] = new_pos
self.positions.add(new_pos)
else:
self.creature_pop.remove(member)
if member['position'] in self.positions:
self.positions.remove(member['position'])
def spawn(self):
'''
Spawns new Erbast upon death of the parent, distributing its attributes between the offspring.
'''
super().spawn(AGING_ERBAST, LIFETIME_ERBAST, MAX_HERD)
def overwhelmed(self):
'''
Removes Erbast from the world when their cell is completely eaten by Carviz.
'''
super().overwhelmed()
class Carviz(Species):
def __init__(self, world):
'''
Carviz initialization.
- memory: strategic decisions are based on the last visited cells, the successful hunts, and dangerous cells.
'''
super().__init__(world)
self.memory = {
"last_visited": set(),
"successful_hunts": set(),
"dangerous_cells": set()
}
def place_randomly(self, count):
'''
Places Carviz randomly in the world, initializing their attributes.
'''
def create_carviz_data(self, x, y):
return {
'position': (x, y),
'energy': random.randint(50, 100),
'lifetime': LIFETIME_CARVIZ,
'age': 0,
'social_attitude': random.uniform(0, 1),
'memory': {
"last_visited": set(),
"successful_hunts": set(),
"dangerous_cells": set()
},
'move_time': 0
}
super().place_randomly(count, create_carviz_data)
def add_creature(self, creature_data):
'''
Adds Carviz to the creature population.
'''
self.creature_pop.append(creature_data)
def move(self):
'''
Moves the Carviz in the world.
'''
super().move(self.evaluate_cell_with_memory, ENERGY_THRESHOLD_CARVIZ, SA_THRESHOLD_CARVIZ)
def evaluate_cell_with_memory(self, pride_member, position):
'''
Evaluates the cell based on prey richness, hunting memory, and dangerous cells.
'''
prey_bonus = 5 if self.world.evaluate_cell(position[0], position[1], 'Erbast') > 1 else 0
hunt_bonus = 2 if position in pride_member['memory']['successful_hunts'] else 0
danger_penalty = 3 if position in pride_member['memory']['dangerous_cells'] else 0
return max(0, prey_bonus + hunt_bonus - danger_penalty)
def fuse_prides_or_fight(self):
'''
Fuses prides or lets them fight for dominance based on social attitudes.
Prides are sorted by size so that the smallest have a chance to fuse before potential fights.
Memoeries of the fused prides' members are combined, allowing for more strategic decisions.
'''
prides_by_pos = self.group_by_position(group_by_time=True)
new_pop = []
for pos, pride_time in prides_by_pos.items():
prides_list = list(pride_time.values())
prides_list.sort(key=len)
while len(prides_list) > 1:
pride_1 = prides_list.pop(0)
pride_2 = prides_list.pop(0)
avg_social_attitude_1 = sum(p['social_attitude'] for p in pride_1) / len(pride_1)
avg_social_attitude_2 = sum(p['social_attitude'] for p in pride_2) / len(pride_2)
if avg_social_attitude_1 > random.random() and avg_social_attitude_2 > random.random():
fused_pride = pride_1 + pride_2
combined_memory = {}
for member in fused_pride:
combined_memory.update(member['memory'])
member['social_attitude'] = sum([m['social_attitude'] for m in fused_pride]) / len(fused_pride)
for member in fused_pride:
member['memory'] = combined_memory
prides_list.append(fused_pride)
else:
winning_pride = self.pride_fight(pride_1, pride_2)
prides_list.append(winning_pride)
prides_list.sort(key=len)
if prides_list:
cell_new_pop = prides_list[0][:MAX_PRIDE]
new_pop.extend(cell_new_pop)
self.creature_pop = new_pop
self.positions = set(member['position'] for member in self.creature_pop)
def pride_fight(self, pride_1, pride_2):
'''
A last-blood match between two prides. The pride led by the strongest Carviz wins.
The loser is removed from the population, the winner loses 10% of its energy.
The winning pride gains a boost in social attitude and its members' memories are updated with the current position.
'''
while pride_1 and pride_2:
champion_1 = max(pride_1, key=lambda p: p['energy'])
champion_2 = max(pride_2, key=lambda p: p['energy'])
if champion_1['energy'] > champion_2['energy']:
loser = pride_2.pop(pride_2.index(champion_2))
champion_1['energy'] *= 0.9
champion_1['energy'] = max(champion_1['energy'], 0)
else:
loser = pride_1.pop(pride_1.index(champion_1))
champion_2['energy'] *= 0.9
champion_2['energy'] = max(champion_2['energy'], 0)
if loser['position'] in self.positions:
self.positions.remove(loser['position'])
winning_pride = pride_1 if pride_1 else pride_2
for member in winning_pride:
member['social_attitude'] += 0.2
member['social_attitude'] = min(1, member['social_attitude'])
if winning_pride:
position = winning_pride[0]['position']
for member in winning_pride:
if 'memory' in member and 'dangerous_cells' in member['memory']:
member['memory']['dangerous_cells'].add(position)
return winning_pride
def pride_hunt(self, erbast):
'''
Carviz hunt Erbast in cells with one remaining pride.
The strongest Erbast is hunted and its energy is distributed among the pride members.
Chance of success is based on the ratio of pride energy to the hunted Erbast's energy, but is capped at 70%.
If successful, the pride's attitude is boosted and the Erbast's energy is shared among the pride members.
If not, the pride's attitude is decreased and the Erbast's memory is updated with the current position.
'''
pride_by_pos = self.group_by_position()
for pos, pride in pride_by_pos.items():
erbast_in_cell = [herd_member for herd_member in self.world.erbast.creature_pop if herd_member['position'] == pos]
if erbast_in_cell:
strongest_erbast = max(erbast_in_cell, key=lambda e: e['energy'])
success_probability = min(0.7, sum([p['energy'] for p in pride]) / (sum([p['energy'] for p in pride]) + strongest_erbast['energy']))
if random.random() < success_probability:
energy_gain = strongest_erbast['energy'] * 0.8
erbast_in_cell.remove(strongest_erbast)
self.world.erbast.creature_pop.remove(strongest_erbast)
if strongest_erbast['position'] in self.world.erbast.positions:
self.world.erbast.positions.remove(strongest_erbast['position'])
for carviz in pride:
carviz['energy'] += int(energy_gain // len(pride))
carviz['energy'] = min(carviz['energy'], 100)
carviz['social_attitude'] = min(1, carviz['social_attitude'] + 0.1)
if pos not in carviz['memory']['successful_hunts']:
carviz['memory']['successful_hunts'].add(pos)
else:
for carviz in pride:
carviz['social_attitude'] = max(0, carviz['social_attitude'] - 0.1)
for erbast in erbast_in_cell:
if pos not in erbast['memory']['dangerous_cells']:
erbast['memory']['dangerous_cells'].add(pos)
else:
for carviz in pride:
carviz['social_attitude'] = max(0, carviz['social_attitude'] - 0.1)
def spawn(self):
'''
Spawns new Carviz upon death of the parent, distributing its attributes between the offspring.
'''
super().spawn(AGING_CARVIZ, LIFETIME_CARVIZ, MAX_PRIDE)
def overwhelmed(self):
'''
Removes Carviz from the world when their cell is completely eaten by Erbast.
'''
super().overwhelmed()
# GUI classes
class PlanisussGUI:
def __init__(self, world):
'''
Initializes the main GUI for the simulation.
Sets up the simulation parameters, data, and GUI elements.
Images are loaded and resized for a nicer visualization of zoomed cells.
'''
self.world = world
self.paused = False
self.terminated = False
self.pause_button = None
self.speed = 100
self.speed_factor = 1.5
self.current_frame = 0
self.anim = None
self.anim_running = False
self.last_update_time = time.time()
self.graph_window = None
self.parameter_window = None
self.population_data = {'time': [], 'erbast': [], 'carviz': []}
self.vegetob_density_data = {'time': [], 'density': []}
self.energy_levels_data = {'time': [], 'erbast_energy': [], 'carviz_energy': []}
self.last_time = 0
self.simulation_params = {
"Simulation length": NUMDAYS,
"Neighborhood": NEIGHBORHOOD,
"Max pride size": MAX_PRIDE,
"Max herd size": MAX_HERD,
"Erbast aging": AGING_ERBAST,
"Carviz aging": AGING_CARVIZ,
"Vegetob growth": VEGETOB_GROWTH,
"Erbast lifetime": LIFETIME_ERBAST,
"Carviz lifetime": LIFETIME_CARVIZ,
"Erbast energy threshold": ENERGY_THRESHOLD_ERBAST,
"Carviz energy threshold": ENERGY_THRESHOLD_CARVIZ,
"Erbast social attitude threshold": SA_THRESHOLD_ERBAST,
"Carviz social attitude threshold": SA_THRESHOLD_CARVIZ
}
self.root = tk.Tk()
self.root.title("Planisuss World")
self.root.geometry("1400x1000")
self.root.configure(bg='deepskyblue')
self.font = tkFont.Font(family="Fixedsys", size=24)
self.erbast_image = Image.open("erbast.png")
self.carviz_image = Image.open("carviz.png")
self.water_bg = Image.open("water.png")
self.ground_bg = Image.open("vegetob.png")
self.erbast_image = self.erbast_image.resize((80, 80), Image.LANCZOS)
self.carviz_image = self.carviz_image.resize((80, 80), Image.LANCZOS)
self.water_bg = self.water_bg.resize((300, 300), Image.LANCZOS)
self.ground_bg = self.ground_bg.resize((300, 300), Image.LANCZOS)
self.setup_gui()
def setup_gui(self):
'''
Sets up the GUI elements, including buttons and the world display.
The left frame contains the buttons, and the right frame contains the world display.
The buttons allow for control of the simulation, such as pausing, terminating, restarting,
speeding up, slowing down, displaying graphs, and changing parameters.
'''
# Title
title_font = tkFont.Font(family="Fixedsys", size=50, weight="bold")
title = tk.Label(self.root, text="Planisuss World", font=title_font, bg='deepskyblue', fg='navy')
title.pack(pady=20)
# Main frame
main_frame = tk.Frame(self.root, bg='deepskyblue')
main_frame.pack(fill=tk.BOTH, expand=True)
# Left frame for buttons
left_frame = tk.Frame(main_frame, width=400, bg='deepskyblue')
left_frame.pack(side=tk.LEFT, padx=50, pady=0, fill=tk.BOTH, expand=True)
left_frame.pack_propagate(False)
# Right frame for map
right_frame = tk.Frame(main_frame, bg='deepskyblue')
right_frame.pack(side=tk.RIGHT, padx=0, pady=0, fill=tk.BOTH, expand=True)
# Buttons
buttons = [
("Pause", self.pause),
("Terminate", self.terminate),
("Restart", self.restart),
("Speed Up", self.speed_up),
("Slow Down", self.slow_down),
("Display Graphs", self.display_graphs),
("Change Parameters", self.change_parameters)
]
# Top spacer frame to center buttons
top_spacer = tk.Frame(left_frame, bg='deepskyblue')
top_spacer.pack(expand=True, fill=tk.Y)
# Button frame
button_frame = tk.Frame(left_frame, bg='deepskyblue')
button_frame.pack(expand=True)
for text, command in buttons:
button_width = self.font.measure(text) // self.font.measure('0') + 2
button = tk.Button(button_frame, text=text, command=command,
font=self.font, bg='saddlebrown', fg='white', activebackground='brown',
activeforeground='white', width=button_width)
button.pack(pady=15, anchor='center')
if text == "Pause":
self.pause_button = button
# Bottom spacer frame to center buttons
bottom_spacer = tk.Frame(left_frame, bg='deepskyblue')
bottom_spacer.pack(expand=True, fill=tk.Y)
# Creating and displaying the world
self.fig, self.ax, self.im, self.erbast_scatter, self.carviz_scatter = display_world(self.world)
self.canvas = FigureCanvasTkAgg(self.fig, master=right_frame)
self.canvas.draw()
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
self.canvas.mpl_connect('button_press_event', self.on_cell_click)
self.ax.set_axis_off()
self.fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
self.anim = animation.FuncAnimation(self.fig, self.update, frames=NUMDAYS, interval=self.speed, blit=False, repeat=False)
def pause(self):
'''
Pauses or resumes the simulation.
The pause button will display "Resume" if the simulation is paused, and "Pause" if it is running.
'''
self.paused = not self.paused
if self.paused:
self.pause_button.config(text="Resume")
print("Simulation paused")
if self.anim and self.anim.event_source:
self.anim.event_source.stop()
else:
self.pause_button.config(text="Pause")
print("Simulation resumed")
if self.anim and self.anim.event_source:
self.anim.event_source.start()
elif not self.anim.event_source:
print("Event source not found - pause") # Not useful for the simulation, but a debug print statement
# to check if the event source is found
def terminate(self):
'''
Terminates the simulation. A dialog box will ask for confirmation.
'''
dialog = CustomDialog(self.root, "Terminate Simulation", "Are you sure you want to terminate the simulation?")
if dialog.result:
self.terminated = True
self.running = False
if self.anim and hasattr(self.anim, 'event_source'):
print("Stopping animation")
try:
self.anim.event_source.stop()
except Exception as e:
print(f"Error stopping animation: {e}") # Again, not useful for the simulation, but for debugging
self.anim = None
self.anim_running = False
self.root.quit()
print("Simulation terminated")
else:
print("Termination cancelled")
def restart(self):
'''
Restarts the simulation. A dialog box will ask for confirmation.
The reset_simulation() function is called to reset the simulation parameters and the world.