Comp 110 Turtle Graphics Reference

Turtle Graphics

The turtle graphics library included for us in introCS will allow us to use different coding concepts and algorithms we learn throughout the semester to create fun patterns and designs. There are several functions that can be imported from "introcs/turtle" that will allow us to move an invisible turtle around our screen and create graphics dictated by our code.

import { forward, left, right, moveTo } from "introcs/turtle";

Forward

The forward function has the following signature:

forward(n: number): void

You can call the forward function with some number n, and can expect the turtle to move forward in its current direction by n pixels.

Left

The left function has the following signature:

left(rad: number): void

You can call the left function with some number rad, and can expect the turtle to rotate left in its current position by rad radians. Remember that a full circle has 2π radians.

Right

The right function has the following signature:

right(rad: number): void

You can call the right function with some number rad, and can expect the turtle to rotate right in its current position by rad radians. Remember that a full circle has 2π radians.

moveTo

The moveTo function has the following signature:

moveTo(x: number, y: number): void

You can call the moveTo function with some number x and some number y, and can expect the turtle to move to the specified (x, y) coordinate.

Example use

Here's an example of how we might use turtle graphics to draw a horizontal zig-zag with 10 points!

let i = 0;
while (i < 10) { 
  if (i  === 0) {
      left(Math.PI / 4);
  } else if (i % 2 === 0) {
      left(Math.PI / 2);;
  } else {
      right(Math.PI /2);
  }
  forward(50);
  i++;
}

Recursive art!

Recursion enhances our ability to make more nuanced and intricate art! Basically the idea is that you draw the same thing over and over again and use only a few simple lines of code to create something beautiful. Let's take a look at some examples!

Special spirals!

In lecture we went over the examples of drawing trees and a square spiral, but what if you wanted your spiral to be customizable? Here's a function that lets you make any sort of special spiral you want:

let specialSpiral = (sideLength: number, angle: number, scaleFactor: number, minLength: number): void => {
    if (sideLength <= minLength) {
        return;
    } 
    forward(sideLength);
    left(angle);
    specialSpiral(sideLength*scaleFactor, angle, scaleFactor, minLength);
};

It takes in 4 parameters: the initial sideLength of your spiral, the angle by which the spiral will be turning left, the factor by which the sideLength will decrease with every recursive call, and our minimum sideLength which acts as our base case. Here a few example calls to specialSpiral and the resulting art!

specialSpiral(150, 45, 0.95, 5);
specialSpiral(400, 15, 0.95, 5);
specialSpiral(20, 25, 0.99, 0.05);