Showing posts with label object. Show all posts
Showing posts with label object. Show all posts

Thursday, March 3, 2011

Python - rock paper scissors game from the command line

# Here is a command line Rock Paper Scissor game. 
# As you can see by my output I am not so good. ;) 
 
import random
 
class RockPaperScissors():
    """ 
        Play Rock Paper Scissors with Python CLI! 
    """ 
    def __init__(self):
        # setup the random chooser for the computer 
        self.rand = random.Random()
        self.cScore = 0 # computer score 
        self.hScore = 0 # human score 
    def getComputerMove(self):
        return self.rand.randrange(1,4)
    def getHumanMove(self):
        while True:
            choice = input("Make your move: rock (1), paper (2), scissors(3): ")
            choice = choice.strip()
            if choice == "1" or choice == "rock":
                return 1
            if choice == "2" or choice == "paper":
                return 2
            if choice == "3" or choice == "scissors":
                return 3
            print("I didn't understand your choice. Please try again")
    def decideWinner(self, c, h):
        """ 
        rock breaks scissors 
        paper covers rock 
        scissors cuts paper 
        """ 
        if (c, h) == (1, 3):
            print("rock breaks scissors")
            print("computer wins")
            self.cScore+=1
        elif (h, c) == (1, 3):
            print("rock breaks scissors")
            print("you win")
            self.hScore+=1
        elif (c, h) == (2, 1):
            print("paper covers rock")
            print("computer wins")
            self.cScore+=1
        elif (h, c) == (2, 1):
            print("paper covers rock")
            print("you win")
            self.hScore+=1
        elif (c, h) == (3, 2):
            print("scissors cuts paper")
            print("computer wins")
            self.cScore+=1
        elif (h, c) == (3, 2):
            print("scissors cuts paper")
            print("you win")   
            self.hScore+=1
        else:
            print("Tie!")
 
    def showScore(self):
        print("Score:")
        print("Computer: ", self.cScore, " You: ", self.hScore)
 
    def playAgain(self):
        yn = input("Play Again? (y/n):  ")
        yn = yn.strip()
        yn = yn.lower()
        if yn == "n" or yn == "no":
            return False
        return True
 
    def gameLoop(self):
        while True:
            print()
            print()
            computerMove = self.getComputerMove()
            humanMove = self.getHumanMove()
            print()
            print("you chose: ", humanMove, " computer chose: ", computerMove)
            self.decideWinner(computerMove, humanMove)
            print()
            self.showScore()
            if self.playAgain() == False:
                return 
 
if __name__ == '__main__':
    rps = RockPaperScissors()
    rps.gameLoop()
    
 
## my output: 
## Make your move: rock (1), paper (2), scissors(3): 2 
## 
## you chose:  2  computer chose:  3 
## scissors cuts paper 
## computer wins 
## 
## Score: 
## Computer:  1  You:  0 
## Play Again? (y/n):  y 
## 
## 
## Make your move: rock (1), paper (2), scissors(3): 1 
## 
## you chose:  1  computer chose:  1 
## Tie! 
## 
## Score: 
## Computer:  1  You:  0 
## Play Again? (y/n):  y 
## 
## 
## Make your move: rock (1), paper (2), scissors(3): 3 
## 
## you chose:  3  computer chose:  1 
## rock breaks scissors 
## computer wins 
## 
## Score: 
## Computer:  2  You:  0 
 
 

Monday, July 26, 2010

Python - simple event programming

# simple event programming with python 
# this example is written in p3k ... but can 
# be easily ported to 2.x 
 
# Event Thrower 
class QueenBee(object):
    def __init__(self):
        self.subscriber_to_event_list = []
    def addSubscriberToEvent(self, subscriber, eventText):
        ''' subscribe bees to eventText commands ''' 
        se = (subscriber, eventText)
        self.subscriber_to_event_list.append(se)
    def issueCommand(self, eventText):
        ''' raise event to followers ''' 
        for se in self.subscriber_to_event_list:
            sub = se[0]
            eve = se[1]
            if eve == eventText:
                sub(eve)
 
# event subscriber 
class WorkerBee(object):
    def __init__(self, name, event):
        self.name = name
    def receiveEvent(self, eventName):
        ''' begin work from here ''' 
        print (self.name + " 'By Your Command,' received event: " + eventName)
 
 
 
 
 
