ENGI E1006: Introduction to Computing for Engineers and Applied Scientists


Lecture 11: Object-Oriented Programming in Python

Reading: Punch and Enbody Chapter 11

Example: BankAccount.py

In [1]:
class BankAccount:
    
     #this method must be named __init__ and is used to set up the object
    def __init__(self, name='', number=0):
        self.name=name
        self.number=number
        self.balance=0.0

    def get_balance(self):
        return self.balance

    def deposit(self,amt=0):
        self.balance+=amt

    def withdraw(self,amt=0):
        self.balance-=amt
In [2]:
b=BankAccount()
b.get_balance()
Out[2]:
0.0
In [3]:
b.deposit(100.0)
b.get_balance()
Out[3]:
100.0

Pig revisited

Recall the Pig example from lecure 3: pig.py

In [4]:
#********************************************
#Pig.py
# 
#Plays the interactive dice game Pig
#
#Written by Cannon
#********************************************

import random

score = 0

# The main function for the applicaiton
def main():
    greeting()
    playgame()
    goodbye()


def playgame():
    '''This function plays the game Pig'''
    p1score=0
    p2score=0
    #establish a while loop for the game
    while (p1score <100 and p2score <100):
        print ('your score total is now: {} \n \n'.format(p1score))
        p1score=p1score + playerMove()
        print ('your score total is now: {} \n \n'.format(p1score))
        if(p1score<100):
            p2score=p2score + computerMove()
            print ('the computer score total is now:{}\n \n'.format(p2score))
    if (p1score>p2score):
        print ('you win!')
    else:
        print ('you lose!')

def playerMove():
    '''manages the human players move in Pig. Returns their score'''
    roundScore=0
    again='y'
    #establish a while loop for the player's turn
    while again=='y':
        roll=rollDice()
        if roll==1:
            print ('you rolled a 1')
            roundScore=0
            again='n'
        else:
            print( 'you rolled a {}'.format(roll))
            roundScore=roundScore+roll
            print( 'your round score is {}'.format(roundScore))
            again=input('roll again? (y/n)')
    print ('your turn is over')
    return roundScore


def computerMove():
    '''plays the computer players turn in Pig returns their turn score'''
    roundScore=0
    again='y'
    #establish a while loop for the computer's turn
    while again=='y':
        roll=rollDice()
        if roll==1:
            print ('computer rolled a 1')
            roundScore=0
            again='n'
        else:
            print( 'computer rolled a {}'.format(roll))
            roundScore=roundScore+roll
            if roundScore < 20:
                print( 'computer will roll again')
            else:
                again='n'
                
    print( 'computer turn is over')
    print( 'computer round score is {}'.format(roundScore))
    return roundScore

def rollDice():
    '''Rolls a 6 sided die and returns an int 1-6'''
    face=int(random.random()*6+1)
    return face

def greeting():
    '''Displays a greeting for the game Pig'''
    print( 'welcome to Pig Death Match!')
    
def goodbye():
    '''Displays a goodbye message for the game Pig'''
    print()
    print()
    print('Toodles!')
    

Object-oriented pig

We can rewrite this example in an object oriented way. This time we will create a a series of classes. Once again we will have a simple main function. Once again we will use our desire for simplicity in main to inform our design decisions.

In [5]:
def main():
    greeting()
    game=Pig()
    game.play()
    goodbye()
    
def greeting():
    '''Displays a greeting for the game Pig'''
    print( 'welcome to Pig Death Match!')
    
def goodbye():
    '''Displays a goodbye message for the game Pig'''
    print()
    print()
    print('Toodles!')

This time instead of calling the playgame() function in the second line of main, we instantiate an object of type Pig. We then call the play method of the Pig class. Let's consider the Pig class for a moment. What should it look like? Instance variables? Methods? Consider the version below.

Example

Pig.py

In [6]:
class Pig:
    
    def __init__(self,p1_human=True,p2_human=False):
        self.die=Die()
        self.p1 = Player('Player 1',p1_human)
        self.p2 = Player('Player 2',p2_human)
        
    def play(self):
        while (self.p1.score<100 and self.p2.score<100):
            self.p1.move()
            if self.p1.score<100:
                self.p2.move()
        if (self.p1.score>self.p2.score):
            print ('Player 1 wins!')
        else:
            print ('Player 2 wins!')
                

What just happened? We created the Pig class and farmed out some of the work to classes that we still need to write. Namely, the Player class.

Player.py

In [7]:
class Player:
    
    def __init__(self,title,human_player=False):
        self.name=title
        self.is_human=human_player
        self.score=0
        self.die=Die(6)
        
    def move(self):
        if self.is_human:
            self.human_move()
        else:
            self.computer_move()
            
    def human_move(self):
        round_score=0
        again='y'
        #establish a while loop for the player's turn
        while again=='y':
            self.die.roll()
            roll=self.die.face
            if roll==1:
                print ('{} rolled a 1'.format(self.name))
                round_score=0
                again='n'
            else:
                print( '{} rolled a {}'.format(self.name,roll))
                round_score=round_score+roll
                print( "{}'s round score is {}".format(self.name,round_score))
                again=input('roll again? (y/n)')
        self.score+=round_score
        print ("{}'s turn is over".format(self.name))
        print( "{}'s total score is {}\n\n".format(self.name,self.score))
        
    def computer_move(self):
        round_score=0
        again='y'
        #establish a while loop for the computer's turn
        while again=='y':
            self.die.roll()
            roll=self.die.face
            if roll==1:
                print ('{} rolled a 1'.format(self.name))
                roundScore=0
                again='n'
            else:
                print( '{} rolled a {}'.format(self.name,roll))
                round_score=round_score+roll
                if round_score < 20:
                    print( '{} will roll again'.format(self.name))
                else:
                    again='n'     
        self.score+=round_score
        print( 'Turn is over')
        print( "{}'s round score is {}".format(self.name,round_score))
        print( "{}'s total score is {}\n\n".format(self.name,self.score))


        

