from cs1graphics import * from bullseye import * from math import * from time import * class DartsHandler(EventHandler): def __init__(self,paper): self._paper=paper EventHandler.__init__(self) def handle(self,event): if event.getDescription() == 'mouse click': # if mouse is clicked p=event.getMouseLocation() throwDart(self._paper,p) else: pass class ExitButtonHandler(EventHandler): def __init__(self,textObj): self._text=textObj EventHandler.__init__(self) def handle(self,event): # if mouse is clicked if event.getDescription() == 'mouse click': self._text.setMessage('Good Buy!') sleep(3) print 'Exit program' exit(0) # forced termination of the program else: pass class Dart(Drawable): def __init__(self,tipCol='yellow',shaftCol='dark green',flightCol='yellow'): Drawable.__init__(self) self._arrow=Polygon(Point(10,0),Point(15,10),Point(5,10)) self._arrow.setFillColor(tipCol) self._shaft=Rectangle(2,20,Point(10,20)) self._shaft.setFillColor(shaftCol) self._flight=Polygon(Point(3,37),Point(10,30),Point(17,37),Point(17,44),Point(12,48),Point(8,48),Point(3,44)) self._flight.setFillColor(flightCol) self._flightLine=Path(Point(10,30),Point(10,48)) #adjusting reference points to be the tip of the arrow self._shaft.adjustReference(0,-20) self._flight.adjustReference(7,-37) self._flightLine.adjustReference(0,-30) def _draw(self): self._beginDraw() self._arrow._draw() self._shaft._draw() self._flight._draw() self._flightLine._draw() self._completeDraw() def throwDart(paper,point): # drawing a dart d=Dart() # rotating d.rotate(30) # moving to the left bottom corner of the graphics window d.moveTo(0,paper.getHeight()-20) # adding dart to the graphics window paper.add(d) # animation for i in range(100): stepX=(point.getX()-d.getReferencePoint().getX())/float(100-i) print 'target pointX:%d, pointX of dart:%d'%(point.getX(),d.getReferencePoint().getX()) print 'stepX=%f'%stepX stepY=(point.getY()-d.getReferencePoint().getY())/float(100-i) print 'target pointY:%d, pointY of dart:%d'%(point.getY(),d.getReferencePoint().getY()) print 'stepY=%f'%stepY if i%5 ==0: d.rotate(1) d.move(stepX,stepY) def main(): paper=Canvas(700,600,'light yellow','Dart Board') w,h=700,600 # drawing Dart Board b=Bullseye(5,60,'black','red') b.move(w/2,h/2) paper.add(b) # adding comment for user text=Text('Click anywhere in the graphics window to send a dart',12,Point(w/2,h-40)) paper.add(text) # drawing Exit button exitButton=Rectangle(60,20,Point(w-40,h-20)) exitButton.setFillColor('light green') exitText=Text('Exit',12,Point(w-40,h-20)) paper.add(exitButton) paper.add(exitText) #throwing darts darts=DartsHandler(paper) # creating darts handler exitB=ExitButtonHandler(text) # creating exit button handler exitT=ExitButtonHandler(text) # creating exit button handler exitButton.addHandler(exitB) # activating exit button handler exitText.addHandler(exitT) # activating exit button handler paper.addHandler(darts) # activating darts handler main()