HexTile.java


Below is the syntax highlighted version of HexTile.java from §2.1 Static Methods.


 /*************************************************************************
 *  Compilation:  javac HexTiile.java
 *  Execution:    java HexTile N
 *  Dependencies: StdDraw.java
 *
 *  Create an N-by-N hexagonal tile.
 *
 *************************************************************************/

public class HexTile {
    public static void hexagon(double x, double y, double size) {
        double c1 = Math.sqrt(3) / 2;
        double c2 = .5;
        double[] px = { x + c1*size, x + c1*size, x,        x - c1*size, x - c1*size, x        };
        double[] py = { y - c2*size, y + c2*size, y + size, y + c2*size, y - c2*size, y - size };
        StdDraw.polygon(px, py);
    }

    public static void filledHexagon(double x, double y, double size) {
        double c1 = Math.sqrt(3) / 2;
        double c2 = .5;
        double[] px = { x + c1*size, x + c1*size, x,        x - c1*size, x - c1*size, x        };
        double[] py = { y - c2*size, y + c2*size, y + size, y + c2*size, y - c2*size, y - size };
        StdDraw.filledPolygon(px, py);
    }

    public static void main(String[] args) {
        double c = Math.sqrt(3) / 2;
        int N = Integer.parseInt(args[0]);
        StdDraw.setCanvasSize(900, 600);
        StdDraw.setXscale(-1, 3*N/2);
        StdDraw.setYscale(-1, N);
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                StdDraw.setPenRadius();
                StdDraw.setPenColor(StdDraw.BLACK);
                filledHexagon(i+.5*j, j*c, .5/c);
                StdDraw.setPenRadius(.005);
                StdDraw.setPenColor(StdDraw.WHITE);
                hexagon(i+.5*j, j*c, .5/c);
            }
        }
    }                
}


Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.
Last updated: Sun Feb 20 13:46:42 EST 2011.