Lecture 5 (Tychonievich) - Turtles

Lecture Date: Friday, January 23

Today we began a 2-day whirlwind tour of most of the semester.

Setup:

  1. open eclipse
  2. create a Java project
  3. create a Class in that project. Make sure you do not specify a package (it should show up in (default package) in the package explorer display).
  4. if eclipse didn’t do this for you, add public static void main(String[] args) { }; code goes inside those curly braces.
  5. Download Turtle.java and World.java and drag the downloaded files into the src folder of your project.

Basics

World earth = new World();
Turtle steve = new Turtle(earth);

  • Turtle steve makes a variable, a name that can refer to a Turtle.
  • steve = new Turtle(earth); makes a new Turtle object on the world named earth

steve.forward(100);
steve.right(45);
steve.backward(50);

  • steve.action(information) is the general pattern of how you tell a turtle to do something. We talked about forward, backward, left, and right.

steve.forward(100);
steve.left(90);
steve.forward(100);
steve.left(90);
steve.forward(100);
steve.left(90);
steve.forward(100);
steve.left(90);

Loops and Methods

  • the above code makes a square
  • it has a lot of repetition; programmers avoid repeating themselves
  • there are loops in Java, ways to say “repeat this.” The for loop means “repeat a fixed number of times”:

for(int i = 0; i < 4; i = i + 1) {
    steve.forward(50);
    steve.left(360/4);
}

  • We can change just a little to make the loop draw a different shape:

for(int i = 0; i < 9; i = i + 1) {
    steve.forward(50);
    steve.left(360/9);
}

  • We can write methods to give a name to a group of actions.
  • Methods must go inside the class but outside main.

public static void drawPolygon(Turtle ophilia, int sides, int size) {
    for(int i = 0; i < sides; i = i + 1) {
        ophilia.forward(size);
        ophilia.left(360/sides);
    }
    }

From lecture:

Audio: