import mesa
from mesa.visualization import SolaraViz, make_space_component
# 1. Создаем класс агента
class MoneyAgent(mesa.Agent):
def __init__(self, model):
# ИСПРАВЛЕНО: Передаем уникальный ID автоматической генерации и модель
super().__init__(model.next_id(), model)
self.wealth = 1
def step(self):
if self.wealth == 0:
return
# Перемещаемся в случайную соседнюю клетку
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)
# Если на новой клетке есть другие агенты, отдаем одному из них монету
cell_mates = self.model.grid.get_cell_list_contents([self.pos])
if len(cell_mates) > 1:
other_agent = self.random.choice(cell_mates)
if other_agent != self:
other_agent.wealth += 1
self.wealth -= 1
# 2. Создаем класс модели
class MoneyModel(mesa.Model):
def __init__(self, width=15, height=15, n_agents=40):
super().__init__()
self.grid = mesa.space.MultiGrid(width, height, torus=True)
for _ in range(n_agents):
agent = MoneyAgent(self)
self.grid.place_agent(agent, self.grid.find_empty())
def step(self):
# ИСПРАВЛЕНО: Новый синтаксис запуска шага для всех агентов в Mesa 3.0
self.agents.do("step")
# 3. Настраиваем внешний вид агентов
def agent_portrayal(agent):
if agent.wealth == 0:
color = "tab:red"
elif agent.wealth == 1:
color = "tab:blue"
else:
color = "tab:green"
return {"type": "circle", "color": color, "size": 60}
# 4. Параметры для слайдеров в UI
model_params = {
"n_agents": {
"type": "SliderInt",
"value": 40,
"label": "Число участников",
"min": 10,
"max": 100,
}
}
# 5. Инициализируем интерфейс SolaraViz
page = SolaraViz(
model_class=MoneyModel,
model_params=model_params,
components=[make_space_component(agent_portrayal)]
)