Example: BankAccount.py
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
b=BankAccount()
b.get_balance()
b.deposit(100.0)
b.get_balance()
#********************************************
#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!')
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.
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.
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.
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.
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
.
main()