Notice that the Player class requires a Die class to take care of the die rolling. This is a simple class we write here.

Die.py

In [8]:
class Die:
    
    def __init__(self,n=6):
        self.sides=n
        self.roll()
        
    def roll(self):
        self.face=int(random.random()*self.sides+1)
        

And now we can run the program by calling main.

In [9]:
main()
welcome to Pig Death Match!
Player 1 rolled a 4
Player 1's round score is 4
roll again? (y/n)n
Player 1's turn is over
Player 1's total score is 4


Player 2 rolled a 3
Player 2 will roll again
Player 2 rolled a 4
Player 2 will roll again
Player 2 rolled a 1
Turn is over
Player 2's round score is 7
Player 2's total score is 7


Player 1 rolled a 5
Player 1's round score is 5
roll again? (y/n)y
Player 1 rolled a 5
Player 1's round score is 10
roll again? (y/n)y
Player 1 rolled a 2
Player 1's round score is 12
roll again? (y/n)y
Player 1 rolled a 6
Player 1's round score is 18
roll again? (y/n)n
Player 1's turn is over
Player 1's total score is 22


Player 2 rolled a 4
Player 2 will roll again
Player 2 rolled a 1
Turn is over
Player 2's round score is 4
Player 2's total score is 11


Player 1 rolled a 2
Player 1's round score is 2
roll again? (y/n)y
Player 1 rolled a 1
Player 1's turn is over
Player 1's total score is 22


Player 2 rolled a 2
Player 2 will roll again
Player 2 rolled a 3
Player 2 will roll again
Player 2 rolled a 6
Player 2 will roll again
Player 2 rolled a 4
Player 2 will roll again
Player 2 rolled a 5
Turn is over
Player 2's round score is 20
Player 2's total score is 31


Player 1 rolled a 6
Player 1's round score is 6
roll again? (y/n)y
Player 1 rolled a 2
Player 1's round score is 8
roll again? (y/n)y
Player 1 rolled a 6
Player 1's round score is 14
roll again? (y/n)y
Player 1 rolled a 6
Player 1's round score is 20
roll again? (y/n)n
Player 1's turn is over
Player 1's total score is 42


Player 2 rolled a 1
Turn is over
Player 2's round score is 0
Player 2's total score is 31


Player 1 rolled a 6
Player 1's round score is 6
roll again? (y/n)y
Player 1 rolled a 1
Player 1's turn is over
Player 1's total score is 42


Player 2 rolled a 1
Turn is over
Player 2's round score is 0
Player 2's total score is 31


Player 1 rolled a 5
Player 1's round score is 5
roll again? (y/n)y
Player 1 rolled a 3
Player 1's round score is 8
roll again? (y/n)y
Player 1 rolled a 5
Player 1's round score is 13
roll again? (y/n)y
Player 1 rolled a 1
Player 1's turn is over
Player 1's total score is 42


Player 2 rolled a 1
Turn is over
Player 2's round score is 0
Player 2's total score is 31


Player 1 rolled a 4
Player 1's round score is 4
roll again? (y/n)y
Player 1 rolled a 1
Player 1's turn is over
Player 1's total score is 42


Player 2 rolled a 3
Player 2 will roll again
Player 2 rolled a 5
Player 2 will roll again
Player 2 rolled a 2
Player 2 will roll again
Player 2 rolled a 6
Player 2 will roll again
Player 2 rolled a 4
Turn is over
Player 2's round score is 20
Player 2's total score is 51


Player 1 rolled a 2
Player 1's round score is 2
roll again? (y/n)y
Player 1 rolled a 3
Player 1's round score is 5
roll again? (y/n)y
Player 1 rolled a 3
Player 1's round score is 8
roll again? (y/n)y
Player 1 rolled a 5
Player 1's round score is 13
roll again? (y/n)y
Player 1 rolled a 3
Player 1's round score is 16
roll again? (y/n)y
Player 1 rolled a 6
Player 1's round score is 22
roll again? (y/n)n
Player 1's turn is over
Player 1's total score is 64


Player 2 rolled a 4
Player 2 will roll again
Player 2 rolled a 3
Player 2 will roll again
Player 2 rolled a 2
Player 2 will roll again
Player 2 rolled a 6
Player 2 will roll again
Player 2 rolled a 2
Player 2 will roll again
Player 2 rolled a 2
Player 2 will roll again
Player 2 rolled a 3
Turn is over
Player 2's round score is 22
Player 2's total score is 73


Player 1 rolled a 6
Player 1's round score is 6
roll again? (y/n)y
Player 1 rolled a 3
Player 1's round score is 9
roll again? (y/n)y
Player 1 rolled a 2
Player 1's round score is 11
roll again? (y/n)y
Player 1 rolled a 6
Player 1's round score is 17
roll again? (y/n)y
Player 1 rolled a 4
Player 1's round score is 21
roll again? (y/n)y
Player 1 rolled a 4
Player 1's round score is 25
roll again? (y/n)n
Player 1's turn is over
Player 1's total score is 89


Player 2 rolled a 1
Turn is over
Player 2's round score is 0
Player 2's total score is 73


Player 1 rolled a 6
Player 1's round score is 6
roll again? (y/n)y
Player 1 rolled a 4
Player 1's round score is 10
roll again? (y/n)y
Player 1 rolled a 5
Player 1's round score is 15
roll again? (y/n)n
Player 1's turn is over
Player 1's total score is 104


Player 1 wins!


Toodles!