qb = QueenBee()
# worker bees 
bList = []
# subscribe bees to commands (events) 
for i in range(10):
    bName = "b"+str(i)
    eventText = "Do More Work" 
    b = WorkerBee(bName, eventText)
    qb.addSubscriberToEvent(b.receiveEvent, eventText)
    bList.append(b)
 
# queen bee issues command that bees are not subscribed to 
print("unscribed to command output: ")
qb.issueCommand("make me a sandwhich")
# nothing happens 
 
print()
print("subscribed event issued:")
# queen bee issues subscribed to event 
qb.issueCommand("Do More Work")
 
 
 
 

Wednesday, April 7, 2010

Python - event programming example

# Event programming in python

# Python doesn't have a standard 'only' way
# of doing events.  You can create your own
# pythonic events like so.
#

# In the example you'll notice that the Musician
# handles all the recieved events.  You could
# have just as easily created specific event
# handlers for the reacting classes.  Whatever

# makes sense for your application is good.
# Python is flexible!
#
# This would be a way that
# python could implement events or delegates.

import time

# Important class that will raise events
class Orchestrator(object):
    def __init__(self):
        # You'll notice that the events instances

        # of the subscribers are stored in these
        # lists.  Having a list allows multiple
        # subscribers to the event.
        self.armsRaise = []
        self.pointsAtMe = []
    def subscribeToArmRaiseEvent(self, event):
        # we append the instance methods to the

        # event lists
        self.armsRaise.append(event)
    def subscribeToPointsAtMeEvent(self, event):
        # we append the instance methods to the
        # event lists

        self.pointsAtMe.append(event)
    def raiseArmRaiseEvent(self):
        # iterating through the lists we call
        # each of the instance methods
        for i in self.armsRaise:
            i("Arms Raised")
    def raisePointsAtMeEvent(self):
        # iterating through the lists we call

        # each of the instance methods
        for i in self.pointsAtMe:
            i("Points at me")
    def raiseArms(self):
        self.raiseArmRaiseEvent()
    def pointAtMusician(self):
        self.raisePointsAtMeEvent()


# class that reacts to events
class Musician(object):
    def __init__(self, name):
        self.name = name
    def receiveEvent(self, msg):
        if msg == "Arms Raised":
            print self.name + " hold up instrument"

        if msg == "Points at me":
            print self.name + " play instrument"

# players

o = Orchestrator()
m = Musician("trumpet")
m2 = Musician("clarinet")

# Subscribe to the Orchestrator events:
# We're really just assigning instance methods
# of our Musician objects to the Orchestra object.

o.subscribeToArmRaiseEvent(m.receiveEvent)
o.subscribeToPointsAtMeEvent(m.receiveEvent)
o.subscribeToArmRaiseEvent(m2.receiveEvent)
o.subscribeToPointsAtMeEvent(m2.receiveEvent)

# Concert begins
o.raiseArms()
# ... other actions and events
# represented by:
print "do bee doo be dooo be do do do"

time.sleep(4)
# finally gets to your part of the song
o.pointAtMusician()

# my output:
#   trumpet hold up instrument
#   clarinet hold up instrument

#   do bee doo be dooo be do do do
#   trumpet play instrument
#   clarinet play instrument


Wednesday, March 31, 2010

Python - insult generator

# negative reinforcement through insults

#
#
# Sometimes negative reinforcement is the way to go.
# For the times when you need a kick in the pants
# rather than a pat on the back I whipped up this

# insult generator.
# It will churn out more insults then you can shake
# a stick at.

import random

class insultGenerator(object):
    def __init__(self):
        # setup the lists of insult fodder

        self.nounList = ['loser',
                         'jerk',
                         'nerd',
                         'doodie head',
                         'butthead',
                         'bonehead',
                         'dunce',
                         'moron',
                         'nerf herder']
        self.adjectiveList = ['smelly',
                              'ugly',
                              'gimpy',
                              'slimy',
                              'crabby',
                              'scabby',
                              'scratchy']
        self.connectorList = ['are one',
                              'are the biggest',
                              'are becoming a']
    def getInsult(self):
        insult = "you"

        # connector phrase
        connector = random.randint(1, len(self.connectorList))
        insult += " " + self.connectorList[connector-1]

        # adjectives
        adjCount = random.randint(2,4)
        random.shuffle(self.adjectiveList)
        for i in xrange(0,adjCount):
            if i != 0:
                insult += ", "

            else:
                insult += " "
            insult += self.adjectiveList[i]

        # ending noun
        noun = random.randint(1,len(self.nounList))
        insult += " " + self.nounList[noun-1]
        return insult


