|
|
@@ -1,443 +0,0 @@
|
|
1
|
|
-# coding: utf-8
|
|
2
|
|
-import typing
|
|
3
|
|
-from random import choice
|
|
4
|
|
-
|
|
5
|
|
-from sandbox.engulf.const import COLLECTION_GRASS, COLLECTION_CELL, COLLECTION_ALIVE, COLLECTION_PREY
|
|
6
|
|
-from sandbox.engulf.exceptions import NotFoundWhereToGo
|
|
7
|
|
-from synergine2.simulation import Event
|
|
8
|
|
-from synergine2.simulation import SubjectBehaviour, SimulationMechanism, SimulationBehaviour, SubjectBehaviourSelector
|
|
9
|
|
-from synergine2.utils import ChunkManager
|
|
10
|
|
-from synergine2_xyz.xyz import DIRECTIONS, DIRECTION_SLIGHTLY, \
|
|
11
|
|
- get_direction_from_north_degree
|
|
12
|
|
-from synergine2_xyz.mechanism import ProximitySubjectMechanism
|
|
13
|
|
-from synergine2_xyz.utils import get_around_positions_of_positions, get_position_for_direction
|
|
14
|
|
-
|
|
15
|
|
-# Import for typing hint
|
|
16
|
|
-if False:
|
|
17
|
|
- from sandbox.engulf.subject import Grass
|
|
18
|
|
- from sandbox.engulf.subject import PreyCell
|
|
19
|
|
-
|
|
20
|
|
-
|
|
21
|
|
-class GrassGrownUp(Event):
|
|
22
|
|
- def __init__(self, subject_id, density, *args, **kwargs):
|
|
23
|
|
- super().__init__(*args, **kwargs)
|
|
24
|
|
- self.subject_id = subject_id
|
|
25
|
|
- self.density = density
|
|
26
|
|
-
|
|
27
|
|
- def repr_debug(self) -> str:
|
|
28
|
|
- return '{}: subject_id:{}, density:{}'.format(
|
|
29
|
|
- self.__class__.__name__,
|
|
30
|
|
- self.subject_id,
|
|
31
|
|
- self.density,
|
|
32
|
|
- )
|
|
33
|
|
-
|
|
34
|
|
-
|
|
35
|
|
-class GrassSpawn(Event):
|
|
36
|
|
- def __init__(self, subject_id, position, density, *args, **kwargs):
|
|
37
|
|
- super().__init__(*args, **kwargs)
|
|
38
|
|
- self.subject_id = subject_id
|
|
39
|
|
- self.position = position
|
|
40
|
|
- self.density = density
|
|
41
|
|
-
|
|
42
|
|
- def repr_debug(self) -> str:
|
|
43
|
|
- return '{}: subject_id:{}, position:{}, density:{}'.format(
|
|
44
|
|
- self.__class__.__name__,
|
|
45
|
|
- self.subject_id,
|
|
46
|
|
- self.position,
|
|
47
|
|
- self.density,
|
|
48
|
|
- )
|
|
49
|
|
-
|
|
50
|
|
-
|
|
51
|
|
-class GrassSpotablePositionsMechanism(SimulationMechanism):
|
|
52
|
|
- parallelizable = True
|
|
53
|
|
-
|
|
54
|
|
- def run(self, process_number: int=None, process_count: int=None):
|
|
55
|
|
- chunk_manager = ChunkManager(process_count)
|
|
56
|
|
- positions = list(self.simulation.subjects.grass_xyz.keys())
|
|
57
|
|
- positions_chunks = chunk_manager.make_chunks(positions)
|
|
58
|
|
- spotables = []
|
|
59
|
|
-
|
|
60
|
|
- for position in positions_chunks[process_number]:
|
|
61
|
|
- arounds = get_around_positions_of_positions(position)
|
|
62
|
|
- from_subject = self.simulation.subjects.grass_xyz[position][0]
|
|
63
|
|
- around_data = {
|
|
64
|
|
- 'from_subject': from_subject,
|
|
65
|
|
- 'around': [],
|
|
66
|
|
- }
|
|
67
|
|
- for around in arounds:
|
|
68
|
|
- if around not in self.simulation.subjects.grass_xyz and self.simulation.is_possible_position(around):
|
|
69
|
|
- around_data['around'].append(around)
|
|
70
|
|
-
|
|
71
|
|
- if around_data['around']:
|
|
72
|
|
- spotables.append(around_data)
|
|
73
|
|
-
|
|
74
|
|
- return spotables
|
|
75
|
|
-
|
|
76
|
|
-
|
|
77
|
|
-class GrowUp(SubjectBehaviour):
|
|
78
|
|
- frequency = 20
|
|
79
|
|
-
|
|
80
|
|
- def run(self, data):
|
|
81
|
|
- return True
|
|
82
|
|
-
|
|
83
|
|
- def action(self, data) -> [Event]:
|
|
84
|
|
- self.subject.density += 1
|
|
85
|
|
- return [GrassGrownUp(
|
|
86
|
|
- self.subject.id,
|
|
87
|
|
- self.subject.density,
|
|
88
|
|
- )]
|
|
89
|
|
-
|
|
90
|
|
-
|
|
91
|
|
-class GrassSpawnBehaviour(SimulationBehaviour):
|
|
92
|
|
- frequency = 100
|
|
93
|
|
- use = [GrassSpotablePositionsMechanism]
|
|
94
|
|
-
|
|
95
|
|
- def run(self, data):
|
|
96
|
|
- spawns = []
|
|
97
|
|
-
|
|
98
|
|
- for around_data in data[GrassSpotablePositionsMechanism]:
|
|
99
|
|
- from_subject = around_data['from_subject']
|
|
100
|
|
- arounds = around_data['around']
|
|
101
|
|
- if from_subject.density >= 40:
|
|
102
|
|
- spawns.extend(arounds)
|
|
103
|
|
-
|
|
104
|
|
- return spawns
|
|
105
|
|
-
|
|
106
|
|
- @classmethod
|
|
107
|
|
- def merge_data(cls, new_data, start_data=None):
|
|
108
|
|
- start_data = start_data or []
|
|
109
|
|
- start_data.extend(new_data)
|
|
110
|
|
- return start_data
|
|
111
|
|
-
|
|
112
|
|
- def action(self, data) -> [Event]:
|
|
113
|
|
- from sandbox.engulf.subject import Grass # cyclic
|
|
114
|
|
- events = []
|
|
115
|
|
-
|
|
116
|
|
- for position in data:
|
|
117
|
|
- if position not in list(self.simulation.subjects.grass_xyz.keys()):
|
|
118
|
|
- new_grass = Grass(
|
|
119
|
|
- config=self.config,
|
|
120
|
|
- simulation=self.simulation,
|
|
121
|
|
- position=position,
|
|
122
|
|
- density=20,
|
|
123
|
|
- )
|
|
124
|
|
- self.simulation.subjects.append(new_grass)
|
|
125
|
|
- events.append(GrassSpawn(
|
|
126
|
|
- new_grass.id,
|
|
127
|
|
- new_grass.position,
|
|
128
|
|
- new_grass.density,
|
|
129
|
|
- ))
|
|
130
|
|
-
|
|
131
|
|
- return events
|
|
132
|
|
-
|
|
133
|
|
-
|
|
134
|
|
-class GrassEatableDirectProximityMechanism(ProximitySubjectMechanism):
|
|
135
|
|
- distance = 1.41 # distance when on angle
|
|
136
|
|
- feel_collections = [COLLECTION_GRASS]
|
|
137
|
|
-
|
|
138
|
|
- def acceptable_subject(self, subject: 'Grass') -> bool:
|
|
139
|
|
- return subject.density >= self.config.simulation.eat_grass_required_density
|
|
140
|
|
-
|
|
141
|
|
-
|
|
142
|
|
-class PreyEatableDirectProximityMechanism(ProximitySubjectMechanism):
|
|
143
|
|
- distance = 1.41 # distance when on angle
|
|
144
|
|
- feel_collections = [COLLECTION_CELL]
|
|
145
|
|
-
|
|
146
|
|
- def acceptable_subject(self, subject: 'PreyCell') -> bool:
|
|
147
|
|
- # TODO: N'attaquer que des "herbivores" ?
|
|
148
|
|
- from sandbox.engulf.subject import PreyCell # cyclic
|
|
149
|
|
- return isinstance(subject, PreyCell)
|
|
150
|
|
-
|
|
151
|
|
-
|
|
152
|
|
-class MoveTo(Event):
|
|
153
|
|
- def __init__(self, subject_id: int, position: tuple, *args, **kwargs):
|
|
154
|
|
- super().__init__(*args, **kwargs)
|
|
155
|
|
- self.subject_id = subject_id
|
|
156
|
|
- self.position = position
|
|
157
|
|
-
|
|
158
|
|
- def repr_debug(self) -> str:
|
|
159
|
|
- return '{}: subject_id:{}, position:{}'.format(
|
|
160
|
|
- type(self).__name__,
|
|
161
|
|
- self.subject_id,
|
|
162
|
|
- self.position,
|
|
163
|
|
- )
|
|
164
|
|
-
|
|
165
|
|
-
|
|
166
|
|
-class EatEvent(Event):
|
|
167
|
|
- def __init__(self, eaten_id: int, eater_id: int, eaten_new_density: float, *args, **kwargs):
|
|
168
|
|
- super().__init__(*args, **kwargs)
|
|
169
|
|
- self.eaten_id = eaten_id
|
|
170
|
|
- self.eater_id = eater_id
|
|
171
|
|
- self.eaten_new_density = eaten_new_density
|
|
172
|
|
-
|
|
173
|
|
-
|
|
174
|
|
-class EatenEvent(Event):
|
|
175
|
|
- def __init__(self, eaten_id: int, *args, **kwargs):
|
|
176
|
|
- super().__init__(*args, **kwargs)
|
|
177
|
|
- self.eaten_id = eaten_id
|
|
178
|
|
-
|
|
179
|
|
-
|
|
180
|
|
-class AttackEvent(Event):
|
|
181
|
|
- def __init__(self, attacker_id: int, attacked_id: int, *args, **kwargs):
|
|
182
|
|
- super().__init__(*args, **kwargs)
|
|
183
|
|
- self.attacker_id = attacker_id
|
|
184
|
|
- self.attacked_id = attacked_id
|
|
185
|
|
-
|
|
186
|
|
-
|
|
187
|
|
-class SearchFood(SubjectBehaviour):
|
|
188
|
|
- mechanism_data_class = NotImplemented
|
|
189
|
|
-
|
|
190
|
|
- def get_required_appetite(self) -> float:
|
|
191
|
|
- raise NotImplementedError()
|
|
192
|
|
-
|
|
193
|
|
- def run(self, data):
|
|
194
|
|
- if self.subject.appetite < self.get_required_appetite():
|
|
195
|
|
- return False
|
|
196
|
|
-
|
|
197
|
|
- if not data[self.mechanism_data_class]:
|
|
198
|
|
- return False
|
|
199
|
|
-
|
|
200
|
|
- direction_degrees = [d['direction'] for d in data[self.mechanism_data_class]]
|
|
201
|
|
- return get_direction_from_north_degree(choice(direction_degrees))
|
|
202
|
|
-
|
|
203
|
|
- def action(self, data) -> [Event]:
|
|
204
|
|
- direction = data
|
|
205
|
|
- position = get_position_for_direction(self.subject.position, direction)
|
|
206
|
|
- self.subject.position = position
|
|
207
|
|
- self.subject.previous_direction = direction
|
|
208
|
|
-
|
|
209
|
|
- return [MoveTo(self.subject.id, position)]
|
|
210
|
|
-
|
|
211
|
|
-
|
|
212
|
|
-class SearchGrass(SearchFood):
|
|
213
|
|
- """
|
|
214
|
|
- Si une nourriture a une case de distance et cellule non rassasié, move dans sa direction.
|
|
215
|
|
- """
|
|
216
|
|
- use = [GrassEatableDirectProximityMechanism]
|
|
217
|
|
- mechanism_data_class = use[0]
|
|
218
|
|
-
|
|
219
|
|
- def get_required_appetite(self) -> float:
|
|
220
|
|
- return self.config.simulation.search_food_appetite_required
|
|
221
|
|
-
|
|
222
|
|
-
|
|
223
|
|
-class SearchPrey(SearchFood):
|
|
224
|
|
- """
|
|
225
|
|
- Si une nourriture a une case de distance et cellule non rassasié, move dans sa direction.
|
|
226
|
|
- """
|
|
227
|
|
- use = [PreyEatableDirectProximityMechanism]
|
|
228
|
|
- mechanism_data_class = use[0]
|
|
229
|
|
-
|
|
230
|
|
- def get_required_appetite(self) -> float:
|
|
231
|
|
- return self.config.simulation.search_and_attack_prey_apetite_required
|
|
232
|
|
-
|
|
233
|
|
-
|
|
234
|
|
-class EatGrass(SubjectBehaviour):
|
|
235
|
|
- def run(self, data):
|
|
236
|
|
- if self.subject.appetite < self.config.simulation.eat_grass_required_density:
|
|
237
|
|
- return False
|
|
238
|
|
-
|
|
239
|
|
- for grass in self.simulation.collections.get(COLLECTION_GRASS, []):
|
|
240
|
|
- # TODO: Use simulation/xyz pre calculated indexes
|
|
241
|
|
- if grass.position == self.subject.position:
|
|
242
|
|
- return grass.id
|
|
243
|
|
-
|
|
244
|
|
- def action(self, data) -> [Event]:
|
|
245
|
|
- subject_id = data
|
|
246
|
|
-
|
|
247
|
|
- grass = self.simulation.subjects.index[subject_id] # TODO: cas ou grass disparu ?
|
|
248
|
|
- grass.density -= self.config.simulation.eat_grass_density_reduction
|
|
249
|
|
-
|
|
250
|
|
- self.subject.appetite -= self.config.simulation.eat_grass_appetite_reduction
|
|
251
|
|
-
|
|
252
|
|
- # TODO: Comment mettre des logs (ne peuvent pas être passé aux subprocess)?
|
|
253
|
|
-
|
|
254
|
|
- return [EatEvent(
|
|
255
|
|
- eater_id=self.subject.id,
|
|
256
|
|
- eaten_id=subject_id,
|
|
257
|
|
- eaten_new_density=grass.density,
|
|
258
|
|
- )]
|
|
259
|
|
-
|
|
260
|
|
-
|
|
261
|
|
-class EatPrey(SubjectBehaviour):
|
|
262
|
|
- def run(self, data):
|
|
263
|
|
- if self.subject.appetite < self.config.simulation.search_and_attack_prey_apetite_required:
|
|
264
|
|
- return False
|
|
265
|
|
-
|
|
266
|
|
- for prey in self.simulation.collections.get(COLLECTION_PREY, []):
|
|
267
|
|
- # TODO: Use simulation/xyz pre calculated indexes
|
|
268
|
|
- if prey.position == self.subject.position:
|
|
269
|
|
- return prey.id
|
|
270
|
|
-
|
|
271
|
|
- def action(self, data) -> [Event]:
|
|
272
|
|
- subject_id = data
|
|
273
|
|
-
|
|
274
|
|
- # Cell already eaten ?
|
|
275
|
|
- if subject_id not in self.simulation.subjects.index:
|
|
276
|
|
- return []
|
|
277
|
|
-
|
|
278
|
|
- prey = self.simulation.subjects.index[subject_id]
|
|
279
|
|
- self.simulation.subjects.remove(prey)
|
|
280
|
|
- self.subject.appetite -= self.config.simulation.eat_prey_required_density
|
|
281
|
|
-
|
|
282
|
|
- return [EatenEvent(
|
|
283
|
|
- eaten_id=prey.id,
|
|
284
|
|
- )]
|
|
285
|
|
-
|
|
286
|
|
-
|
|
287
|
|
-class Explore(SubjectBehaviour):
|
|
288
|
|
- """
|
|
289
|
|
- Produit un mouvement au hasard (ou un immobilisme)
|
|
290
|
|
- """
|
|
291
|
|
- use = []
|
|
292
|
|
-
|
|
293
|
|
- def run(self, data):
|
|
294
|
|
- # TODO: Il faut pouvoir dire tel behaviour concerne que tel collections
|
|
295
|
|
- if COLLECTION_ALIVE not in self.subject.collections:
|
|
296
|
|
- return False
|
|
297
|
|
-
|
|
298
|
|
- return True
|
|
299
|
|
-
|
|
300
|
|
- def action(self, data) -> [Event]:
|
|
301
|
|
- try:
|
|
302
|
|
- position, direction = self.get_random_position_and_direction()
|
|
303
|
|
- self.subject.position = position
|
|
304
|
|
- self.subject.previous_direction = direction
|
|
305
|
|
- return [MoveTo(self.subject.id, position)]
|
|
306
|
|
- except NotFoundWhereToGo:
|
|
307
|
|
- return []
|
|
308
|
|
-
|
|
309
|
|
- def get_random_position_and_direction(self) -> tuple:
|
|
310
|
|
- attempts = 0
|
|
311
|
|
-
|
|
312
|
|
- while attempts <= 5:
|
|
313
|
|
- attempts += 1
|
|
314
|
|
- direction = self.get_random_direction()
|
|
315
|
|
- position = get_position_for_direction(self.subject.position, direction)
|
|
316
|
|
-
|
|
317
|
|
- if self.simulation.is_possible_subject_position(self.subject, position):
|
|
318
|
|
- return position, direction
|
|
319
|
|
-
|
|
320
|
|
- # If blocked, permit any direction (not slightly)
|
|
321
|
|
- if attempts >= 3:
|
|
322
|
|
- self.subject.previous_direction = None
|
|
323
|
|
-
|
|
324
|
|
- raise NotFoundWhereToGo()
|
|
325
|
|
-
|
|
326
|
|
- def get_random_direction(self):
|
|
327
|
|
- if not self.subject.previous_direction:
|
|
328
|
|
- return choice(DIRECTIONS)
|
|
329
|
|
- return choice(DIRECTION_SLIGHTLY[self.subject.previous_direction])
|
|
330
|
|
-
|
|
331
|
|
-
|
|
332
|
|
-class Hungry(SubjectBehaviour):
|
|
333
|
|
- def run(self, data):
|
|
334
|
|
- return True
|
|
335
|
|
-
|
|
336
|
|
- def action(self, data) -> [Event]:
|
|
337
|
|
- self.subject.appetite += self.config.simulation.hungry_reduction
|
|
338
|
|
- return []
|
|
339
|
|
-
|
|
340
|
|
- def get_random_direction(self):
|
|
341
|
|
- if not self.subject.previous_direction:
|
|
342
|
|
- return choice(DIRECTIONS)
|
|
343
|
|
- return choice(DIRECTION_SLIGHTLY[self.subject.previous_direction])
|
|
344
|
|
-
|
|
345
|
|
-
|
|
346
|
|
-class Attack(SubjectBehaviour):
|
|
347
|
|
- use = [PreyEatableDirectProximityMechanism]
|
|
348
|
|
-
|
|
349
|
|
- def run(self, data):
|
|
350
|
|
- if self.subject.appetite < self.config.simulation.search_and_attack_prey_apetite_required:
|
|
351
|
|
- return False
|
|
352
|
|
-
|
|
353
|
|
- eatable_datas = data[PreyEatableDirectProximityMechanism]
|
|
354
|
|
- attackable_datas = []
|
|
355
|
|
-
|
|
356
|
|
- for eatable_data in eatable_datas:
|
|
357
|
|
- if COLLECTION_ALIVE in eatable_data['subject'].collections:
|
|
358
|
|
- attackable_datas.append(eatable_data)
|
|
359
|
|
-
|
|
360
|
|
- if attackable_datas:
|
|
361
|
|
- return choice(attackable_datas)
|
|
362
|
|
- return False
|
|
363
|
|
-
|
|
364
|
|
- def action(self, data) -> [Event]:
|
|
365
|
|
- attacked = self.simulation.subjects.index[data['subject'].id]
|
|
366
|
|
-
|
|
367
|
|
- try:
|
|
368
|
|
- # TODO il faut automatiser/Refactoriser le fait de retirer/ajouter un collection
|
|
369
|
|
- self.simulation.collections[COLLECTION_ALIVE].remove(attacked)
|
|
370
|
|
- attacked.collections.remove(COLLECTION_ALIVE)
|
|
371
|
|
- except ValueError:
|
|
372
|
|
- pass # On considere qu'il a ete tué par une autre, TODO: en être sur ?
|
|
373
|
|
-
|
|
374
|
|
- return [AttackEvent(attacker_id=self.subject.id, attacked_id=data['subject'].id)]
|
|
375
|
|
-
|
|
376
|
|
-
|
|
377
|
|
-class CellBehaviourSelector(SubjectBehaviourSelector):
|
|
378
|
|
- # If behaviour in sublist, only one be kept in sublist
|
|
379
|
|
- behaviour_hierarchy = ( # TODO: refact it
|
|
380
|
|
- (
|
|
381
|
|
- EatPrey,
|
|
382
|
|
- EatGrass, # TODO: Introduce priority with appetite
|
|
383
|
|
- Attack,
|
|
384
|
|
- SearchPrey,
|
|
385
|
|
- SearchGrass, # TODO: Introduce priority with appetite
|
|
386
|
|
- Explore,
|
|
387
|
|
- ),
|
|
388
|
|
- )
|
|
389
|
|
-
|
|
390
|
|
- def reduce_behaviours(
|
|
391
|
|
- self,
|
|
392
|
|
- behaviours: typing.Dict[typing.Type[SubjectBehaviour], object],
|
|
393
|
|
- ) -> typing.Dict[typing.Type[SubjectBehaviour], object]:
|
|
394
|
|
- reduced_behaviours = {} # type: typing.Dict[typing.Type[SubjectBehaviour], object]
|
|
395
|
|
-
|
|
396
|
|
- for behaviour_class, behaviour_data in behaviours.items():
|
|
397
|
|
- if not self.behaviour_class_in_sublist(behaviour_class):
|
|
398
|
|
- reduced_behaviours[behaviour_class] = behaviour_data
|
|
399
|
|
- elif self.behaviour_class_is_prior(behaviour_class, behaviours):
|
|
400
|
|
- reduced_behaviours[behaviour_class] = behaviour_data
|
|
401
|
|
-
|
|
402
|
|
- return reduced_behaviours
|
|
403
|
|
-
|
|
404
|
|
- def behaviour_class_in_sublist(self, behaviour_class: typing.Type[SubjectBehaviour]) -> bool:
|
|
405
|
|
- for sublist in self.behaviour_hierarchy:
|
|
406
|
|
- if behaviour_class in sublist:
|
|
407
|
|
- return True
|
|
408
|
|
- return False
|
|
409
|
|
-
|
|
410
|
|
- def behaviour_class_is_prior(
|
|
411
|
|
- self,
|
|
412
|
|
- behaviour_class: typing.Type[SubjectBehaviour],
|
|
413
|
|
- behaviours: typing.Dict[typing.Type[SubjectBehaviour], object],
|
|
414
|
|
- ) -> bool:
|
|
415
|
|
- for sublist in self.behaviour_hierarchy:
|
|
416
|
|
- if behaviour_class in sublist:
|
|
417
|
|
- behaviour_position = sublist.index(behaviour_class)
|
|
418
|
|
- other_behaviour_top_position = self.get_other_behaviour_top_position(
|
|
419
|
|
- behaviour_class,
|
|
420
|
|
- behaviours,
|
|
421
|
|
- sublist,
|
|
422
|
|
- )
|
|
423
|
|
- if other_behaviour_top_position is not None and behaviour_position > other_behaviour_top_position:
|
|
424
|
|
- return False
|
|
425
|
|
- return True
|
|
426
|
|
-
|
|
427
|
|
- def get_other_behaviour_top_position(
|
|
428
|
|
- self,
|
|
429
|
|
- exclude_behaviour_class,
|
|
430
|
|
- behaviours,
|
|
431
|
|
- sublist,
|
|
432
|
|
- ) -> typing.Union[None, int]:
|
|
433
|
|
- position = None
|
|
434
|
|
- for behaviour_class in behaviours.keys():
|
|
435
|
|
- if behaviour_class != exclude_behaviour_class:
|
|
436
|
|
- try:
|
|
437
|
|
- behaviour_position = sublist.index(behaviour_class)
|
|
438
|
|
- if position is None or behaviour_position < position:
|
|
439
|
|
- position = behaviour_position
|
|
440
|
|
- except ValueError:
|
|
441
|
|
- pass
|
|
442
|
|
-
|
|
443
|
|
- return position
|