CSci 150: Foundations of computer science I
Home Syllabus Assignments Tests

Assignment 2: Tipsy turtle

Due: 2:00pm, Thursday, September 10. Value: 30 pts. Submit your saved file using the Sauron Submission System. [instructions]

Write a program that displays a turtle that starts from the center of the screen and walks randomly for 100 steps. Each step, the turtle should repeatedly go forward 5 pixels, then turn randomly, then go forward another 5 pixels, and so forth. Each random turn should be chosen randomly between −180 and 180 degrees.

Below is a program that may serve as a useful starting point: It guides a turtle around in a circle.

public class DizzyTurtle extends TurtleProgram {
    public void run() {
        Turtle dizzy;
        dizzy = new Turtle(95, 50);
        while(true) {
            dizzy.forward(10);
            dizzy.right(11.537);
        }
    }
}

In your program, you'll want some way to generate random numbers for each turn. To select your random numbers, you should use the Random class, which allows you to retrieve a sequence of random values between 0 and 1. This class is in the java.util package, so you will need to add the following line into imports, after the import turtles.*; line.

import java.util.*;

The Random class has constructors and methods just like the Turtle and Color classes. The relevant documentation for Random is as follows.

Random()

(Constructor) Constructs a new random sequence from which numbers can be drawn.

double nextDouble()

Returns the next random value in this sequence. This value will be between 0 and 1.

Note that the random numbers created by nextDouble are between 0 and 1. However, you want random numbers between −180 and 180. You can multiply nextDouble's returned number in order to extend its range to between 0 and 360, and then you can subtract 180 to translate the range to between −180 and 180.