summaryrefslogtreecommitdiff
path: root/ws2015/eip/blaetter/07/H7-1C/de/lmu/tcs/Hexagon.java
blob: 12f10316128fbb3c5f8e96e2cf22be7ee1a45541 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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;
    }
}