CSC111 Programs for Week 11 2015
--D. Thiebaut (talk) 12:50, 13 April 2015 (EDT)
Aqarium.py (with bubbles)
# aquarium.gif
# D. Thiebaut
from graphics import *
import random
WIDTH = 700 # geometry of tank2.gif
HEIGHT = 517
class Fish:
def __init__( self, fileNm, xx, yy ):
self.fileName = fileNm
self.x = xx
self.y = yy
self.image = Image( Point( xx, yy ), fileNm )
def draw( self, win ):
self.image.draw( win )
def moveRandom( self ):
deltax = - random.randrange( 10 )
deltay = random.randrange( -3, 3 )
self.image.move( deltax, deltay )
x = self.image.getAnchor().getX()
if x < -50:
self.image.move( WIDTH+100, 0 )
class Bubble:
def __init__( self, center ):
self.circ = Circle( center, random.randrange(5, 15) )
self.circ.setOutline( "white" )
def draw( self, win ):
self.circ.draw( win )
def moveRandom( self ):
deltaX = random.randrange( -3, 3 )
deltaY = random.randrange( -5, 0 )
self.circ.move( deltaX, deltaY )
# make bubbles wrap around...
if self.circ.getCenter().getY() < 0:
self.circ.move( 0, HEIGHT+50 )
def main():
# open the window
win = GraphWin( "CSC Aquarium", WIDTH, HEIGHT )
# display background
background = Image( Point( WIDTH//2, HEIGHT//2 ), "tank2.gif" )
background.draw( win )
fishList = []
for i in range( 4 ):
fish = Fish( "fish0.gif", i*100, 350 )
fish.draw( win )
fishList.append( fish )
# animation loop
bubbles = []
while True:
# move all fish
for fish in fishList:
fish.moveRandom()
# new bubble?
p = win.checkMouse() # did the user click the mouse?
if p != None: # None means no, a real Point means yes
b = Bubble( p ) # create a new bubble
b.draw( win ) # draw it
bubbles.append( b ) # add it to the list of bubbles
# move bubbles
for b in bubbles:
b.moveRandom()
win.close()
main()