CSC111 Lab 11 Solution Program
--D. Thiebaut 22:45, 15 April 2010 (UTC)
# lab11.py
# Solution program for Lab 11
# D. Thiebaut
#
# This program creates a school of fish with a random number
# of fish (but at least 1).
# The fish have random horizontal speed and will move up and
# down at random as well.
# I created two kinds of fish using the "convert" utility.
#
# First I made a copy of fish15.gif and named it Lfish15.gif
#
# copy fish15.gif Lfish15.gif
#
# Then I "flopped" the fish to create a mirror image that
# goes in the opposite direction:
#
# convert Lfish15.gif -flop Rfish15.gif
#
# The 'L' fish goes to the left, and the 'R' fish to the
# right.
#
# Then when fish are created, the L fish are given negative
# dx speeds, and the R fish are given positive dx speeds.
#
import random
from graphics import *
H = 400
W = 400
class Fish:
"""the class for the fish"""
def __init__( self, fileName, centerPoint, dx ):
"""constructor"""
self.Image = Image( centerPoint, fileName )
self.dx = dx
def move( self ):
"""move the fish to the right using its own self.dx
and move the fish up or down some random number of pixels"""
ddy = [-1, -2, 1, 2, 0, 0, 0, 0, 0, 0, 0, 4]
index = random.randrange( len( ddy ) )
self.Image.move( self.dx, ddy[ index ] )
def draw( self, win ):
"""draw the fish on the graphics window"""
self.Image.draw( win )
def waitForClick( win, message ):
""" waitForClick: stops the GUI and displays a message.
Returns when the user clicks the window. The message is erased."""
# wait for user to click mouse to start
startMsg = Text( Point( win.getWidth()/2, win.getHeight()/2 ), message )
startMsg.draw( win ) # display message
win.getMouse() # wait
startMsg.undraw() # erase
def main():
"""the main program: creates a school of fish and moves them on the screen"""
global H, W
H = 399
W = 266
win = GraphWin( "Fish Tank", W, H )
background = Image( Point( W/2, H/2 ), "tank2.gif" )
background.draw( win )
#waitForClick( win, "click to start" )
#--- create a school of fish ---
school = []
for i in range( 1 + random.randrange( 5 ) ):
if random.randrange( 20 )<10:
f = Fish( "Rfish15.gif", Point( 30+i*20, 30+i*40 ), +1 + random.randrange( 3 ) )
else:
f = Fish( "Lfish15.gif", Point( 30+i*20, 30+i*40 ), -1 - random.randrange( 3 ) )
f.draw( win )
school.append( f )
#--- move the fish around, 100 times ---
for i in range( 100 ):
for f in school:
f.move()
#--- we're done when the user clicks the window ---
waitForClick( win, "click to end" )
win.close()
main()