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 = 0.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 = 0.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.0*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+0.5*j, j*c, 0.5/c);
                StdDraw.setPenRadius(0.005);
                StdDraw.setPenColor(StdDraw.WHITE);
                hexagon(i+0.5*j, j*c, 0.5/c);
            }
        }
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:15:13 EDT 2022.