''' building.py Feb 11, 2011 Written by Jeff Ondich and friends to illustrate classes. ''' import random import time from graphics import * class Building: def __init__(self, left, width, height, color): # Buildings consist of what? First, a silhouette rectangle. upperLeft = Point(left, 400 - height) bottomRight = Point(left + width, 400) self.silhouette = Rectangle(upperLeft, bottomRight) self.silhouette.setFill(color) # Second, a list of window rectangles. All my # windows are 40 pixels wide and 60 pixels high. self.windowList = [] windowsPerRow = width / (40 + 5) gapSize = (width - windowsPerRow * 40) / (windowsPerRow + 1) windowTop = 10 + (400 - height) # top of the top row of windows windowLeft = left + gapSize black = color_rgb(0, 0, 0) for k in range(windowsPerRow): upperLeft = Point(windowLeft, windowTop) bottomRight = Point(windowLeft + 40, windowTop + 60) newWindow = Rectangle(upperLeft, bottomRight) newWindow.setFill(black) self.windowList.append(newWindow) windowLeft = windowLeft + 40 + gapSize def draw(self, window): self.silhouette.draw(window) for w in self.windowList: w.draw(window) def turnOnRandomLight(self): windowToLightUp = random.choice(self.windowList) # Note that because of how choice works, windowToLightUp # is one of the items in self.windowList, and thus # a Rectangle object. yellow = color_rgb(255, 255, 0) windowToLightUp.setFill(yellow) if __name__ == '__main__': # Initialize city window windowHeight = 500 windowWidth = 700 windowTitle = 'City' backgroundColor = color_rgb(255, 255, 255) window = GraphWin(windowTitle, windowWidth, windowHeight) window.setBackground(backgroundColor) # Create the buildings buildings = [] for k in range(20): newBuildingColor = color_rgb(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) newBuildingLeft = random.randint(-10, windowWidth - 40) newBuildingHeight = random.randint(100, 350) newBuildingWidth = random.randint(50, 150) newBuilding = Building(newBuildingLeft, newBuildingWidth, newBuildingHeight, newBuildingColor) buildings.append(newBuilding) # Draw the buildings for building in buildings: building.draw(window) # Something with lights for k in range(8): time.sleep(0.5) b = random.choice(buildings) b.turnOnRandomLight() s = raw_input('Hit Enter to quit')