Category: School Projects

Porting the Observer Pattern to Python

Porting a simplified version of the Weather Observer program to Python proved to be pretty straight forward, especially since most of the classes and methods were already provided to us ported over. The one issue I initially encountered came when I tried to implement humidity into the display. My first thought was to simply copy the following method:

    def setTemperature(self, temperature):
        self.temperature = temperature
        self.notifyObservers()

and create another version for Humidity:

    def setHumidity(self, humidity):
        self.humidity = humidity
        self.notifyObservers()

I then would call each method in the driver to set a value using:

weatherData.setTemperature(78.0)
weatherData.setHumidity(30.0)

The problem with this was that as soon as the program got through the setTemperature method it would then notify the observers without running through the setHumidity method and the output would initially be 78.0 and None, rather than 78.0 and 30.0.

When I finally tracked down what was happening it occurred to me to make a single setMeasurements method as below:

    def setMeasurements(self, temperature, humidity):
        self.temperature = temperature
        self.humidity = humidity
        self.notifyObservers()
weatherData.setMeasurements(78.0, 30.0)

Once I implemented those changes the appropriate output was produced:

Current Conditions: 78.0F degrees and 30.0% humidity
Advertisements

Step-by-Step: Using the Observer Pattern

1. Create two interfaces: Observable and Observer.

2. The Observable interface should contain the following methods:

  • registerObserver() – registers Observers to receive updates
  • removeObserver() – removes Observers from receive updates
  • notifyObservers() – notify Observers of an updates using Push/Pull
  • setChanged() – Optional, but let’s you control what updates should be sent

3. The Observer interface should contain the following method:

  • update() – retrieves updated data from the Observable for Observers

Reflections on Using the Observer Pattern

I’m not sure I entirely grasp how to implement the observer pattern in my project as of yet, but I want virtually everything (except for the locations) to have the ability to interact amongst each other. My simulation, as previously noted, will be based around Godzilla rampaging through several locales in which he will be able to destroy inanimate objects such as buildings, trees, and boats and engage in battle with animates such as military, battleships, tanks, and Mothra. In each scenario there will need to be communication between objects about their position relative to each other. Godzilla in-particular will need to be updated with the status of these objects as each of them will be able to be destroyed/killed which should be Godzilla’s queue to move on. Conversely these objects will need to be updated when they are being attacked by Godzilla so that they know to fight back, die, or run away.

Strategy Pattern TestDriver

Here is a simple driver that tests the code I posted here: https://jasonjkeller.wordpress.com/2013/01/25/my-strategy-pattern-strategy/

__author__ = ‘jasonjkeller’

from GodzillaSim import *

def main():

godzilla = Godzilla()
godzilla.performDeclare()
godzilla.performMove()
godzilla.performAttacks()

mothra = Mothra()
mothra.performDeclare()
mothra.performMove()
mothra.performAttacks()

civilian = Civilian()
civilian.performDeclare()
civilian.performMove()

military = Military()
military.performDeclare()
military.performMove()
military.performAttacks()

battleship = Battleship()
battleship.performDeclare()
battleship.performMove()
battleship.performAttacks()

tank = Tank()
tank.performDeclare()
tank.performMove()
tank.performAttacks()
boat = Boat()
boat.Display()

building = Building()
building.Display()

tree = Tree()
tree.Display()

oceanbg = OceanBG()
oceanbg.Display()

citybg = CityBG()
citybg.Display()

main()

 

 

Here is the output produced by the driver:

 

/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python /Users/jasonjkeller/PycharmProjects/GodzillaSim/GodzillaSimDriver.py
Godzilla declares: ROOOAAAAAR!!!
I’m walking around!
I’m breathing fire at you!
Mothra declares: BZZZzzz!!!
I’m flying around!
I’m shooting a laser beam at you!
Civilian declares: Run for your life!!!
I’m running away!
Military declares: Fire your weapons!!!
I’m walking around!
I’m shooting my gun at you!
Battleship declares: Fire your battleship weapons!!!
I’m floating around!
I’m shooting my gun at you!
Tank declares: Fire your tank cannon!!!
I’m driving around!
I’m shooting my gun at you!
I am an inanimate boat.
I am an inanimate building.
I am an inanimate tree.
I am an Ocean location.
I am a City location.

