Week 6, Wednesday: Fruitful Functions

announcements

review

more practice with functions

Given the following main(), write the functions needed to draw the circles, find the biggest one, color it red, and then animate the circles.

def main():
  width = 800
  height = 800
  gw = GraphWin("circle animation", width, height)
  gw.setBackground("white")

  circles = makeCircles(gw, 10)
  # findBiggest(circles, "red")
  # animate(circles)

  gw.getKey()

Note: the last two functions (findBiggest() and animate()) are commented out, so we can just work on makeCircles() for now. This is a good technique to learn: write main(), but comment out any functions you have yet to write. Write and test each function, one at a time.

makeCircles()

This function should create and draw the given number of circles. Each circle should have a random size an location (in the graphics window). The function should create the circles and store them all in a list. At the end of the function, return the list back to main.

Here's how to use the list append() method, with pseudo code for the function:

circles = []      # start with empty list
for loop:
  pick random location (x,y), size (radius)
  create circle: c = Circle(...)
  draw it, change color, etc
  circles.append(c)
# return list of circles to main
return circles

findBiggest()

This function gets the list of Circle objects from main, finds the biggest one, and changes its color to the given color ("red" shown above). To find the biggest circle we can use the Circle method getRadius(), and compare the radii of each circle. Here's some pseudo code for this function:

# set biggest (so far) to be first circle
biggest = circles[0]   
for loop over all circles in list
  get radius of current circle
  compare it to radius of biggest
  if current_circle_radius > biggest_radius:
     set biggest to current circle
# after for loop, biggest should point to largest circle in list
biggest.setFill(color)

Note: this function does not need to return anything. It just changes the color of one circle in the given list.

animate()

This function also gets the list of circles from main() and just animates them by moving them random amounts. A simple for loop to move each circle a small amount, plus an outer loop to run the animation until the user clicks:

while user hasn't clicked:
  for loop over all circles:
     pick random/small dx,dy
     move current circle by dx,dy
  sleep a small amount