-
Notifications
You must be signed in to change notification settings - Fork 4
/
universe.py
320 lines (267 loc) · 12.7 KB
/
universe.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
__author__ = 'gkour'
from space import Space
from evolution import Evolution
from config import ConfigPhysics, ConfigBiology, ConfigBrain
import numpy as np
import utils
from creature_actions import Actions
from sound import Sound
class Universe:
def __init__(self, races, statistics=None):
self._creature_counter = 0
self._races = races
self._space = Space(ConfigPhysics.SPACE_SIZE)
self._time = 0
self.statistics = statistics
for race in races:
num_fathers = ConfigPhysics.NUM_FATHERS
fathers_locations_i = np.random.choice(ConfigPhysics.SPACE_SIZE, num_fathers)
fathers_locations_j = np.random.choice(ConfigPhysics.SPACE_SIZE, num_fathers)
ages = np.zeros(num_fathers) #np.random.randint(low=0, high=ConfigBiology.BASE_LIFE_EXPECTANCY, size=num_fathers)
for n in range(num_fathers):
dna = Evolution.mutate_dna(race.race_basic_dna())
self.create_creature(race, id=self.allocate_id(), dna=dna,
coord=(fathers_locations_i[n], fathers_locations_j[n]),
age=ages[n], parents=None)
self.give_food(ConfigPhysics.INITIAL_FOOD_AMOUNT)
def allocate_id(self):
self._creature_counter += 1
return self._creature_counter
def get_creatures_counter(self):
return self._creature_counter
def get_races(self):
return self._races
def num_races(self):
return len(self._races)
# Space Management
def space(self):
return self._space
def get_surroundings(self, coord, vision_range):
return self._space.get_state_in_coord(coord, vision_range, self._races)
# Time Management
def pass_time(self):
self._time += 1
num_creatures = self.num_creatures()
if self._time < ConfigPhysics.ETERNITY and num_creatures > 0:
self.give_food(round(num_creatures * ConfigPhysics.FOOD_CREATURE_RATIO))
for creature in self.get_all_creatures():
if creature.alive():
self.execute_action(creature)
self.space().update_sounds(self._time)
return self.num_creatures()
else:
return None
def get_time(self):
return self._time
# Food Supply management
def give_food(self, amount):
food_cells_i = np.random.choice(ConfigPhysics.SPACE_SIZE, amount)
food_cells_j = np.random.choice(ConfigPhysics.SPACE_SIZE, amount)
for n in range(amount):
self.space().add_food((food_cells_i[n], food_cells_j[n]), 1)
# Creatures Control
def create_creature(self, race, id, dna, coord, age=0, energy=ConfigBiology.INITIAL_ENERGY, parents=None):
descendant = race(universe=self, id=id, dna=dna, age=age, energy=energy, parents=parents)
cell = self.space().insert_creature(descendant, coord)
descendant.update_cell(cell)
def get_all_creatures(self):
return np.random.permutation(self.space().get_all_creatures()).tolist()
def get_food_distribution(self):
return self.space().get_food_distribution()
def get_creatures_distribution(self):
return self.space().get_creatures_distribution()
def num_creatures(self):
return len(self.get_all_creatures())
def execute_action(self, creature):
# if creature.age() > creature.life_expectancy():
# self.kill_creature(creature, cause='elderly')
# return
creature.increase_age()
previous_energy = creature.energy()
state = creature.get_state()
decision = creature.decide(state)
action = creature.index_to_enum(decision)
self.statistics.action_dist.append([creature.id(), creature.get_race(), Actions.enum_to_index(action)])
if action == Actions.LEFT:
self.creature_move_left(creature)
if action == Actions.RIGHT:
self.creature_move_right(creature)
if action == Actions.UP:
self.creature_move_up(creature)
if action == Actions.DOWN:
self.creature_move_down(creature)
if action == Actions.EAT:
self.creature_eat(creature)
if action == Actions.MATE:
self.creature_mate(creature)
if action == Actions.FIGHT:
self.creature_fight(creature)
if action == Actions.WORK:
self.creature_work(creature)
if action == Actions.DIVIDE:
self.creature_divide(creature)
if action == Actions.VOCALIZE:
self.creature_vocalize(creature)
dec_1hot = np.zeros(creature.num_actions())
dec_1hot[decision] = 1
reward = creature.energy() - previous_energy
new_state = creature.get_state() if creature.alive() else creature.dead_state()
terminated = False if creature.alive() else True
creature.add_experience([state, dec_1hot, reward, new_state, terminated])
if creature.age() % creature.learning_frequency() == 0:
creature.smarten()
def races_dist(self):
dist = []
for race in self.get_races():
num_in_race = [creature for creature in self.get_all_creatures() if creature.get_race() == race]
dist.extend([len(num_in_race)])
return np.asarray(dist)
def kill_creature(self, creature, cause='fatigue'):
creature.dying()
creature.reduce_energy(creature.energy())
cell = creature.cell()
creature.update_cell(None)
cell.remove_creature(creature)
if self.statistics is not None:
if cause == 'fight':
self.statistics.death_cause.append([creature.id(), creature.get_race(), 1])
elif cause == 'elderly':
self.statistics.death_cause.append([creature.id(), creature.get_race(), 2])
elif cause == 'fall':
self.statistics.death_cause.append([creature.id(), creature.get_race(), 3])
else: # fatigue
self.statistics.death_cause.append([creature.id(), creature.get_race(), 0])
#print(self.statistics.death_cause[-1])
## AbstractCreature Actions
def creature_eat(self, creature):
if creature.energy() < ConfigBiology.MOVE_ENERGY:
self.kill_creature(creature)
return
creature.reduce_energy(ConfigBiology.MOVE_ENERGY)
available_food = creature.cell().get_food()
meal = min(ConfigBiology.MEAL_SIZE, available_food)
creature.add_energy(meal)
creature.cell().remove_food(meal)
def creature_move_left(self, creature):
self.move_creature(creature, Actions.LEFT)
def creature_move_right(self, creature):
self.move_creature(creature, Actions.RIGHT)
def creature_move_up(self, creature):
self.move_creature(creature, Actions.UP)
def creature_move_down(self, creature):
self.move_creature(creature, Actions.DOWN)
def move_creature(self, creature, direction):
if creature.energy() < ConfigBiology.MOVE_ENERGY:
self.kill_creature(creature)
return
creature.reduce_energy(ConfigBiology.MOVE_ENERGY)
i, j = creature.coord()
if direction == Actions.RIGHT:
rel_dim_coord = j
if rel_dim_coord == ConfigPhysics.SPACE_SIZE - 1:
if not ConfigPhysics.SLIPPERY_SPACE:
return
self.kill_creature(creature, "fall")
return
self.space().remove_creature(creature)
new_cell = self.space().insert_creature(creature, (i, j + 1))
creature.update_cell(new_cell)
if direction == Actions.LEFT:
rel_dim_coord = j
if rel_dim_coord == 0:
if not ConfigPhysics.SLIPPERY_SPACE:
return
self.kill_creature(creature, "fall")
return
self.space().remove_creature(creature)
new_cell = self.space().insert_creature(creature, (i, j - 1))
creature.update_cell(new_cell)
if direction == Actions.UP:
rel_dim_coord = i
if rel_dim_coord == 0:
if not ConfigPhysics.SLIPPERY_SPACE:
return
self.kill_creature(creature, "fall")
return
self.space().remove_creature(creature)
new_cell = self.space().insert_creature(creature, (i - 1, j))
creature.update_cell(new_cell)
if direction == Actions.DOWN:
rel_dim_coord = i
if rel_dim_coord == ConfigPhysics.SPACE_SIZE - 1:
if not ConfigPhysics.SLIPPERY_SPACE:
return
self.kill_creature(creature, "fall")
return
self.space().remove_creature(creature)
new_cell = self.space().insert_creature(creature, (i + 1, j))
creature.update_cell(new_cell)
def creature_mate(self, creature):
if creature.age() < ConfigBiology.MATURITY_AGE:
if creature.energy() < ConfigBiology.MOVE_ENERGY:
self.kill_creature(creature)
return
creature.reduce_energy(ConfigBiology.MOVE_ENERGY)
return
if creature.energy() < ConfigBiology.MATE_ENERGY:
self.kill_creature(creature)
return
creature.reduce_energy(ConfigBiology.MATE_ENERGY)
potential_spouses = self.space().get_nearby_creatures_from_same_race(creature)
spouse = creature.select_spouse(potential_spouses)
if spouse is None:
return
new_dna = Evolution.mix_dna(creature.dna(), spouse.dna())
self.create_creature(creature.get_race(), self.allocate_id(), new_dna, creature.coord(),
parents=[creature, spouse])
def creature_divide(self, creature):
if creature.age() < ConfigBiology.MATURITY_AGE:
if creature.energy() < ConfigBiology.MOVE_ENERGY:
self.kill_creature(creature)
return
creature.reduce_energy(ConfigBiology.MOVE_ENERGY)
return
self.create_creature(creature.get_race(), self.allocate_id(), dna=Evolution.mutate_dna(creature.dna()),
coord=creature.coord(),
energy=int(creature.energy() / 2) + 1,
parents=[creature])
creature.reduce_energy(amount=int(creature.energy() / 2))
creature._age = 1
def creature_fight(self, creature):
if creature.energy() < ConfigBiology.FIGHT_ENERGY:
self.kill_creature(creature, 'fight')
return
creature.reduce_energy(ConfigBiology.FIGHT_ENERGY)
if creature.self_race_enemy():
opponent = self.space().find_nearby_creature(creature)
else:
opponent = self.space().find_nearby_creature_from_different_race(creature)
if opponent is None:
return
opponent_support = creature.cell().race_energy_level(opponent.get_race()) - opponent.energy()
creature_support = creature.cell().race_energy_level(creature.get_race()) - creature.energy()
fight_res = utils.roll_fight(creature.energy() + creature_support, opponent.energy() + opponent_support)
if fight_res == -1:
energy_trans = int(opponent.energy() / 2)
creature.add_energy(energy_trans)
opponent.reduce_energy(energy_trans)
else:
energy_trans = int(creature.energy() / 2)
opponent.add_energy(energy_trans)
creature.reduce_energy(energy_trans)
def creature_work(self, creature):
self.statistics.action_dist[Actions.enum_to_index(Actions.WORK)] += 1
if creature.energy() < ConfigBiology.WORK_ENERGY:
self.kill_creature(creature, 'work')
return
creature.reduce_energy(ConfigBiology.WORK_ENERGY)
creature.cell().add_food(ConfigBiology.MEAL_SIZE)
def creature_vocalize(self, creature):
self.statistics.action_dist[Actions.enum_to_index(Actions.VOCALIZE)] += 1
if creature.energy() < ConfigBiology.VOCALIZE_ENERGY:
self.kill_creature(creature, 'vocalize')
return
if [s for s in creature.cell().get_sounds() if s.creature() != creature]:
creature.add_energy(2)
creature.reduce_energy(ConfigBiology.VOCALIZE_ENERGY)
creature.cell().add_sound(Sound(creature, self._time))