Process finished with exit code 0

My “Strategy Pattern” Strategy

EDIT: Sorry, I can’t seem to get my code to paste into this blog while keeping the spacing and indentation that I use in PyCharm. 😦

I’m not sure if I’m generalizing too much or not, but I saw an opportunity to utilize the strategy pattern by creating a few interfaces (classes) that implement shared, but different, behaviors for almost all of my animate classes. For instance, I currently have the following animate classes: Monster (subclasses: Godzilla, Mothra), People (subclasses: Civilian, Military), and Vehicles (subclasses: Battleship, Tank). Each class implements all of the following interfaces (with the exception being that Civilians don’t attack at all): MoveBehavior (different ways of moving around), AttackBehavior (different ways of attacking), and DeclareBehavior (different ways of talking or declaring themselves). Within each of those interfaces is different methods for achieving the actions of moving, attacking, and declaring (in an audible manner) themselves.

One thing I don’t really understand is how to implement my inanimates and locations. Being that we’re using OO programming my first instinct is to create a class for each so I ended up with the following classes:

Inanimates: Boat, Building, Tree

Locations: Ocean, City

Being that I don’t really know what else to do with these, I simply created a Display method in each class which prints a line of text saying what they are. The locations are meant to simply be backgrounds, as are the three inanimates, with the exception that I want the three inanimates (Boat, Building, Tree) to be destroyable by Godzilla either breathing fire or punching them.

This leads me to one issue with my AttackBehavior interface, I wanted to have two subclasses AttackFireBreath and AttackPunch that could both be utilized by Godzilla. I’m not sure if it’s possible to have Godzilla choose the appropriate behavior based on context if I’m using a simple interface. For instance in the Godzilla class (subclass of Monster) I currently just have self.attackBehavior = AttackFireBreath() but if I also implemented self.attackBehavior = AttackPunch() then how do I get him to choose between the two? Say I want him to breath fire at trees, boats, people but punch Mothra, battleships, buildings, and tanks. Can I do that with how I currently have the interface set up? Is it something that can be implemented by using the Observer pattern?

Here’s a copy of my current code:

__author__ = ‘jasonjkeller’

 
#interface for move behaviors
class MoveBehavior(object):
def move(self):
pass

class MoveWalk(MoveBehavior):
def move(self):
print “I’m walking around!”

class MoveRunAway(MoveBehavior):
def move(self):
print “I’m running away!”

class MoveFly(MoveBehavior):
def move(self):
print “I’m flying around!”

class MoveFloat(MoveBehavior):
def move(self):
print “I’m floating around!”

class MoveDrive(MoveBehavior):
def move(self):
print “I’m driving around!”

 
#interface for attack behaviors
class AttackBehavior(object):
def attack(self):
pass

class AttackFireBreath(AttackBehavior):
def attack(self):
print “I’m breathing fire at you!”

class AttackLaserBeam(AttackBehavior):
def attack(self):
print “I’m shooting a laser beam at you!”

class AttackPunch(AttackBehavior):
def attack(self):
print “I’m punching you!”

class AttackShootGun(AttackBehavior):
def attack(self):
print “I’m shooting my gun at you!”

 

 

#interface for declare behaviors
class DeclareBehavior(object):
def declare(self):
pass

class DeclareGodzilla(DeclareBehavior):
def declare(self):
print “Godzilla declares: ROOOAAAAAR!!!”

class DeclareMothra(DeclareBehavior):
def declare(self):
print “Mothra declares: BZZZzzz!!!”

class DeclareCivilian(DeclareBehavior):
def declare(self):
print “Civilian declares: Run for your life!!!”

class DeclareMilitary(DeclareBehavior):
def declare(self):
print “Military declares: Fire your weapons!!!”

class DeclareBattleship(DeclareBehavior):
def declare(self):
print “Battleship declares: Fire your battleship weapons!!!”

class DeclareTank(DeclareBehavior):
def declare(self):
print “Tank declares: Fire your tank cannon!!!”

 

