Python Programming: An Introduction to Computer Science

(Nora) #1
174 CHAPTER10. DEFININGCLASSES

mouthOff= size / 2.0
self.head= Circle(center, size)
self.head.draw(window)
self.leftEye= Circle(center, eyeSize)
self.leftEye.move(-eyeOff, -eyeOff)
self.rightEye= Circle(center, eyeSize)
self.rightEye.move(eyeOff, -eyeOff)
self.leftEye.draw(window)
self.rightEye.draw(window)
p1 = center.clone()
p1.move(-mouthSize/2,mouthOff)
p2 = center.clone()
p2.move(mouthSize/2,mouthOff)
self.mouth= Line(p1,p2)
self.mouth.draw(window)

(a)Usethisclasstowritea programthatdrawsthreefacesina window.
(b)Addandtestamovemethodsothatfacescanbemovedlike othergraphicsobjects.
(c)Addandtestaflinchmethodthatcausesa face’s eyesto close.Alsoaddandtestanunflinch
toopenthembackupagain.
(d)Writea completeprogramthatdrawsa singlefaceina window andthenanimatesit “bouncing
around.” Startthefaceata randomlocationinthewindow andusea loopthatmovesit a small
incrementinthexandydirections.Whenthefacehitstheedgeofthewindow, it shouldflinch
andbounceoff. Youcandothebouncebysimplyreversingthesignofthexincrementorthey
incrementdependingonwhetherthefacehita side-ortop-/bottom-edgerespectively. Writethe
animationprogramtorunfora certain(fixed)numberofsteps.
Note:Youwillneedtoflushthegraphicswindow at thebottomoftheloopto achieve theeffect
ofanimation.


  1. CreateaTrackerclassthatdisplaysa circleina graphicswindow toshow thecurrentlocationofan
    object.Hereis a quickspecificationoftheclass:


class Tracker:

def __init__(self,window, objToTrack):
# windowis a graphWin and objToTrack is an object whose
# positionis to be shown in the window. objToTrackmust be
# an objectthat has getX() and getY() methods thatreport its
# currentposition.
# Createsa Tracker object and draws a circle in windowat the
# currentposition of objToTrack.

def update():
# Moves the circlein the window to the current positionof the
# objectbeing tracked.

UseyournewTrackerclassinconjunctionwiththeProjectileclasstowritea programthat
graphicallydepictstheflightofa cannonball.


  1. AddaTargetclasstothecannonballprogramfromthepreviousproblem. Atargetshouldbea
    rectangleplacedata randompositioninthewindow. Allowtheusertokeepfiringuntilthey hitthe
    target.

Free download pdf