Difference between revisions of "CSC111 Moving Graphic Objects"
(→A car that moves out of the canvas) |
|||
Line 3: | Line 3: | ||
=A car that moves out of the canvas= | =A car that moves out of the canvas= | ||
− | [[Image:CarPolyGraphicsMovingRight.png| | + | [[Image:CarPolyGraphicsMovingRight.png|350px|right]] |
<br /> | <br /> | ||
The example program below requires the graphics library available on [[CSC111 Event-Driven Programming with Graphics111.py 2014| this page]]. | The example program below requires the graphics library available on [[CSC111 Event-Driven Programming with Graphics111.py 2014| this page]]. |
Revision as of 08:52, 20 April 2014
--D. Thiebaut (talk) 09:48, 20 April 2014 (EDT)
A car that moves out of the canvas
The example program below requires the graphics library available on this page.
# Demo program 1
# D. Thiebaut
# Demonstrates the user the graphics111 library with
# moveable objects, menu, and event-driven programming
# Activating a key of the menu result in the name of
# the button being printed on the console.
from graphics111 import *
from random import seed
from random import randrange
from time import sleep
MAXWIDTH = 800
MAXHEIGHT = 600
class Car:
def __init__( self, x, y, width, height, color ):
self._x = x
self._y = y
self._width = width
self._height = height
self._color = color # list of 3 ints between 0 and 255
# build the body
self._top = Rectangle( x+width//4, y-height//2,
width//2, height//2,
color )
self._body = Rectangle( x, y, width, height, color )
# build the wheels
self._w1 = Wheel( x + width//4, y + height, width//5 )
self._w2 = Wheel( x + 3*width//4, y + height, width//5 )
def setRandomColor( self ):
self._top.setRandomColor()
self._body.setRandomColor()
def getTotalHeight( self ):
return self._height*2 + self._width//10
def getTotalWidth( self ):
return self._width
def draw( self, canvas ):
self._canvas = canvas
self._body.draw( canvas )
self._top.draw( canvas )
self._w1.draw( canvas )
self._w2.draw( canvas )
def move( self, canvas, dx, dy ):
self._body.move( canvas, dx, dy )
self._top.move( canvas, dx, dy )
self._w1.move( canvas, dx, dy )
self._w2.move( canvas, dx, dy )
# ========================================================
# Main Program
# ========================================================
def main():
# make the menu and car global so that they will
# be accessible to the call-back function
global menu, car
# open the window and get access to its canvas
win = GraphicsWindow(MAXWIDTH, MAXHEIGHT)
canvas = win.canvas()
# draw something
p1 = Polygon( (100, 100, 150, 50, 350, 50, 400, 100), (255, 0, 0 ) )
p1.draw( canvas )
car = Car( 150, 75, 100, 20, (250, 250, 0 ) )
car.draw( canvas )
deltaX = 5
for i in range( MAXWIDTH//deltaX ):
car.move( canvas, deltaX, 0 )
# wait and respond to events, or comment out and make the program
# stop as soon as car disappears.
win.wait()
win.close()
main()