summaryrefslogtreecommitdiff
path: root/ws2015/eip/blaetter/06/Polygon.java
blob: 461fcc627bf6248a339dec269c39cc3583cd11a6 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.util.ArrayList;
import java.util.Arrays;

import java.util.List;
import java.util.ListIterator;

import java.util.Collection;

import java.awt.Point;

import gameoflifetest.GraphicsWindow;

class Polygon {
    private final List<Position> points;

    public Polygon (Position[] pointsPrime)
    {
	points = Arrays.asList(pointsPrime);
    }

    public Polygon (Collection<Position> pointsPrime)
    {
	points = new ArrayList<Position>(pointsPrime);
    }

    public Polygon translate (int dx, int dy)
    {
	ListIterator<Position> it = points.listIterator();
	ArrayList<Position> translated = new ArrayList<Position>();
	while (it.hasNext())
	    translated.add(it.next().translate(dx, dy));
	return new Polygon(translated);
    }

    public Polygon erweitere (Position pos)
    {
	ArrayList<Position> extended = new ArrayList<Position>(points);
	extended.add(pos);
	return new Polygon(extended);
    }

    public Polygon reduziere (int n)
    {
	if (n == 0)
	    return new Polygon(new ArrayList<Position>());

	List<Position> reduced = new ArrayList<Position>(points);

	int c = 0;

	for (int i = 0; i < points.size(); i++)
	    {
		if (i % n == 1)
		    {
			reduced.remove(i - c);
			c++;
		    }
	    }

	return new Polygon(reduced);
    }

    public boolean istGleichZu(Polygon other)
    {
	ListIterator<Position> itThis = points.listIterator();
	ListIterator<Position> itOther = other.points.listIterator();

	while (itThis.hasNext() && itOther.hasNext())
	    if (! itThis.next().istGleichZu(itOther.next()))
		return false;

	if (itThis.hasNext() || itOther.hasNext())
	    return false;

	return true;
    }

    public double berechneFlaeche()
    {
	if (points.size() < 3)
	    return 0;
	
	double area = 0;

	for (int i = 0; i <= points.size(); i++)
	    {
		Position r0 = points.get(i % points.size());
		Position r1 = points.get((i + 1) % points.size());
		
		area += 0.5 * ((r0.getX() + r1.getX()) * (r1.getY() - r0.getY()));
	    }

	return area;
    }

    public void zeichneDich (GraphicsWindow gw)
    {
	for (int i = 0; i <= points.size(); i++)
	    {
		Position r0 = points.get(i % points.size());
		Position r1 = points.get((i + 1) % points.size());

		gw.drawLine(new Point(r0.getX(), r0.getY()), new Point(r1.getX(), r1.getY()));
	    }
    }
}