'''A class for representing a simple graphical target. Jeff Ondich, 1/24/07 This Target class is smarter than the original one in target.py. It retains a memory of the circles used to draw the target so it can implement the undraw() and move() methods. This class depends on the "graphics.py" library written by John Zelle for his textbook "Python Programming: An Introduction to Computer Science." ''' from graphics import * class Target: def __init__(self, center, radius, nRings): ''' Initializes the Target object's center (a Point), radius (an integer), and number of rings (an integer). Sets the ring colors to default values of red and white. ''' self.center = center self.radius = radius self.numberOfRings = nRings self.outerColor = color_rgb(200, 0, 0) self.innerColor = color_rgb(255, 255, 255) self.circles = [] self.window = None self.rebuildCircles() def rebuildCircles(self): self.circles = [] ringSeparation = self.radius / self.numberOfRings currentRadius = self.radius currentColor = self.outerColor for k in range(self.numberOfRings): circle = Circle(self.center, currentRadius) circle.setFill(currentColor) self.circles.append(circle) currentRadius = currentRadius - ringSeparation if currentColor == self.outerColor: currentColor = self.innerColor else: currentColor = self.outerColor def setCenter(self, center): self.center = center self.rebuildCircles() def getCenter(self): return self.center def setRadius(self, radius): self.radius = radius self.rebuildCircles() def getRadius(self): return self.radius def setNumberOfRings(self, nRings): self.numberOfRings = nRings self.rebuildCircles() def getNumberOfRings(self): return self.numberOfRings def setOuterColor(self, color): self.outerColor = color self.rebuildCircles() def getOuterColor(self): return self.outerColor def setInnerColor(self, color): self.innerColor = color self.rebuildCircles() def getInnerColor(self): return self.innerColor def draw(self, window): self.window = window for circle in self.circles: circle.draw(window) def undraw(self): for circle in self.circles: circle.undraw() def move(self, dx, dy): for circle in self.circles: circle.move(dx, dy) self.center = self.circles[0].getCenter() if __name__ == '__main__': window = GraphWin('Target demo', 800, 400) window.setBackground(color_rgb(255, 255, 255)) target = Target(Point(150, 200), 100, 5) target.draw(window) import time movingRight = True while True: center = target.getCenter() if center.getX() >= window.getWidth() - target.getRadius(): movingRight = False elif center.getX() <= target.getRadius(): movingRight = True if movingRight: dx = 2 else: dx = -2 target.move(dx, 0) time.sleep(0.01)