''' car.py Written by Jeff Ondich and friends in class on 10 Feb 2010. Objects of type Car represent graphical cars to be used in a simple 2D graphical animation using John Zelle's graphics library. ''' import time import random from graphics import * class Car: def __init__(self, x, y, width, height, color, velocity): # Initialize the instance variables. self.x = x self.y = y self.width = width self.height = height self.color = color self.velocity = velocity self.body = None self.leftTire = None self.rightTire = None self.windshield = None # Now set up the body, tires, and windshield self.setUpCarParts() def setUpCarParts(self): # The body of the car. topLeft = Point(self.x, self.y) bottomRight = Point(self.x + self.width, self.y + (4 * self.height / 5)) self.body = Rectangle(topLeft, bottomRight) self.body.setFill(self.color) # The tires. tireRadius = self.width / 7 center = Point(self.x + 2 * tireRadius, self.y + self.height - tireRadius) self.leftTire = Circle(center, tireRadius) self.leftTire.setFill(color_rgb(0, 0, 0)) center = Point(self.x + 5 * tireRadius, self.y + self.height - tireRadius) self.rightTire = Circle(center, tireRadius) self.rightTire.setFill(color_rgb(0, 0, 0)) # The windshield. windshieldWidth = self.width / 6 windshieldHeight = self.height / 3 if self.velocity < 0: left = self.x + 5 else: left = self.x + self.width - 5 - windshieldWidth topLeft = Point(left, self.y + 5) bottomRight = Point(left + windshieldWidth, self.y + 5 + windshieldHeight) self.windshield = Rectangle(topLeft, bottomRight) self.windshield.setFill(color_rgb(0, 0, 0)) def draw(self, window): self.body.draw(window) self.leftTire.draw(window) self.rightTire.draw(window) self.windshield.draw(window) def undraw(self): self.body.undraw() self.leftTire.undraw() self.rightTire.undraw() self.windshield.undraw() def move(self, dx, dy): self.x += dx self.y += dy self.body.move(dx, dy) self.leftTire.move(dx, dy) self.rightTire.move(dx, dy) self.windshield.move(dx, dy) def step(self): self.move(self.velocity, 0) def reverseDirection(self): self.velocity = -self.velocity self.setUpCarParts()