-
Notifications
You must be signed in to change notification settings - Fork 0
/
organism.py
368 lines (311 loc) · 14.9 KB
/
organism.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
#
# Dan Clark
# thedanclark@gmail.com
# 15 June 2013
#
# organism.py
# Ecosystem
#
from util import Location
from util import LOGGING
from util import getOrganismsInRadius
from util import getLivingOrganismsInRadiusWithType
from util import clip
import graphics
import random
import world
import config
import abc # For abstract base class
class Organism(metaclass=abc.ABCMeta):
def __init__(self, createWithSpawnRing):
self.isAlive = True
self.age = 0
self.location = Location(0,0)
self.hasSpawnRing = createWithSpawnRing
self.spawnRingRadius = config.Organism.SPAWN_RING_STARTING_RADIUS
# Draw the Organism
@abc.abstractmethod
def draw(self):
pass
# Draw an expanding ring around a newly spawned Organism to highlight
# its location
def drawSpawnRing(self, screen):
if self.hasSpawnRing:
# TODO: Would it look better if this faded as it expanded?
graphics.pygame.draw.circle(
screen,
graphics.COLORS['orange'],
[self.location.x, self.location.y],
self.spawnRingRadius,
config.Organism.SPAWN_RING_WIDTH)
# Returns an instance of the Organism (a non-abstract subclass).
# @todo Is there a more pythonic way to do this?
@abc.abstractmethod
def createOffspring(self):
pass
# Run one unit of time for the organism
def doTurn(self):
self.age += 1
if self.hasSpawnRing:
if self.spawnRingRadius >= config.Organism.SPAWN_RING_MAX_RADIUS:
self.hasSpawnRing = False
self.spawnRingRadius = 0
else:
self.spawnRingRadius += config.Organism.SPAWN_RING_RADIUS_INCREMENT
# Returns true if should reproduce this turn, false othewise.
def shouldReproduce(self):
timeSinceLastReproduction = self.age - self.lastReproductionAge
probabilityOfReproduction = min(1.0, timeSinceLastReproduction / self.maxTimeBetweenReproduction)
return random.random() < probabilityOfReproduction
# Attempt to place a new Organism at a nearby location. If it's too crowded
# to place another Organism, give up after a specified number of attempts.
def reproduce(self):
newOrganism = self.createOffspring()
attemptsToReproduce = 0
while attemptsToReproduce < self.maxAttemptsToReproduce:
potentialLocation = world.randomLocationInCircle(self.location, self.reproductionRadius)
if LOGGING:
print(self, "attempting to reproduce at", potentialLocation)
if world.canFit(newOrganism, potentialLocation):
newOrganism = self.createOffspring()
newOrganism.location = potentialLocation
world.organisms.append(newOrganism)
return
attemptsToReproduce += 1
class Plant(Organism):
def __init__(self, createWithSpawnRing):
super().__init__(createWithSpawnRing)
self.size = config.Plant.SIZE
self.lastReproductionAge = 0
self.maxTimeBetweenReproduction = config.Plant.MAX_TIME_BETWEEN_REPRODUCTION
self.reproductionRadius = config.Plant.REPRODUCTION_RADIUS
self.maxAttemptsToReproduce = config.Plant.MAX_ATTEMPTS_TO_REPRODUCE
def draw(self):
assert self.isAlive
self.drawSpawnRing(graphics.screen)
graphics.pygame.draw.circle(graphics.screen, graphics.COLORS['green'],
[self.location.x, self.location.y], self.size)
def doTurn(self):
super().doTurn()
if LOGGING:
print("Age of plant is", self.age, "lastReproductionAge:", self.lastReproductionAge)
if self.shouldReproduce():
if LOGGING:
print("Plant", self, "reproducing")
self.lastReproductionAge = self.age
self.reproduce()
def createOffspring(self):
return Plant(False)
class Animal(Organism):
# Take one step in the direction of the Animal's current destination
def takeStep(self):
if abs(self.location.x - self.destination.x) <= self.speed:
self.location.x = self.destination.x
else:
self.location.x += self.speed if self.location.x < self.destination.x \
else -self.speed if self.location.x > self.destination.x else 0
if abs(self.location.y - self.destination.y) <= self.speed:
self.location.y = self.destination.y
self.location.y += self.speed if self.location.y < self.destination.y \
else -self.speed if self.location.y > self.destination.y else 0
# Returns true if the Animal has arrived at their destination, false otherwise
def hasArrivedAtDestination(self):
return (abs(self.location.x - self.destination.x) < config.Animal.REACHED_LOCATION_TOLERANCE
and abs(self.location.y - self.destination.y) < config.Animal.REACHED_LOCATION_TOLERANCE)
# Returns true if the Animal will try to eat if there is food available
def isHungry(self):
return self.timeSinceLastEaten >= self.timeToHunger
# End the Animal's life if it has starved
def dieIfStarved(self):
if self.timeSinceLastEaten >= self.timeToStarvation:
assert self.isHungry()
self.isAlive = False
def drawStatusBars(self):
bottomStatusBarLocation = Location(self.location.x, int(self.location.y - 1.5 * self.size))
graphics.drawStatusBar(bottomStatusBarLocation,
int(2.0 * self.size),
clip((self.timeToStarvation - self.timeSinceLastEaten) / (self.timeToStarvation - self.timeToHunger), 0.0, 1.0))
graphics.drawStatusBar(Location(bottomStatusBarLocation.x, int(bottomStatusBarLocation.y - 1.2 * graphics.STATUS_BAR_HEIGHT)),
int(2.0 * self.size),
clip((self.timeToHunger - self.timeSinceLastEaten) / self.timeToHunger, 0.0, 1.0))
class Herbivore(Animal):
def __init__(self, createWithSpawnRing):
super().__init__(createWithSpawnRing)
self.size = config.Herbivore.SIZE
self.speed = config.Herbivore.SPEED
self.destination = self.getNewDestination()
self.timeSinceLastEaten = 0
self.timeToHunger = config.Herbivore.TIME_TO_HUNGER
self.timeToStarvation = config.Herbivore.TIME_TO_STARVATION
self.sightRadius = config.Herbivore.SIGHT_RADIUS # The radius within which the Herbivore can see food
self.maxEatRadius = config.Herbivore.MAX_EAT_RADIUS # The radius within which the Herbivore can reach food
self.prey = None # Is the Herbivore chasing a particular prey organism
self.lastReproductionAge = 0
self.maxTimeBetweenReproduction = config.Herbivore.MAX_TIME_BETWEEN_REPRODUCTION
self.reproductionRadius = config.Herbivore.REPRODUCTION_RADIUS # Radius within which children are created
self.maxAttemptsToReproduce = config.Herbivore.MAX_ATTEMPTS_TO_REPRODUCE
def draw(self):
assert self.isAlive
assert self.prey is None or self.isHungry()
if self.isHungry() and not self.prey is None:
color = graphics.COLORS['blue']
graphics.pygame.draw.line(graphics.screen, graphics.COLORS['red'],
[self.location.x, self.location.y],
[self.prey.location.x, self.prey.location.y], 1)
elif self.isHungry():
# Fade between colors as the Herbivore gets hungrier
color = graphics.getTransitionColor(graphics.COLORS['blue'],
graphics.COLORS['grey'],
float(self.timeSinceLastEaten) / self.timeToStarvation)
else:
color = graphics.COLORS['blue']
self.drawSpawnRing(graphics.screen)
graphics.pygame.draw.circle(graphics.screen, color,
[self.location.x, self.location.y], self.size)
self.drawStatusBars()
def doTurn(self):
super().doTurn()
if self.shouldReproduce():
if LOGGING:
print("Herbivore", self, "reproducing")
self.lastReproductionAge = self.age
self.reproduce()
# Stop chasing prey if it's not there anymore
if not self.prey is None:
if not self.prey.isAlive:
self.prey = None
self.takeStep()
self.timeSinceLastEaten += 1
assert self.prey is None or self.isHungry()
if self.isHungry():
atePrey = self.tryToEat()
if atePrey and not self.prey is None:
# If the Herbivore successfully chased down and ate prey, now it needs
# something else to do.
self.prey = None
self.destination = self.getNewDestination()
if self.isHungry() and (self.prey is None or self.hasArrivedAtDestination()):
# Look for prey to chase down.
potentialPrey = self.findPrey()
if len(potentialPrey) > 0:
self.destination = potentialPrey[0].location
self.prey = potentialPrey[0]
else:
self.prey = None
self.dieIfStarved()
if self.hasArrivedAtDestination():
self.destination = self.getNewDestination()
if LOGGING:
print("Age of Herbivore is", self.age)
# Returns a new location for the Herbivore.
def getNewDestination(self):
return world.randomLocation()
# Returns a list of living prey organisms within sight.
def findPrey(self):
return getLivingOrganismsInRadiusWithType(world.organisms, self.location, self.sightRadius, Plant)
# If there is a prey Organism within range of this Herbivore, remove it from the world
# and set this Herbivore's timeSinceLastEaten to 0.
# Returns True if prey was successfully eaten, False otherwise.
def tryToEat(self):
nearbyOrganisms = getLivingOrganismsInRadiusWithType(world.organisms, self.location, self.maxEatRadius, Plant)
if len(nearbyOrganisms) > 0:
# Eat the unfortunate prey
nearbyOrganisms[0].isAlive = False
self.timeSinceLastEaten = 0
return True
else:
return False
def createOffspring(self):
return Herbivore(False)
class Carnivore(Animal):
def __init__(self, createWithSpawnRing):
super().__init__(createWithSpawnRing)
self.size = config.Carnivore.SIZE
self.speed = config.Carnivore.SPEED
self.destination = self.getNewDestination()
self.timeSinceLastEaten = 0
self.timeToHunger = config.Carnivore.TIME_TO_HUNGER
self.timeToStarvation = config.Carnivore.TIME_TO_STARVATION
self.sightRadius = config.Carnivore.SIGHT_RADIUS # The radius within which the Carnivore can see food
self.maxEatRadius = config.Carnivore.MAX_EAT_RADIUS # The radius within which the Carnivore can reach food
self.lastReproductionAge = 0
self.maxTimeBetweenReproduction = config.Carnivore.MAX_TIME_BETWEEN_REPRODUCTION
self.reproductionRadius = config.Carnivore.REPRODUCTION_RADIUS # Radius within which children are created
self.maxAttemptsToReproduce = config.Carnivore.MAX_ATTEMPTS_TO_REPRODUCE
self.prey = None
def draw(self):
assert self.isAlive
assert self.prey is None or self.isHungry()
self.drawSpawnRing(graphics.screen)
if self.isHungry() and not self.prey is None:
color = graphics.COLORS['blue']
graphics.pygame.draw.line(graphics.screen, graphics.COLORS['red'],
[self.location.x, self.location.y],
[self.prey.location.x, self.prey.location.y], 1)
elif self.isHungry():
# Fade between colors as the Carnivore gets hungrier
color = graphics.getTransitionColor(graphics.COLORS['blue'],
graphics.COLORS['grey'],
float(self.timeSinceLastEaten) / self.timeToStarvation)
else:
color = graphics.COLORS['blue']
graphics.pygame.draw.circle(graphics.screen, color,
[self.location.x, self.location.y], self.size)
self.drawStatusBars()
def doTurn(self):
super().doTurn()
if self.shouldReproduce():
if LOGGING:
print(self.__class__.__name__, self, "reproducing")
self.lastReproductionAge = self.age
self.reproduce()
# Continue chasing prey
if not self.prey is None:
if not self.prey.isAlive:
self.prey = None
else:
self.destination = self.prey.location
self.takeStep()
self.timeSinceLastEaten += 1
assert self.prey is None or self.isHungry()
if self.isHungry():
atePrey = self.tryToEat()
if atePrey:
# If the Carnivore successfully chased down and ate prey, now it needs
# something else to do.
self.destination = self.getNewDestination()
if self.isHungry() and (self.prey is None or self.hasArrivedAtDestination()):
# Look for prey to chase down.
potentialPrey = self.findPrey()
if len(potentialPrey) > 0:
self.prey = potentialPrey[0]
self.destination = self.prey.location
else:
assert self.prey is None or self.hasArrivedAtDestina
self.prey = None
self.dieIfStarved()
if self.hasArrivedAtDestination():
self.destination = self.getNewDestination()
if LOGGING:
print("Age of", self.__class__.__name__, "is", self.age)
# If there is a prey Organism within range of this Carnivore, remove it from the world
# and set this Carnivore's timeSinceLastEaten to 0.
# Returns True if prey was successfully eaten, False otherwise.
def tryToEat(self):
nearbyOrganisms = getLivingOrganismsInRadiusWithType(world.organisms, self.location, self.maxEatRadius, Herbivore)
if len(nearbyOrganisms) > 0:
# Eat the unfortunate prey
nearbyOrganisms[0].isAlive = False
self.timeSinceLastEaten = 0
self.prey = None
return True
else:
return False
# Returns a new location for the Herbivore.
def getNewDestination(self):
return world.randomLocation()
# Returns a list of living prey organisms within sight.
def findPrey(self):
return getLivingOrganismsInRadiusWithType(world.organisms, self.location, self.sightRadius, Herbivore)
def createOffspring(self):
return Carnivore(False)