Squares.java


Below is the syntax highlighted version of Squares.java from §3.6 Case Study: Purple America.


/******************************************************************************
 *  Compilation:  javac Squares.java
 *  Execution:    java Squares N
 *  Dependencies: Draw.java DrawListener.java
 *
 *  Draw an N-by-N grid of squares. User clicks a grid
 *  square. Alternate between drawing a red or blue circle
 *  in the grid square.
 *
 ******************************************************************************/

import java.awt.Color;

public class Squares implements DrawListener {
    private int pieces = 0;
    private Draw draw = new Draw();

    public Squares(int N) {
        draw.addListener(this);
        draw.setXscale(0, N);
        draw.setYscale(0, N);

        // draw black grid lines with gray background
        draw.clear(Color.LIGHT_GRAY);
        draw.setPenColor(Color.BLACK);
        for (int i = 0; i <= N; i++) draw.line(i, 0, i, N);
        for (int j = 0; j <= N; j++) draw.line(0, j, N, j);
        draw.show();
    }

    public void mousePressed(double x, double y) {
        if (pieces % 2 == 0) draw.setPenColor(Color.BLUE);
        else                 draw.setPenColor(Color.RED);
        draw.filledCircle(Math.floor(x) + 0.5, Math.floor(y) + 0.5, .375);
        pieces++;
        draw.show();
    }


    public void keyTyped(char c) { draw.save("squares" + c + ".png"); }

    public void keyPressed(int keycode)  { }
    public void keyReleased(int keycode) { }
    public void mouseDragged (double x, double y) { }
    public void mouseClicked (double x, double y) { }
    public void mouseReleased(double x, double y) { }


    // test client
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        new Squares(N);
    }
   
}


Copyright © 2000–2019, Robert Sedgewick and Kevin Wayne.
Last updated: Sun Sep 6 06:40:03 EDT 2020.