This is a sightly revised version of Michael Dawson's critter_caretaker.py from chapter 8 of Michael Dawson, "Python: Programming for the Absolute Beginner," Third Edition, Course Technology PTR, 2010, Cengage Learning, Boston, ISBN 978-1-4354-5500-9, to avoid problems when run under Python 2.
1 # Critter Caretaker 2 # A virtual pet to care for 3 4 class Critter(object): 5 """A virtual pet""" 6 def __init__(self, name, hunger = 0, boredom = 0): 7 self.name = name 8 self.hunger = hunger 9 self.boredom = boredom 10 11 def __pass_time(self): 12 self.hunger += 1 13 self.boredom += 1 14 15 @property 16 def mood(self): 17 unhappiness = self.hunger + self.boredom 18 if unhappiness < 5: 19 m = "happy" 20 elif 5 <= unhappiness <= 10: 21 m = "okay" 22 elif 11 <= unhappiness <= 15: 23 m = "frustrated" 24 else: 25 m = "mad" 26 return m 27 28 def talk(self): 29 print "I'm", self.name, "and I feel", self.mood, "now.\n" 30 self.__pass_time() 31 32 def eat(self, food = 4): 33 print "Brruppp. Thank you." 34 self.hunger -= food 35 if self.hunger < 0: 36 self.hunger = 0 37 self.__pass_time() 38 39 def play(self, fun = 4): 40 print "Wheee!" 41 self.boredom -= fun 42 if self.boredom < 0: 43 self.boredom = 0 44 self.__pass_time() 45 46 47 def main(): 48 crit_name = raw_input("What do you want to name your critter?: ") 49 crit = Critter(crit_name) 50 51 choice = None 52 while choice != "0": 53 print \ 54 """ 55 Critter Caretaker 56 57 0 - Quit 58 1 - Listen to your critter 59 2 - Feed your critter 60 3 - Play with your critter 61 """ 62 63 choice = raw_input("Choice: ") 64 print 65 66 # exit 67 if choice == "0": 68 print "Good-bye." 69 70 # listen to your critter 71 elif choice == "1": 72 crit.talk() 73 74 # feed your critter 75 elif choice == "2": 76 crit.eat() 77 78 # play with your critter 79 elif choice == "3": 80 crit.play() 81 82 # some unknown choice 83 else: 84 print "\nSorry, but", choice, "isn't a valid choice." 85 86 main() 87 raw_input ("\n\nPress the enter key to exit.") 88