Turtlegraphics for Smartphones and Tablets

Bern University of Teacher Education  
HomeStart Online EditorPrintAndroid GamesJava-Online

Use multiple turtles


On a playground multiple turtles can be created as instances of the class turtles. In order to use the method for multiple turtles, we give this method a turtle reference.

In our example the turtles joe and luka are drawing alternativley a step of a staircase

Edit source with online-compiler

Install App on smartphone or tablet

QR-Code

download sources (Tu13.zip)

// Tu13.java

package app.tu13;

import turtle.*;

public class Tu13 extends Playground
{
  Turtle joe = new Turtle(RED);
  Turtle luka = new Turtle(GREEN);

  public public void main()
  {
    joe.setPos(-120,-120);
    luka.setPos(-120,120);
    luka.rt(90);
    joe.setPenColor(RED);
    luka.setPenColor(GREEN);
    for (int = 0; i < 8; i++)
    {
      step(joe);    
      step(luka);   
    }
  }
  
  void step(Turtle t)
  {
    t.fd(30);
    t.rt(90);
    t.fd(30);
    t.lt(90);
  }
}
 

Explanatation to the program code:

Turtle joe = new Turtle(RED)

Creates a red turtle joe

void step(Turtle t)

The method step() will be generally declared for a random turtle t

step(joe)   
step(luka)   

Call of the method step() for turtle joe
Call of the method step() for turtle luka

 

In the following example turtles joe and luka are building a tower that is made out of red respectively green squares.

Edit source with online-compiler

Install App on smartphone or tablet

QR-Code

download sources (Tu14.zip)

// Tu14.java

package app.tu14;

import turtle.*;

public class Tu14 extends Playground
{
  Turtle joe = new Turtle(RED);
  Turtle luka = new Turtle(GREEN);

  public void main()
  {
    joe.setPos(-80,-50);
    luka.setPos(50,-50);
    joe.setPenColor(RED);
    luka.setPenColor(GREEN);
    for (int = 0; i < 5; i++)
    {
      square(joe);      
      square(luka);   
    }
  }
  
  void square(Turtle t)
  {
    for (int = 0; i < 4; i++)
    {
      t.fd(30);
      t.rt(90);
    }
    t.fill(t.getX() + 2, t.getY() + 2);
    t.fd(33);
  }
}
 

Explanations to the program code:

void square(Turtle)

The parameter turtle t belongs to the method square

square(joe) 

Turtle joe draws a red square

t.fill(t.getX() + 2, t.getY() + 2)

We would like to fill the squares successively. Therfeore we get with getX() and getY() the coordinates of the turtle after it is finished drawing a square. The point (getX() + 2, getY() + 2) lies within the square.