Showing posts with label class. Show all posts
Showing posts with label class. 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 
 
 

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



Monday, March 8, 2010

Python - creating an interface with python

# python doesn't formally support an interface.
# You can work around this and support the spirit

# of an interface by creating abstract classes that
# have empty methods that just raise exceptions if
# haven't been implemented.

class Vehicle:
    def __init__(self, model):
        self.model = model
    def returnModel(self):
        raise NotImplementedError("Subclass must implement")
    def calculateTaxes(self):
        raise NotImplementedError("Subclass must implement")


class Toyota(Vehicle):
    pass


t = Toyota("Carolla")
t.returnModel()

#output:
# NotImplementedError: Subclass must implement

# You are required to implement the defined methods ( just

# like when using an interface

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 
 
 
 

Saturday, October 3, 2009

Python - create unit tests and ensure accurate documentation with doctest

""" 
The doctest module uses class and 
method documentation to run unit 
tests on your code. 
 
The doctest module reads the coding documentation 
you've created and uses that same documentation 
to conduct unit tests.  This helps ensure 
the documentation is accurate and creates a 
one stop destination for documentation and unit 
tests. 
""" 
 
class ExampleClass(object):
    """ 
    Example class that 
    has one working method. 
 
    >>> ec = ExampleClass()
    >>> ec.example(10)
    19 
 
    >>> ec = ExampleClass()
    >>> ec.example(0)
    -1 
 
    # non int parameters should 
    # return nothing 
    >>> ec = ExampleClass()
    >>> ec.example("apple")
 
    >>> ec = ExampleClass()
    >>> ec.a = 3
    >>> ec.example(10)
    30 
    """ 
 
    def __init__(self):
        self.a = 2
        self.b = -1
    def example(self, n):
        try:
            n = int(n)
        except ValueError:
            return None
        return n * self.a + self.b
 
 
if __name__ == '__main__':
    # more about  doctest features  
    import doctest
    doctest.testmod()
 
 
# this outputs: 
# nothing at all 
# if no errors are found then doctest doesn't complain 
 
# If you were to change some of the expected values in the 
# documention....for instance... the last example: 
#    >>> ec = ExampleClass() 
#    >>> ec.a = 3 
#    >>> ec.example(10) 
#    29 
# and change the expected response to 30 
# 
# 
# the output would be: 
#    ********************************************************************** 
#    File "C:\python\docstringexample.py", line 27, in __main__.ExampleClass 
#    Failed example: 
#        ec.example(10) 
#    Expected: 
#        30 
#    Got: 
#        29 
#    ********************************************************************** 
#    1 items had failures: 
#       1 of   9 in __main__.ExampleClass 
#    ***Test Failed*** 1 failures. 
 
 

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>

Python - create static methods in a class

#create static methods in a python class

import math

class MyStaticClass:
def getSqrt(num):
return math.sqrt(num)
def getHalf(num):
return num/2
# labels the methods as static
getSqrt = staticmethod(getSqrt)
getHalf = staticmethod(getHalf)

MyStaticClass.getSqrt(144)
12.0
MyStaticClass.getHalf(20)
10