Computer Science 120
Introduction to Programming

Spring 2012, Siena College

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.*;

/*
 * Example ColorfulSpirograph: adding some randomly chosen
 * colors to our Spirograph.
 *
 * Jim Teresco, Siena College, CSIS 120, Spring 2011
 * Based on example from Williams College, CSCI 134
 *
 * $Id: ColorfulSpirograph.java 1501 2011-01-24 20:48:50Z 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 RandomIntGenerator pickAColor = new RandomIntGenerator(1, 4);

    // 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.nextValue();

        if (colorNumber == 1) {
            currentColor = Color.red;
        } else if (colorNumber == 2) {
            currentColor = Color.blue;
        } else if (colorNumber == 3) {
            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);
    }
}