Turtle Graphics



Turtle Graphics


Processing uses an absolute coordinate system for its drawing functions, but other programming languages like Logo use a relative system called turtle graphics. :turtle:

In turtle graphics, you control a “turtle”, which you can think of as a pen. You can tell the turtle to move forward (which draws a line) or rotate, which makes it face a different direction. You can also change the turtle’s color, whether it should draw while it moves, etc.

The idea is that turtle graphics are a little easier to think about than an absolute coordinate system because you just have to imagine what the turtle would be doing, and you can design some pretty cool-looking things this way.

This program uses a few variables and functions to recreate turtle graphics in Processing.

float turtleX;
float turtleY;
float turtleHeading = 0;

void setup() {
  size(300, 300);
  turtleX = width/2;
  turtleY = height/2;
  background(64);
}

void draw() {

  stroke(random(256), random(256), random(256));

  rotateTurtle(random(360));
  float length = random(0, 150);

  forward(length);
  rotateTurtle(90);

  forward(length);
  rotateTurtle(90);

  forward(length);
  rotateTurtle(90);

  forward(length);
}

void forward(float amount) {

  float newX = turtleX + cos(radians(turtleHeading)) * amount;
  float newY = turtleY + sin(radians(turtleHeading)) * amount;

  line(turtleX, turtleY, newX, newY);
  fill(0);

  turtleX = newX;
  turtleY = newY;
}

void rotateTurtle(float degrees) {
  turtleHeading += degrees;
}
Code Editor

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

I pretty much stole borrowed this algorithm from Secret Coders, which is an awesome kids book that I highly recommend!

🐢 graphics

Tweak Ideas

  • Add to the program so you can tell the turtle whether to draw when it moves or not.
  • Draw a turtle using turtle graphics. 🐢 :turtle: 🐢
  • Look up examples of turtle graphics art (like the Secret Coders art gallery) and then make your own!

Creating Functions Examples

Comments

Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!