diff --git a/mesa/examples/basic/boltzmann_wealth_model/agents.py b/mesa/examples/basic/boltzmann_wealth_model/agents.py index 35c8e6b1014..f293b9068a5 100644 --- a/mesa/examples/basic/boltzmann_wealth_model/agents.py +++ b/mesa/examples/basic/boltzmann_wealth_model/agents.py @@ -1,7 +1,7 @@ -from mesa import Agent +from mesa.discrete_space import CellAgent -class MoneyAgent(Agent): +class MoneyAgent(CellAgent): """An agent with fixed initial wealth. Each agent starts with 1 unit of wealth and can give 1 unit to other agents @@ -11,28 +11,23 @@ class MoneyAgent(Agent): wealth (int): The agent's current wealth (starts at 1) """ - def __init__(self, model): + def __init__(self, model, cell): """Create a new agent. Args: model (Model): The model instance that contains the agent """ super().__init__(model) + self.cell = cell self.wealth = 1 def move(self): """Move the agent to a random neighboring cell.""" - possible_steps = self.model.grid.get_neighborhood( - self.pos, moore=True, include_center=False - ) - new_position = self.random.choice(possible_steps) - self.model.grid.move_agent(self, new_position) + self.cell = self.cell.neighborhood.select_random_cell() def give_money(self): """Give 1 unit of wealth to a random agent in the same cell.""" - cellmates = self.model.grid.get_cell_list_contents([self.pos]) - # Remove self from potential recipients - cellmates.pop(cellmates.index(self)) + cellmates = [a for a in self.cell.agents if a is not self] if cellmates: # Only give money if there are other agents present other = self.random.choice(cellmates) diff --git a/mesa/examples/basic/boltzmann_wealth_model/model.py b/mesa/examples/basic/boltzmann_wealth_model/model.py index 21dbaf63e19..53076cf0e24 100644 --- a/mesa/examples/basic/boltzmann_wealth_model/model.py +++ b/mesa/examples/basic/boltzmann_wealth_model/model.py @@ -9,8 +9,8 @@ from mesa import Model from mesa.datacollection import DataCollector +from mesa.discrete_space import OrthogonalMooreGrid from mesa.examples.basic.boltzmann_wealth_model.agents import MoneyAgent -from mesa.space import MultiGrid class BoltzmannWealth(Model): @@ -39,22 +39,18 @@ def __init__(self, n=100, width=10, height=10, seed=None): super().__init__(seed=seed) self.num_agents = n - self.grid = MultiGrid(width, height, torus=True) + self.grid = OrthogonalMooreGrid((width, height), random=self.random) # Set up data collection self.datacollector = DataCollector( model_reporters={"Gini": self.compute_gini}, agent_reporters={"Wealth": "wealth"}, ) - - # Create and place the agents - for _ in range(self.num_agents): - agent = MoneyAgent(self) - - # Add agent to random grid cell - x = self.random.randrange(self.grid.width) - y = self.random.randrange(self.grid.height) - self.grid.place_agent(agent, (x, y)) + MoneyAgent.create_agents( + self, + self.num_agents, + self.random.choices(self.grid.all_cells.cells, k=self.num_agents), + ) self.running = True self.datacollector.collect(self)