CSC111 Building A Car 2014

From dftwiki3
Jump to: navigation, search

--D. Thiebaut (talk) 22:13, 6 April 2014 (EDT)


Graphics Program For Building a Car with Objects


This page shows how to build a simple car made with a rectangle and two sets of concentric circles for wheels using Horstmann's graphics library.

Simple2WheelCar.png


from graphics2 import GraphicsWindow
import time

MAXWIDTH = 400
MAXHEIGHT = 400

class Wheel:
    def __init__( self, x, y, radius1, radius2 ):
        self._x = x
        self._y = y
        self._radius1 = min( radius1, radius2 )
        self._radius2 = max( radius1, radius2 )

    def setX( self, x ):
        self._x = x

    def setY( self, y ):
        self._y = y

    def undraw( self, canvas ):
        canvas.setColor( "white" )
        canvas.drawOval( self._x-self._radius2,
                         self._y-self._radius2,
                         2*self._radius2, 2*self._radius2 )

    def draw( self, canvas ):
        canvas.setFill( "black" )
        canvas.drawOval( self._x-self._radius2,
                         self._y-self._radius2,
                         2*self._radius2, 2*self._radius2 )
        canvas.setFill( "grey" )
        canvas.drawOval( self._x-self._radius1,
                         self._y-self._radius1,
                         2*self._radius1, 2*self._radius1 )
        

class Body:
    def __init__(self, topX, topY, bottomX, bottomY, color ):
        self._topX = min( topX, bottomX )
        self._topY = min( topY, bottomY )
        self._bottomX = max( bottomX, topX )
        self._bottomY = max( bottomY, topY )
        self._width  = self._bottomX - self._topX
        self._height = self._bottomY - self._topY
        self._color  = color
        self._wheel1 = Wheel( self._topX + (self._bottomX-self._topX )//4,
                              self._bottomY, 20, 40 )
        self._wheel2 = Wheel( self._topX + 3*(self._bottomX-self._topX )//4,
                              self._bottomY, 20, 40 )
        
    def draw( self, canvas ):
        canvas.setFill( self._color )
        canvas.drawRect( self._topX, self._topY, self._width, self._height )
        self._wheel1.draw( canvas )
        self._wheel2.draw( canvas )
        
def main():
    win = GraphicsWindow(MAXWIDTH, MAXHEIGHT)
    canvas = win.canvas()

    """
    wheel1 = Wheel( 50, 250, 20, 40 )
    wheel1.draw( canvas )
    
    wheel1 = Wheel( 150, 250, 20, 40 )
    wheel1.draw( canvas )

    
    for x in range( 0, MAXWIDTH, 5 ):
        wheel1.undraw( canvas )
        wheel1.setX( x )
        wheel1.draw( canvas )
        time.sleep( 0.08 )
    """
    car = Body( 50, 50, 250, 100, "yellow" )
    car.draw( canvas )
    win.wait()

main()