# a little example to get some insults flowing
if __name__ == '__main__':
    ig = insultGenerator()
    print ig.getInsult()
    print ig.getInsult()
    print ig.getInsult()
    print ig.getInsult()



# my output:
#   you are one ugly, slimy, scabby loser
#   you are the biggest scabby, slimy nerd
#   you are becoming a scabby, ugly, gimpy butthead

#   you are one slimy, smelly, crabby bonehead



Saturday, March 27, 2010

Python - unit tests with the unittest module

# python has a built in unit test module "unittest"
#

# Using python's unittest module is similar to NUnit
# or JUnit (if you are familiar with those).
#


import unittest


# my example function
# Normally you would have the class in its own
# file and then just import ExampleFunction into

# the unit test file.
class ExampleFunction(object):
    def __init__(self):
        self.example = 0
        self.example2 = 1
        self.example3 = 2
    def processVariable(self, item):
        item *= self.example2 * self.example3
        return item
    def setExampleVariables(self, example):
        self.example = example
        self.example2 = self.example + 1
        self.example3 = self.example2 + 1


# The test class inherits from unittest's TestCase.
# Inheriting ensures that the tests will run when you
# call unittest.Main()
class TestExampleFunction(unittest.TestCase):
    def setUp(self):
        self.ef = ExampleFunction()
    def test_defaults(self):
        # There are a lot types of asserts available

        # I only demo the assertEqual here.
        self.assertEqual(self.ef.example, 0, "example is not set to 0")
        self.assertEqual(self.ef.example2, 1, "example2 is not set to 1")
        self.assertEqual(self.ef.example3, 2, "example3 is not set to 2")
    def test_processVariable(self):
        self.assertEqual(self.ef.processVariable(1), 2, "example error message")
    def test_setExampleVariables(self):
        self.ef.setExampleVariables(5)
        self.assertEqual(self.ef.example, 5, "example is not set to 0")
        self.assertEqual(self.ef.example2, 6, "example2 is not set to 1")
        self.assertEqual(self.ef.example3, 7, "example3 is not set to 2")


if __name__ == '__main__':
    unittest.main()


# My Output:
#    ...
#    -------------------------------------
#    Ran 3 tests in 0.000s
#
#    OK


Tuesday, March 23, 2010

Python - calling super class methods from derived classes

# An inheritance, abstract classes, and
# calling super class methods from derived

# classes example

class AbstractBot(object):
    def __init__(self):
        self.size = 0
        self.speed = 1
        self.pos = [0,0]
    def applyPos(self, xy):
        self.pos[0] += xy[0] * self.speed
        self.pos[1] += xy[1] * self.speed
    def getCurrentPos(self):
        return self.pos


class WalkingBot(AbstractBot):
    def applyPos(self, xy):
        super(WalkingBot, self).applyPos(xy)
        print "step, step"

class DrivingBot(AbstractBot):
    def applyPos(self, xy):
        super(DrivingBot, self).applyPos(xy)
        print "vroom, vroom"

class RunningBot(AbstractBot):
    def __init__(self):
        super(RunningBot, self).__init__()
        self.speed = 5
    def applyPos(self, xy):
        super(RunningBot, self).applyPos(xy)
        print "trot, trot"

bot1 = WalkingBot()
bot2 = DrivingBot()
bot3 = RunningBot()
bots = [bot1, bot2, bot3]

distance = (1,1)

for step in xrange(3):
    for bot in bots:
        bot.applyPos(distance)
        print 'position: ' + str(bot.getCurrentPos())
        


Thursday, February 25, 2010

Python - a simple polymorphism example

# A quick example of polymorphism at work in python 
 
class Food(object):
    def __init__(self, name, calories):
        self.name = name
        self.calories = calories
    def tastesLike(self):
        raise NotImplementedException("Subclasses are responsible for creating this method")
 
class HotDog(Food):
    def tastesLike(self):
        return "Extremely processed meat" 
 
class Hamburger(Food):
    def tastesLike(self):
        return "grilled goodness" 
 
class ChickenPatty(Food):
    def tastesLike(self):
        return "tastes like chicken" 
 
dinner = []
dinner.append(HotDog('Beef/Turkey BallPark', 230))
dinner.append(Hamburger('Lowfat Beef Patty', 260))
dinner.append(ChickenPatty('Micky Mouse shaped Chicken Tenders', 170))
 
