// クリックした点がこれまでの多角形の内部にないかどうかチェック for (List<Point> points : polygons) { if (points.equals(latestPoints) || points.size() < 3) break;
Polygon polygon = new Polygon(); for (Point point : points) { polygon.addPoint(point.x, point.y); } if (polygon.contains(p)) { return; } }
// すでにある点をクリックしたら削除 for (Point point : latestPoints) { if (distance(point, p) < 2.5) { latestPoints.remove(point); drawPolygons(rightClick); return; } }
// クリックした点がこれまでの多角形と交差しないかどうかチェック for (List<Point> points : polygons) { if (points.equals(latestPoints)) break;
for (int i = 0; i < points.size(); i++) { int ax = points.get(i).x; int ay = points.get(i).y; int bx = points.get((i + 1) % points.size()).x; int by = points.get((i + 1) % points.size()).y; for (int j = 0; j < latestPoints.size(); j++) { int cx = latestPoints.get(j).x; int cy = latestPoints.get(j).y; if (isIntersect(ax, ay, bx, by, cx, cy, p.x, p.y)) return; } } }
if (!rightClick) latestPoints.add(p);
drawPolygons(rightClick); }
private double distance(Point a, Point b) { return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2)); }
private void drawPolygons(boolean drawLine) { clear(); Graphics g = getGraphics(); for (List<Point> points : polygons) { Polygon polygon = new Polygon(); for (Point point : points) { g.fillOval(point.x - 2, point.y - 2, 5, 5); polygon.addPoint(point.x, point.y); } if (points.size() >= 3 && (!points.equals(polygons.get(polygons.size() - 1)) || drawLine)) { g.drawPolygon(polygon); } } g.dispose(); }
private void clear() { Graphics g = getGraphics(); g.setColor(getBackground()); Dimension d = getSize(); g.fillRect(0, 0, d.width, d.height); g.dispose(); }
private boolean isIntersect(int ax, int ay, int bx, int by, int cx, int cy, int dx, int dy) { int ta = (cx - dx) * (ay - cy) + (cy - dy) * (cx - ax); int tb = (cx - dx) * (by - cy) + (cy - dy) * (cx - bx); int tc = (ax - bx) * (cy - ay) + (ay - by) * (ax - cx); int td = (ax - bx) * (dy - ay) + (ay - by) * (ax - dx);