-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlaba.py
More file actions
89 lines (67 loc) · 2.63 KB
/
Copy pathlaba.py
File metadata and controls
89 lines (67 loc) · 2.63 KB
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
# Расширьте код этой программы, добавив новые классы Grass, Flower, Vine, Snail, Rabbit, Wolf. Интегрируйте их в экосистему, заменив обобщенные Animal и Plant
import matplotlib.pyplot as plt
import random
class Creature:
def __init__(self, name, count):
self.name = name
self.count = count
def step(self, ecosystem=None):
pass
class Plant(Creature):
def __init__(self, name, count, growth_rate=0.2, max_count=100):
super().__init__(name, count)
self.growth_rate = growth_rate
self.max_count = max_count
def step(self, ecosystem=None):
B = self.count
self.count += self.growth_rate * B * (1 - B / self.max_count) # simple constant growth
class Animal(Creature):
def __init__(self, name, count, bite_size, diet):
super().__init__(name, count)
self.bite_size = bite_size
self.diet = diet
def step(self, ecosystem):
edible = [c for c in ecosystem.creatures
if isinstance(c, tuple(self.diet)) and c.count > 0]
if not edible:
return
target = random.choice(edible)
eaten = min(target.count, self.bite_size)
target.count -= eaten
self.count += eaten * 0.5
class Ecosystem:
def __init__(self, creatures):
self.creatures = creatures
self.history = {c: [] for c in creatures}
def step(self):
for c in self.creatures:
if isinstance(c, Plant):
c.step()
for c in self.creatures:
if isinstance(c, Animal):
c.step(self)
# remove dead creatures
self.creatures = [c for c in self.creatures if c.count > 0]
for c in list(self.history.keys()):
if c in self.creatures:
self.history[c].append(c.count)
else:
# creature died → keep count at 0
self.history[c].append(0)
def plot(self):
for creature, biomass_list in self.history.items():
plt.plot(biomass_list, label=creature.name)
plt.xlabel("Step")
plt.ylabel("Biomass")
plt.legend()
plt.show()
# Example usage:
if name == "__main__":
eco = Ecosystem([
Plant("Grass1", 5),
Plant("Grass2", 6),
Animal("Rabbit", 4, bite_size=2, diet=[Plant])
])
for _ in range(50):
eco.step()
eco.plot()