from mesa import Agent
from mesa import Model
from mesa.examples.basic.conways_game_of_life.agents import Cell
from mesa.space import HexSingleGrid
from mesa.examples.basic.conways_game_of_life.model import ConwaysGameOfLife
from mesa.visualization import (
SolaraViz,
make_space_component,
)
import numpy as np
import matplotlib.pyplot as plt
import solara
from matplotlib import image
import matplotlib
# from svgpathtools import svg2paths
# from svgpath2mpl import parse_path
# planet_path, attributes = svg2paths('car.svg')
# planet_marker = parse_path(attributes[0]['d'])
# planet_marker.vertices -= planet_marker.vertices.mean(axis=0)
# planet_marker = planet_marker.transformed(matplotlib.transforms.Affine2D().rotate_deg(180))
# planet_marker = planet_marker.transformed(matplotlib.transforms.Affine2D().scale(-1,1))
class Car(Agent):
def __init__(self, pos, model):
super().__init__(model)
self.x, self.y = pos
def drive(self):
# self.x += np.random.randint(0, 2)
self.x +=1
self.model.grid.move_agent(self, (self.x, self.y))
@property
def neighbors(self):
return self.model.grid.iter_neighbors((self.x, self.y), True)
class CarSimulation(Model):
def __init__(self, width=50, height=2, amount=10, seed=None):
super().__init__(seed=seed)
self.grid = HexSingleGrid(width, height, torus=True)
for i in range(amount):
cell = Car((i*2, 0), self)
self.grid.place_agent(cell, (i*2, 0))
self.running = True
def step(self):
self.agents.do("drive")
def agent_portrayal(agent):
if (isinstance(agent, Car)):
return {
"color": "red",
"marker": "8", # hexagon
"size": 50,
}
def post_process(ax):
ax.set_aspect("equal")
ax.set_xticks([])
ax.set_yticks([])
ax.set_facecolor("gray")
model_params = {
"seed": {
"type": "InputText",
"value": 42,
"label": "Random Seed",
},
"width": {
"type": "SliderInt",
"value": 50,
"label": "Width",
"min": 5,
"max": 600,
"step": 1,
},
"height": {
"type": "SliderInt",
"value": 50,
"label": "Height",
"min": 5,
"max": 60,
"step": 1,
},
}
model1 = CarSimulation()
SpaceGraph = make_space_component(
agent_portrayal, post_process=post_process, draw_grid=False
)
page = SolaraViz(
model1,
components=[SpaceGraph],
model_params=model_params,
name="Car Simulation",
)
page