Skip to content

Commit dcaf243

Browse files
committed
examples/wolf_sheep: Don't allow dump moves
Agents now move completely random in WolfSheep. That makes no sense whatsoever, so this PR makes them move a little bit less dump. - Wolf moves to random cell with sheep on them, if available (otherwise completely random) - Sheep move to a random cell without a wolf (if available), and preferably with grass. This enables sheep to actually "search" for grass, wolfs to search for sheep and sheep to not move to a cell with wolves. More importantly, it shows of some nice selection mechanics with the cell space.
1 parent 54d7e28 commit dcaf243

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

mesa/examples/advanced/wolf_sheep/agents.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ def feed(self):
3737
def step(self):
3838
"""Execute one step of the animal's behavior."""
3939
# Move to random neighboring cell
40-
self.cell = self.cell.neighborhood.select_random_cell()
40+
self.move()
41+
4142
self.energy -= 1
4243

4344
# Try to feed
@@ -62,6 +63,27 @@ def feed(self):
6263
self.energy += self.energy_from_food
6364
grass_patch.fully_grown = False
6465

66+
def move(self):
67+
"""Move towards a cell where there isn't a wolf, and preferably with grown grass."""
68+
cells_without_wolves = self.cell.neighborhood.select(
69+
lambda cell: not any(isinstance(obj, Wolf) for obj in cell.agents)
70+
)
71+
# If all surrounding cells have wolves, stay put
72+
if len(cells_without_wolves) == 0:
73+
return
74+
75+
# Among safe cells, prefer those with grown grass
76+
cells_with_grass = cells_without_wolves.select(
77+
lambda cell: any(
78+
isinstance(obj, GrassPatch) and obj.fully_grown for obj in cell.agents
79+
)
80+
)
81+
# Move to a cell with grass if available, otherwise move to any safe cell
82+
target_cells = (
83+
cells_with_grass if len(cells_with_grass) > 0 else cells_without_wolves
84+
)
85+
self.cell = target_cells.select_random_cell()
86+
6587

6688
class Wolf(Animal):
6789
"""A wolf that walks around, reproduces (asexually) and eats sheep."""
@@ -74,6 +96,16 @@ def feed(self):
7496
self.energy += self.energy_from_food
7597
sheep_to_eat.remove()
7698

99+
def move(self):
100+
"""Move to a neighboring cell, preferably one with sheep."""
101+
cells_with_sheep = self.cell.neighborhood.select(
102+
lambda cell: any(isinstance(obj, Sheep) for obj in cell.agents)
103+
)
104+
target_cells = (
105+
cells_with_sheep if len(cells_with_sheep) > 0 else self.cell.neighborhood
106+
)
107+
self.cell = target_cells.select_random_cell()
108+
77109

78110
class GrassPatch(FixedAgent):
79111
"""A patch of grass that grows at a fixed rate and can be eaten by sheep."""

0 commit comments

Comments
 (0)