Turtle Graphics with Java

Bern University of Teacher Education  
HomeStart Online-EditorPrintAndroid-TurtlegraphicsJava-Online

Multiple Turtles

With the constructor Turtle() more than one Turtle-object can be generated.
Turtle joe = new Turtle(); generates the first Turtle in a window. If afterwards a second Turtle is generated with Turtle luka = new Turtle(); it will run in a second window and not in the same as the first one. It is possible to generate up to 20 Turtles in different windows.

Run this example (Tu15.java)

// Tu15.java
import ch.aplu.turtle.*;
import java.awt.Color;

class Tu15
{
  Tu15()
  {
    Turtle joe = new Turtle();  //generates Turtel joe
    Turtle luka = new Turtle(); //generates Turtle luka in a different window
    luka.setColor(Color.red);
    luka.setPenColor(Color.green);

    for (int i = 0; i < 5; i++)
    {
      square(joe);    //joe draws a square
      joe.forward(30);
      square(luka);   //luka draws a square
      luka.forward(30)
    }
  }

  void square(Turtle t)
  {
    for (int i = 0; i < 4; i++)
    {
      t.forward(30);
      t.right(90);
    }
  }

  public static void main(String[] args)
  {
    new Tu15();
  }
}
 

Test this example in the Online-Editor


With Turtle luka = new Turtle(joe); a second Turtle is generated in the window of the first one. So luka is now inside joe's window. In this example a constructor with a parameter is used: Turtle(Turtle other Turtle). This allows both Turtles to run in one window.

Run this example (Tu16.java)

// Tu16.java
import ch.aplu.turtle.*;
import java.awt.Color;

class Tu16
{
  Tu16()
  {
    Turtle joe = new Turtle()
    Turtle luka = new Turtle(joe); //generates luka in joe's window
    luka.setColor(Color.red);
    luka.setPenColor(Color.green);
    luka.setPos(100,0);

    for (int i = 0; i < 5; i++)
    {
      quadrat(joe);
      joe.forward(30);
      quadrat(luka);
      luka.forward(30);
    }
  }

  void quadrat(Turtle t)
  {
    for (int i = 0; i < 4; i++)
    {
      t.forward(30);
      t.right(90);
    }
  }

  public static void main(String[] args)
  {
    new Tu16();
  }
}
 

Test this example in the Online-Editor


Exercises