Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

examples/wolf_sheep: Don't allow dumb moves #2503

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion mesa/examples/advanced/wolf_sheep/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
def step(self):
"""Execute one step of the animal's behavior."""
# Move to random neighboring cell
self.cell = self.cell.neighborhood.select_random_cell()
self.move()

self.energy -= 1

# Try to feed
Expand All @@ -62,6 +63,27 @@
self.energy += self.energy_from_food
grass_patch.fully_grown = False

def move(self):
"""Move towards a cell where there isn't a wolf, and preferably with grown grass."""
cells_without_wolves = self.cell.neighborhood.select(
lambda cell: not any(isinstance(obj, Wolf) for obj in cell.agents)
)
# If all surrounding cells have wolves, stay put
if len(cells_without_wolves) == 0:
return

Check warning on line 73 in mesa/examples/advanced/wolf_sheep/agents.py

View check run for this annotation

Codecov / codecov/patch

mesa/examples/advanced/wolf_sheep/agents.py#L73

Added line #L73 was not covered by tests

# Among safe cells, prefer those with grown grass
cells_with_grass = cells_without_wolves.select(
lambda cell: any(
isinstance(obj, GrassPatch) and obj.fully_grown for obj in cell.agents
)
)
# Move to a cell with grass if available, otherwise move to any safe cell
target_cells = (
cells_with_grass if len(cells_with_grass) > 0 else cells_without_wolves
)
self.cell = target_cells.select_random_cell()


class Wolf(Animal):
"""A wolf that walks around, reproduces (asexually) and eats sheep."""
Expand All @@ -74,6 +96,16 @@
self.energy += self.energy_from_food
sheep_to_eat.remove()

def move(self):
"""Move to a neighboring cell, preferably one with sheep."""
cells_with_sheep = self.cell.neighborhood.select(
lambda cell: any(isinstance(obj, Sheep) for obj in cell.agents)
)
target_cells = (
cells_with_sheep if len(cells_with_sheep) > 0 else self.cell.neighborhood
)
self.cell = target_cells.select_random_cell()


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