class VonKoch { static void vonKoch(DrawingWindow w, int n, // niveau de récursion demandé float xa, float ya, // coordonnées du point A float xb, float yb) // coordonnées du point B { if (n == 0) { w.drawLine(Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb)); } else { float xc = (2 * xa + xb) / 3; float yc = (2 * ya + yb) / 3; float xd = (xa + 2 * xb) / 3; float yd = (ya + 2 * yb) / 3; float x = xd - xc; float y = yd - yc; float xe = xc + (x - y * (float)Math.sqrt(3)) / 2; float ye = yc + (x * (float)Math.sqrt(3) + y) / 2; vonKoch(w, n - 1, xa, ya, xc, yc); vonKoch(w, n - 1, xc, yc, xe, ye); vonKoch(w, n - 1, xe, ye, xd, yd); vonKoch(w, n - 1, xd, yd, xb, yb); } } // Algorithme de remplissage. Version récursive. static void floodFillRec(DrawingWindow w, int x, int y, // coordonnées de départ int old_color) // couleur à « effacer » { if (x < 0 || y < 0 || x >= w.width || y >= w.height || w.getPointColor(x, y) != old_color) { return; } // 1. on cherche le point le plus à gauche sur la ligne courante... int xl = x; while (xl > 0 && w.getPointColor(xl - 1, y) == old_color) { xl--; } // ... et celui le plus à droite int xr = x; while (xr < w.width - 1 && w.getPointColor(xr + 1, y) == old_color) { xr++; } // 2. on colorie la ligne w.drawLine(xl, y, xr, y); // 3. on recommence récursivement au dessus et en dessous for (int xx = xl; xx <= xr; xx++) { floodFillRec(w, xx, y - 1, old_color); floodFillRec(w, xx, y + 1, old_color); } } // Fonction de remplissage, à partir d'un point donné static void floodFill(DrawingWindow w, int x, int y) { floodFillRec(w, x, y, w.getPointColor(x, y)); } public static void main(String[] args) { DrawingWindow w = new DrawingWindow("von Koch", 600, 600); // coordonnées de départ : même si ce n'est pas nécessaire, on souhaite // un triangle équilatéral. La longuer du côté est 'c'. float c = (float)Math.min(w.width - 4, (w.height - 4) * Math.sqrt(3) / 2); float xa = w.width / 2f; float ya = (float)(w.height - 2 * c / Math.sqrt(3)) / 2f; float xb = (w.width - c) / 2f; float yb = (float)(ya + c * Math.sqrt(3) / 2); float xc = xb + c; float yc = yb; int rec = 5; w.setColor("black"); vonKoch(w, rec, xa, ya, xb, yb); vonKoch(w, rec, xb, yb, xc, yc); vonKoch(w, rec, xc, yc, xa, ya); w.setColor("blue"); floodFill(w, 0, 0); w.setColor("gray"); floodFill(w, w.width / 2, w.height / 2); } }