Introductory Programming
Fall 2004
Homework 4
The reading for this assignment is Chapter 4 of
How to think....
- On paper, sketch what you think this program will draw:
def draw(t, dist, n):
if n==0:
return
fd(t, dist)
lt(t)
draw(t, dist, n-1)
bob = Turtle(world)
draw(bob, 50, 4)
- Now type the code into turtle_code.py and run
it using World.py. Did you get what you expected?
- Draw a stack diagram that shows the state of the program
when n == 0.
- Now change draw so that if n is even, the
turtle turns left, and if n is odd, it turns right.
What do you expect to see? Run the code and check.
- From the department of deliberate errors, remove the lines
that say
if n==0:
return
Now the recursion has no base case, so it will keep going, calling
draw over and over. If you wait long enough, eventually the
stack grows too big and you'll get a RuntimeError: maximum
recursion depth exceeded.
In this section, we will investigate the mating behavior of amoebas.
But remember, this isn't exactly biology.
- Download http://wb/ip/code/Amoebas.py. Read over the
code and then run it. You should see two amoebas moving around the
slide at random.
- Inside the move function, add code that keeps the amoebas
from moving off the slide. Notice that move takes an optional
parameter named limit that is meant to be the boundary. That
is, the coordinates of the amoeba should always be between -limit
and +limit.
- You might notice that the amoebas sometimes have trouble finding
each other. It's like a microscopic version of a Jane Austen novel.
But from our omniscient point of view, we can help them by changing the
code that controls their behavior.
Write a function called nudge that takes two amoebas as parameters
and that tries to move the first amoeba toward the second amoeba by
some small amount. Inside main, you can
nudge each amoeba toward the other.
Keep it simple: nudge doesn't have to do very much to get the
amoebas together.
- Inside main and after both amoebas have moved, add code
that computes the distance between the amoebas and, if it is less
than 1.0, changes the behavior of the amoebas in a way that you
think is appropriate.
- ... biology
- Google `Sex and the
single amoeba' for more information (than you wanted).
|