# BabyDragon Example # Simulate actions of a baby dragon. # Modified from IT 211 Ruby text by Chris Pine. import sys class BabyDragon: # Initialize runs when constructor is invoked. def __init__(self, the_name): # A pet baby dragon must have a name. self.name = the_name # It is born awake. self._asleep = False # It is born with food in its stomach self._stuff_in_stomach = 10 # Initially, doesn't have to go self._stuff_in_intestine = 0 def eat(self): print(f"{self.name} eats food.") self._stuff_in_stomach = 10 self._passage_of_time( ) def go_for_walk(self): print(f"{self.name} goes for walk.") self._stuff_in_intestine = 0 self.passage_of_time( ) def get_put_to_bed(self): print(f"{self.name} goes to bed.") self._asleep = True for i in range(1, 4): if self._asleep: self._passage_of_time( ) if self._asleep: print(f"{self.name} snores, " + \ "filling room with smoke.") if self._asleep: print(f"{self.name} wakes up slowly.") def get_tossed(self): print(f"{self.name} gets tossed into the air.") print(f"{self.name} giggles, which singes your eyebrows.") self._passage_of_time( ) def get_rocked(self): print(f"{self.name} gets rocked gently.") self._asleep = True print(f"{self.name} briefly dozes off ...") self._passage_of_time( ) self._asleep = False print(f"... but wakes up when you stop.") # Private methods cannot be called by you # They can only be called by the baby dragon itself. def _is_hungry(self): self._stuff_in_stomach <= 2 def _must_go(self): self._stuff_in_intestine >= 8 def _wake_up_suddenly(self): self._asleep = False print(f"{self.name} wakes up suddenly!") def _passage_of_time(self): if self._stuff_in_stomach > 0: # Move food from stomach to intestine. self._stuff_in_stomach -= 1 self._stuff_in_intestine += 1 else: # Dragon is starving! if self._asleep: self._wake_up_suddenly( ) print(f"{self.name} is starving! " + \ "In desperation, he eats YOU!!") sys.exit( ) if self._stuff_in_intestine >= 10: print("Whoops, had an accident.") self._stuff_in_intestine = 0 if self._is_hungry( ) and self._asleep: self.wake_up_suddenly( ) print(f"{self.name}'s stomach grumbles.") if self._must_go( ): if self._asleep: wake_up_suddenly( ) print(f"{self.name} walks in circles and looks at you.")