Computer Science 252
Problem Solving with Java

Fall 2013, The College of Saint Rose

ColorfulSpirograph Demo

A working demo of ColorfulSpirograph will appear below. Click inside the applet to interact with it.



ColorfulSpirograph BlueJ Project

Click here to download a BlueJ project for ColorfulSpirograph.


ColorfulSpirograph Source Code

The Java source code for ColorfulSpirograph is below. Click on a file name to download it.


ColorfulSpirograph.java

import objectdraw.*;
import java.awt.*;
import java.util.Random;

/*
 * Example ColorfulSpirograph: adding some randomly chosen
 * colors to our Spirograph.
 *
 * Jim Teresco, Siena College, CSIS 120, Spring 2011
 * Modified for CSC 252, The College of Saint Rose, Fall 2013
 * Based on example from Williams College, CSCI 134
 *
 * $Id: ColorfulSpirograph.java 2218 2013-10-18 14:06:39Z terescoj $
 */

public class ColorfulSpirograph extends WindowController {

    // first coordinate of a line segment
    private Location linesStart;

    // color of next spriograph
    private Color currentColor;

    // generator for random numbers between 1 and 4
    private Random pickAColor = new Random();

    // used when picking a new color
    private int colorNumber;

    /*
     * Save the first coordinate of the line, and pick
     * a new random color.
     */
    public void onMousePress(Location point) {
        linesStart = point;

        colorNumber = pickAColor.nextInt(4);

        if (colorNumber == 0) {
            currentColor = Color.red;
        } else if (colorNumber == 1) {
            currentColor = Color.blue;
        } else if (colorNumber == 2) {
            currentColor = Color.magenta;
        } else {
            currentColor = Color.green;
        }
    }

    /*
     * As the user is dragging draw a line from
     * initial point where mouse pressed to current point.
     */
    public void onMouseDrag(Location point) {
        new Line(linesStart, point, canvas).setColor(currentColor);
    }
}