CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Object-Oriented Programming (OOP), Part 1
Using Objects and Methods


  1. Updated Example: Adding and Deleting Shapes


  1. Updated Example: Adding and Deleting Shapes
    Here is an improved version of the adding-and-deleting-shapes example from here. Instead of representing dots as (cx, cy) pairs, here we will create a Dot class. Now, each instance will use dot.cx, dot.cy, dot.r, dot.counter, and dot.color.
    from cmu_graphics import * import random class Dot(object): def __init__(self, cx, cy, r, color): self.cx = cx self.cy = cy self.r = r self.color = color self.counter = 0 def contains(self, x, y): return (((self.cx - x)**2 + (self.cy - y)**2)**0.5 <= self.r) def onAppStart(app): app.dots = [ ] def getRandomColor(): colors = ['red', 'orange', 'yellow', 'green', 'blue', 'pink', 'lightGreen', 'gold', 'magenta', 'maroon', 'salmon', 'cyan', 'brown', 'orchid', 'purple'] return random.choice(colors) def onMousePress(app, mouseX, mouseY): # go through dots in reverse order so that # we find the topmost dot that intersects for dot in reversed(app.dots): if dot.contains(mouseX, mouseY): dot.counter += 1 dot.color = getRandomColor() return # mouse click was not in any dot, so create a new dot newDot = Dot(mouseX, mouseY, 20, 'cyan') app.dots.append(newDot) def onKeyPress(app, key): if (key == 'd'): if (len(app.dots) > 0): app.dots.pop(0) else: print('No more dots to delete!') def redrawAll(app): # draw the dots and their counters for dot in app.dots: drawCircle(dot.cx, dot.cy, dot.r, fill='white', border=dot.color, borderWidth=5) drawLabel(dot.counter, dot.cx, dot.cy) # draw the text drawLabel('Example: Adding and Deleting Shapes', app.width/2, 20) drawLabel('Mouse clicks outside dots create now dots', app.width/2, 40) drawLabel('Mouse clicks inside dots increase their counter', app.width/2, 60) drawLabel('and randomize their color.', app.width/2, 70) drawLabel('Pressing "d" deletes circles', app.width / 2, 90) runApp(width=400, height=400)