Change Contents of the Bubble
View this PageEdit this Page (locked)Uploads to this PageHistory of this PageHomeRecent ChangesSearchHelp Guide

Demonstration of turtle predator chasing prey

class Chase extends Thread {
  
  public static void main(String args[]) {
    
    // Create an amphitheater in which our turtles will fight to the death
    World amphitheater = new World(960, 720);
    
    // Create two turtles: a predator and its prey
    Turtle predator = new Turtle(amphitheater);
    Turtle prey = new Turtle(amphitheater);

    // The predator's and prey's initial speeds
    double predSpeed = 40.0;
    double preySpeed = predSpeed - 5.0;
    
    // Position the turtles in their starting positions.
    // The predator is aiming at the prey; the prey is pointing South-East.
    predator.penUp();
    prey.penUp();
    int x1 = (int)(Math.random()*amphitheater.getWidth()/4.0);
    int y1 = (int)(Math.random()*amphitheater.getHeight()/4.0);
    int x2 = (int)(amphitheater.getWidth()/2.0);
    int y2 = (int)(amphitheater.getHeight()/2.0);
    predator.moveTo(x1, y1);
    prey.moveTo(x2, y2);
    predator.turnToFace(x2, y2);
    prey.turnToFace(amphitheater.getWidth(), amphitheater.getHeight());
    predator.penDown();
    prey.penDown();
    
    // Have the predator chase the prey and the prey run away until the
    // predator has closed to within tooth distance or has collapsed exhausted.
    double dist = Math.sqrt(Math.pow(predator.getXPos()-prey.getXPos(), 2) + Math.pow(predator.getYPos()-prey.getYPos(), 2));
    double toothDist = 1.0;
    while ((dist > toothDist) && (predSpeed > 0.0)) {
 
      // The prey panics and keeps changing direction.
      int evasiveAngle = ((int)(Math.random()*150)) - 75;
      prey.turn(evasiveAngle);
      prey.forward((int)(preySpeed));
          
      // The predator aims at where the prey is.
      predator.turnToFace(prey.getXPos(), prey.getYPos());
      double closingDistance = predSpeed;
      
      // We can optionally stop the predator overshooting.
      // closingDistance = (int)(Math.min(dist, predSpeed));

      // Close in on the victim
      predator.forward((int)closingDistance);

      // Pause so that we can watch what happens at leisure.
      try {
        Thread.sleep(250);
      } catch (InterruptedException e) {
        ;
      }

      // Both turtles get tired....
      if (predSpeed >= 0) {
        predSpeed = predSpeed - 0.25;
      }
      if (preySpeed >= 0) {
        preySpeed = predSpeed - 0.10;
      }

      dist = Math.sqrt(Math.pow(predator.getXPos()-prey.getXPos(), 2) + Math.pow(predator.getYPos()-prey.getYPos(), 2));

    }
  }

}


Link to this Page