# Q-12 MCS 275 Thu 8 Apr 2010 : quiz12b.py # Soap bubbles start at a certain location (x,y,z), # at a give radius r. Each second the location shifts a little # at random and also the radius r varies randomly. # The bubble pops when it hits the ground (i.e.: z <= 0) # or after t seconds. # Inheriting from Thread, write a class Bubble # to simulate the life cycle of a soap bubble as described above. # After sleeping 1 second, each bubble prints all its data attributes. from threading import * from time import sleep from random import randint class Bubble(Thread): """ simulating soap bubbles """ def __init__(self,n,x,y,z,r,t): """ Initializes a bubble with name n, coordinates (x,y,z), radius r, and time t. """ Thread.__init__(self,name=n) print 'bubble ' + n + ' is born' self.position = (x,y,z) self.radius = r self.lifespan = t def run(self): """ Every step the bubble sleeps a second and prints its status. """ n = self.getName() while self.lifespan > 0 and self.position[2] > 0: s = n + ' at ' + str(self.position) \ + ' with radius ' + str(self.radius) \ + ' and lifespan ' + str(self.lifespan) print s sleep(1) (x,y,z) = self.position nx = x + randint(-1,+1) ny = y + randint(-1,+1) nz = z + randint(-1,+1) self.position = (nx,ny,nz) self.radius += randint(-1,+1) self.lifespan = self.lifespan - 1 def main(): """ Launches some bubbles. """ a = Bubble('A',10,5,10,3,5) b = Bubble('B',5,10,15,4,4) a.start() b.start() if __name__ == "__main__": main()