Change Contents of the Bubble
Welcome to CS1315. Click on the python to add comments.

This page removed for FERPA compliance
View this PageEdit this PageUploads to this PageHistory of this PageHomeRecent ChangesSearchHelp Guide

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(960, 720)

  # Create two turtles: a predator and its prey
  predator = makeTurtle(amphitheater)
  prey = makeTurtle(amphitheater)

  # The predator's and prey's initial speeds
  predSpeed = 40
  preySpeed = predSpeed - 10

  # 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())
  penDown(predator)
  penDown(prey)

  # 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 and predSpeed > 0:

    # 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())

    # The prey panics and keeps changing direction.
    evasiveAngle = random.choice(range(-75, 75))
    turn(prey, evasiveAngle)
    forward(prey, preySpeed)

    # PaREMOVEDe so that we can watch what happens at leisure.
    time.sleep(0.25)

    # We need to stop the predator overshooting.
    # See what happens if you take this out.
    closingDistance = int(min(distanceBetween(predator, prey), int(predSpeed)))

    # Close in on the victim
    forward(predator, closingDistance)

    # PaREMOVEDe so that we can watch what happens at leisure.
    time.sleep(0.25)

    if predSpeed >= 0:
      predSpeed = predSpeed - 0.25


# 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
  

def sickScreenSaver():
  while 1:
    chase()
    time.sleep(2.0)


Link to this Page