simulation of a predator turtle chasing its prey
import random
import time
def chase():
# Create an amphitheater in which our turtles will fight to the death
amphitheater = makeWorld()
# Create two turtles: a predator and its prey
predator = makeTurtle(amphitheater)
prey = makeTurtle(amphitheater)
# Position the turtles in their starting positions.
# The predator is aiming at the prey; the prey is pointing South-East.
penUp(predator)
penUp(prey)
x1 = random.choice(range(0, amphitheater.getWidth()/4))
y1 = random.choice(range(0, amphitheater.getHeight()/4))
x2 = amphitheater.getWidth()/2
y2 = amphitheater.getHeight()/2
moveTo(predator, x1, y1)
moveTo(prey, x2, y2)
turnToFace(predator, x2, y2)
turnToFace(prey, amphitheater.getWidth(), amphitheater.getHeight())
# Have the predator chase the prey and the prey run away until the
# predator has closed to within tooth distance.
while distanceBetween(predator, prey) > 5:
# The prey panics and keeps changing direction.
evasiveAngle = random.choice(range(-90, 90))
turn(prey, evasiveAngle)
forward(prey, 40)
# The predator aims at where the prey is, not where it is moving to.
# But if it is fast enough, it won't keep going round in a circle.
turnToFace(predator, prey.getXPos(), prey.getYPos())
# We need to stop the predator overshooting.
# See what happens if you take this out.
closingDistance = int(min(distanceBetween(predator, prey), 50))
# Close in on the victim
forward(predator, closingDistance)
# Pause half a second so that we can watch what happens at leisure.
time.sleep(0.5)
# Compute the Euclidean distance between turtles. Very like the distance between
# colors, except that they have three dimensions (RGB). Turtles live in a
# two-dimensional plane.
def distanceBetween(turtle1, turtle2):
x1 = turtle1.getXPos()
x2 = turtle2.getXPos()
y1 = turtle1.getYPos()
y2 = turtle2.getYPos()
dist = math.sqrt((x1-x2)**2 + (y1-y2)**2)
return dist
Link to this Page