# Monster superclass
class Monster(object):
moveBehavior = MoveBehavior()
attackBehavior = AttackBehavior()
declareBehavior = DeclareBehavior()
def setMoveBehavior(self, cb):
self.moveBehavior = cb

def setAttackBehavior(self, ab):
self.attackBehavior = ab

def setDeclareBehavior(self, yb):
self.declareBehavior = yb

def display(self):
pass

def performMove(self):
self.moveBehavior.move()

def performAttacks(self):
self.attackBehavior.attack()

def performDeclare(self):
self.declareBehavior.declare()

def isDead(self):
pass

class Godzilla(Monster):
“””a subclass of Monster”””
def __init__(self):

self.attackBehavior = AttackFireBreath()
self.moveBehavior = MoveWalk()
self.declareBehavior = DeclareGodzilla()

def display(self):
print “I’m Godzilla!!!”

class Mothra(Monster):
“””a subclass of Monster”””
def __init__(self):

self.attackBehavior = AttackLaserBeam()
self.moveBehavior = MoveFly()
self.declareBehavior = DeclareMothra()

def display(self):
print “I’m Mothra!!!”

 

 

# People superclass
class People(object):
moveBehavior = MoveBehavior()
attackBehavior = AttackBehavior()
declareBehavior = DeclareBehavior()
def setMoveBehavior(self, cb):
self.moveBehavior = cb

def setAttackBehavior(self, ab):
self.attackBehavior = ab

def setDeclareBehavior(self, yb):
self.declareBehavior = yb

def display(self):
pass

def performMove(self):
self.moveBehavior.move()

def performAttacks(self):
self.attackBehavior.attack()

def performDeclare(self):
self.declareBehavior.declare()

def isDead(self):
pass

class Civilian(People):
“””a subclass of People”””
def __init__(self):

self.moveBehavior = MoveRunAway()
self.declareBehavior = DeclareCivilian()

def display(self):
print “We’re just civilians!!!”

class Military(People):
“””a subclass of People”””
def __init__(self):

self.moveBehavior = MoveWalk()
self.attackBehavior = AttackShootGun()
self.declareBehavior = DeclareMilitary()

def display(self):
print “We’re the military!!!”

 
# Vehicle superclass
class Vehicle(object):
moveBehavior = MoveBehavior()
attackBehavior = AttackBehavior()
declareBehavior = DeclareBehavior()
def setMoveBehavior(self, cb):
self.moveBehavior = cb

def setAttackBehavior(self, ab):
self.attackBehavior = ab

def setDeclareBehavior(self, yb):
self.declareBehavior = yb

def display(self):
pass

def performMove(self):
self.moveBehavior.move()

def performAttacks(self):
self.attackBehavior.attack()

def performDeclare(self):
self.declareBehavior.declare()

def isDead(self):
pass

class Battleship(Vehicle):
“””a subclass of Vehicle”””
def __init__(self):

self.moveBehavior = MoveFloat()
self.attackBehavior = AttackShootGun()
self.declareBehavior = DeclareBattleship()

def display(self):
print “I’m a battleship!!!”

class Tank(Vehicle):
“””a subclass of Vehicle”””
def __init__(self):

self.moveBehavior = MoveDrive()
self.attackBehavior = AttackShootGun()
self.declareBehavior = DeclareTank()

def display(self):
print “I’m a tank!!!”

 
# inanimate classes
class Boat(object):
def Display(self):
print “I am an inanimate boat.”

class Building(object):
def Display(self):
print “I am an inanimate building.”

class Tree(object):
def Display(self):
print “I am an inanimate tree.”

class OceanBG(object):
def Display(self):
print “I am an Ocean location.”

class CityBG(object):
def Display(self):
print “I am a City location.”

Jumble Solver

The purpose of this assignment was to write a program, using the Python programming language, which was capable of taking as input any scrambled word and producing as output a list of all possible unscrambled words according to a dictionary document. The output would also produce a string of text documenting how many unscrambled words were found out of the total number of words in the dictionary document.

The IO looks like the following (python3  program_name  scrambled_word  dictionary_document):

$ python3 jumbler.py trsesi dict.txt
resist
sister
2 matches from 41238 words

A link to the final code: jumbler.py  dict.txt