# even though each course of the dinner is a differnet type 
# we can process them all in the same loop 
for course in dinner:
    print course.name + " is type " + str(type(course))
    print "  has " + str(course.calories) + " calories " 
    print "  and tastes like " + course.tastesLike()
 
 
# my output: 
# 
#Beef/Turkey BallPark is type <class '__main__.HotDog'> 
#  has 230 calories 
#  and tastes like Extremely processed meat 
#Lowfat Beef Patty is type <class '__main__.Hamburger'> 
#  has 260 calories 
#  and tastes like grilled goodness 
#Micky Mouse shaped Chicken Tenders is type <class '__main__.ChickenPatty'> 
#  has 170 calories 
#  and tastes like tastes like chicken 
 
 

Sunday, October 4, 2009

Python - make your own class attributes iterable

# It can be useful to iterate through data contained 
# in your own custom objects. 
 
# Lets say you have your own class 
class ExampleClass(object):
    def __init__(self):
        self.objectList = []
        self.objectDict = {}
        self.maxItem = 100
        self.objectItem = "" 
    def iterateList(self):
        return self.objectList
    def addListItem(self, item):
        self.objectList.append(item)
    def addDictItem(self, item, value):
        self.objectDict[item] = value
 
 
# create an instance of the class 
# and lets use it's iterating methods 
ec = ExampleClass()
 
# add some example data 
for i in xrange(10):
    ec.addListItem(i)
    ec.addDictItem(i, str(i)+"'s value")
 
# now that we have data lets iterate 
# through the data 
for item in ec.iterateList():
    print item
 
#output: 
#    0 
#    1 
#    2 
#    3 
#    4 
#    5 
#    6 
#    7 
#    8 
#    9 
 
 
 

Tuesday, September 22, 2009

Python - find the average rgb color for an image

#   iterate through each pixel in an image and
# determine the average rgb color

# you will need to install the PIL module

from PIL import Image

class PixelCounter(object):
''' loop through each pixel and average rgb '''
def __init__(self, imageName):
self.pic = Image.open(imageName)
# load image data
self.imgData = self.pic.load()
def averagePixels(self):
r, g, b = 0, 0, 0
count = 0
for x in xrange(self.pic.size[0]):
for y in xrange(self.pic.size[1]):
tempr,tempg,tempb = self.imgData[x,y]
r += tempr
g += tempg
b += tempb
count += 1
# calculate averages
return (r/count), (g/count), (b/count), count

if __name__ == '__main__':
# assumes you have a test.jpg in the working directory!
pc = PixelCounter('test.jpg')
print "(red, green, blue, total_pixel_count)"
print pc.averagePixels()


# for my picture the ouput rgb values are:
# (red, green, blue, total_pixel_count)
# (135, 122, 107, 10077696)
#
# you can see that my image had 10,077,696 pixels and python/PIL
# still churned right through it!

Tuesday, September 15, 2009

Python - multiple inheritance

<pre>
<span class="comment"># multiple inheritance with python....its easy!span>
<span class="comment"># in addition to multiple inheritance you shouldspan>
<span class="comment">#   check out the creating static methods for a classspan>

<span class="ANY_KEYWORD">classspan> Arm(object):
    <span class="ANY_KEYWORD">defspan> flipBird(self):
        <span class="ANY_KEYWORD">printspan> <span class="STRING_LITERAL">&quot;span><span class="STRING_LITERAL">extend middle fingerspan><span class="STRING_LITERAL">&quot;span>


<span class="ANY_KEYWORD">classspan> Weapon(object):
    <span class="ANY_KEYWORD">defspan> fireWeapon(self):
        <span class="ANY_KEYWORD">printspan> <span class="STRING_LITERAL">&quot;span><span class="STRING_LITERAL">rat tat tatspan><span class="STRING_LITERAL">&quot;span>
<span class="comment"># with your span><span class="comment">powers combined I am Hero Arm (part arm part weapon!)span>
<span class="ANY_KEYWORD">classspan> HeroArm(Arm, Weapon):
    <span class="ANY_KEYWORD">passspan>


a = HeroArm()

a.fireWeapon()

<span class="comment">#output:span>
<span class="comment"># rat tat tatspan>

a.flipBird()
<span class="comment">#outputspan>
<span class="comment"># extend middle fingerspan>

pre>