RechteckDemo.java
RechteckDemo.java
—
Java source code,
2 KB (3063 bytes)
Dateiinhalt
import java.awt.Color; import java.awt.Graphics2D; import java.util.Random; /** * @author jost * */ public class RechteckDemo { public static void main(String[] args) { // Eckdaten der Grafik final int xsize = 520; final int ysize = 520; final int iterations = 14; //Initalisierung von Grafik und Zufallsgenerator Random random = new Random(); CanvasFrame frame = new CanvasFrame("Sierpinski", xsize, ysize); Graphics2D canvas = frame.getGraphics(); Color color = Color.BLACK; //Ein Rechteck ueber das Gesamte Fenster Punkt upperLeft = new Punkt(4,4); Punkt lowerRight = new Punkt(xsize-4,ysize-4); Rechteck full = new Rechteck(lowerRight, upperLeft); Rechteck[] oblist = new Rechteck[] { full }; for(int i = 0; i < iterations; i++){ // Alle Rechtecke in oblist zeichnen canvas.setColor(color); for(int j = 0; j < oblist.length; j++) { drawRechteck(canvas, oblist[j]); } // Alten Text loeschen canvas.setColor(Color.BLACK); canvas.fillRect(4, ysize-55, 123, 50); if (color == Color.BLACK) { canvas.setColor(Color.WHITE); } else { canvas.setColor(color); } canvas.drawString("Click to proceed", 7, ysize - 40); canvas.drawString("Iterations: " + i, 7, ysize - 25); canvas.drawString("Squares: " + oblist.length, 7, ysize - 10); frame.repaint(); frame.waitMouseClicked(); // Naechste Iteration vorbereiten oblist = sierpinski(oblist); color = new Color(random.nextInt(1 << 24)); } canvas.setColor(Color.BLACK); canvas.fillRect(4, ysize-55, 123, 50); canvas.setColor(Color.WHITE); canvas.drawString("Finished!", 7, ysize - 40); canvas.drawString("Squares: " + oblist.length, 7, ysize - 10); frame.repaint(); } /** * * @param obs * Liste mit Rechtecken. Jedes Rechteck wird durch drei innere Rechtecke ersetzt * @return * Ersetzte Liste mit Rechtecken */ public static Rechteck[] sierpinski(Rechteck[] obs) { Rechteck[] result = new Rechteck[3 * obs.length]; int j = 0; for(int i = 0; i < obs.length; i++) { Rechteck[] intermediate = stepSierpinski(obs[i]); result[j++] = intermediate[0]; result[j++] = intermediate[1]; result[j++] = intermediate[2]; } return result; } /** * * @param ob * ein beliebiges Rechteck * @return * Liste mit drei inneren Rechtecken */ public static Rechteck[] stepSierpinski(Rechteck ob) { Rechteck ob_um = new Rechteck(ob); ob_um.half(); ob_um.square(); int dy = ob_um.getHeight() / 2; ob_um.move(0,dy); Rechteck ob_ll = new Rechteck(ob_um); ob_ll.alignUpperLeft(ob); Rechteck ob_lr = new Rechteck(ob_ll); ob_lr.moveWidth(); return new Rechteck[] {ob_ll, ob_um, ob_lr}; } /** * Draws an Rechteck object in the current color * * @param canvas * Canvas to draw upon * @param ob * Rechteck to be drawn */ public static void drawRechteck(Graphics2D canvas, Rechteck ob) { Punkt ll = ob.getUpperLeft(); canvas.fillRect(ll.getX(), ll.getY(), ob.getWidth(), ob.getHeight()); } }
Artikelaktionen