MCS 275 Spring 2024
Emily Dumas
Reminders and announcements:
Finish our robot simulation class hierarchy
Discuss more OOP theory & practice
WanderBot
walks about randomly.
DestructBot
sits for a while and deactivates.
PatrolBot
walks back and forth.Now there are two simulation programs:
botsimulation.py
- Active bots shown as *
botsimulation_fancy.py
- Bots have their own symbols, inactive ones
are shown as ☠.Classes: Cat
, Dog
, Vector2
, WanderBot
Instances of Cat
:
Instances of Vector2
:
self.*
assignments in constructor like
class Cat(Pet):
def __init__(self, age, fur_color):
# other stuff...
self.age = age # applies to *this* cat
self.fur_color = fur_color # applies to *this* cat
add attributes to the instance. They are therefore called instance attributes.
Often initialized from __init__
arguments and modified by methods.
Attributes can also be declared in the class definition, outside of any method. Then they are shared by every instance and are called class attributes. E.g.
class Cat(Pet):
retractable_claws = True # Applies to all cats
Typically used for constants (never changed).
Natural to use class attributes for:
WanderBot
selects its step fromTakes direction
(vector) and n
(int). Walks n
steps of size
direction
, then n
steps of size -direction
. Repeats
indefinitely.
This robot has internal state:
Keep track of which state we're in. Handle input differently depending on the state. Fixed set of possible states.
if state == "work":
handle_at_work(sms_content)
elif state == "home":
handle_at_home(sms_content)
Handlers may change state depending on the input.
def handle_at_home(sms_content):
if announces_critical_outage(sms_content):
send_reply("on my way")
state = "work"
else:
# deal with it tomorrow
return
Beyond adding more robot types, how might me improve or extend the simulation?
Might create a class Arena
that manages the list of bots and the space in which they
move. Would have a single .update()
method that updates all bots.
Arena
object would be made first, then passed to each robots constructor.
Robots would call Arena
methods to interrogate surroundings (e.g. avoid collision, seek
other
bots, ...)