Skip to content

Commit 5105dde

Browse files
committed
adding heading information and created move_forward_or_backward function, which calculates the next position the agent will move. move_forward function, which moves the agent forward by specified amount. move_backward function, which moves the agent backwards by specified amount. turn_right function, turns the agent right by specified degree. turn_left function, turns the agent left by specified degree.
1 parent 241924d commit 5105dde

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

mesa/agent.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ def __init__(self, unique_id: int, model: "Model") -> None:
2828
self.unique_id = unique_id
2929
self.model = model
3030
self.pos: Optional[Position] = None
31+
self.heading = 90
3132

3233
def step(self) -> None:
3334
"""A single step of the agent."""
@@ -36,6 +37,33 @@ def step(self) -> None:
3637
def advance(self) -> None:
3738
pass
3839

40+
def move_forward_or_backward(self, amount, sign):
41+
"""Does the calculation to find the agent's next move and is used within the forward and backward functions"""
42+
new_x = float(self.pos[0]) + sign * math.cos(self.heading * math.pi / 180) * amount
43+
new_y = float(self.pos[1]) + sign * math.sin(self.heading * math.pi / -180) * amount
44+
next_pos = (new_x, new_y)
45+
try:
46+
self.model.space.move_agent(self, next_pos)
47+
except:
48+
print("agent.py (forward_backwards): could not move agent within self.model.space")
49+
50+
def move_forward(self, amount):
51+
"""Moves the agent forward by the amount given"""
52+
self.move_forward_or_backward(amount, 1)
53+
54+
def move_backward(self, amount):
55+
"""Moves the agent backwards from where its facing by the given amount"""
56+
self.move_forward_or_backward(amount, -1)
57+
58+
def turn_right(self, degree):
59+
"""Turns the agent right by the given degree"""
60+
self.heading = (self.heading - degree) % 360
61+
62+
def turn_left(self, degree):
63+
"""Turns the agent left by the given degree"""
64+
self.heading = (self.heading + degree) % 360
65+
66+
3967
@property
4068
def random(self) -> Random:
4169
return self.model.random

0 commit comments

Comments
 (0)