'''lecture_16_objects_in_lists_zelle.py Show slices of lists of objects not independent Oliver W. Layton CS 151: Computational Thinking: Visual Media Spring 2021 ''' import graphics as gr def setColor(shapeList, colorList): '''Sets the color of corresponding shapes in `shapeList`. `shapeList` is the list of shapes `colorList` is the list of shapes Both have the same length ''' for i in range(len(shapeList)): shapeList[i].setFill(colorList[i]) def draw(shapeList, window): '''Draw each shape in `shapeList` on the canvas `window`''' for shape in shapeList: shape.draw(window) # Create the screen screen = gr.GraphWin('Shallow copy with lists', width=500, height=500) # Create 3 Rectangles, add them to a list `shapes1` # Coordinates of their corners: # (25, 25) (75, 75) # (125, 25) (175, 75) # (225, 25) (275, 75) rec1 = gr.Rectangle(gr.Point(25, 25), gr.Point(75, 75)) rec2 = gr.Rectangle(gr.Point(125, 25), gr.Point(175, 75)) rec3 = gr.Rectangle(gr.Point(225, 25), gr.Point(275, 75)) shapes1 = [rec1, rec2, rec3] draw(shapes1, screen) # Set the color of each rectangle to a unique color colorsList = ['red', 'green', 'blue'] setColor(shapes1, colorsList) # Draw the shapes1 on the canvas/window # Keep the window open until we click screen.getMouse() # Slice the object rectangle object list, taking the 1st two shapes2 = shapes1[:2] # rec1 and rec2 # FIX # shapes3 = [] # for shape in shapes1: # shape3.append(shape.clone()) # Now shapes 3 would be a list of INDEPENDENT COPIES of shapes in shapeList1 # Draw the shapes in `shapes2` # draw(shapes2, screen) # Set the colors of the 2 Rectangles in `shapes2` to unique colors setColor(shapes2, ['pink', 'orange']) # Keep the window open until we click screen.getMouse() # Close the window after the click screen.close()