package de.lmu.tcs; import java.awt.*; class Hexagon { private final Point center; private final int sideLength; public Hexagon(Point center2, int sideLength2) { this.center = center2; this.sideLength = sideLength2; } public Point[] vertices() { Point vertex = new Point((int) (Math.sqrt(3) * ((double) sideLength) / 2), sideLength / 2); Point[] relative = { new Point(0, sideLength) , vertex , mirrory(vertex) , new Point(0, -1 * sideLength) , mirrorx(mirrory(vertex)) , mirrorx(vertex) }; for (Point r : relative) r.translate(center.x, center.y); return relative; } private static Point mirrorx(Point r) { return new Point(r.x * -1, r.y); } private static Point mirrory(Point r) { return new Point(r.x, r.y * -1); } public int height() { return 2 * sideLength; } public int width() { return (int) (Math.sqrt(3) * (double) sideLength); } public boolean contains(Point r) { // clever maths is clever (and very hexagon-specific) int rx = Math.abs(r.x - center.x); int ry = Math.abs(r.y - center.y); if (rx > width() / 2 || ry > height()) return false; return width() * height() - height() * rx - height() * ry >= 0; } public Rectangle boundingBox() { Point uL = new Point(center); uL.translate(-1 * width() / 2, -1 * height() / 2); return new Rectangle(uL, new Dimension(width(), height())); } public Polygon asPolygon() { Polygon ret = new Polygon(); for (Point r : vertices()) ret.addPoint(r.x, r.y); return ret; } }