import javax.swing.*; import java.awt.*; /** Demo for recursion, CS1110, Fall 2009 */ public class Hilbert extends Turtle { int d= 20; // size of line between hilberts int ms= 500; // time to wait after drawing /** Precondition: The turtle faces east [or west]. * Draw a Hilbert space-filling curve of order n * north/east [or south/west] * of the current turtle position. * End up facing east [or west]*/ public void hilbert0(int n) { pause(ms); if (n == 0) return; addAngle(90); // Face north [or south] hilbert1(n-1); move(d); // Line heading north [or south] addAngle(-90); // Face east [or west] hilbert0(n-1); move(d); // Line heading east [or west] hilbert0(n-1); addAngle(-90); // Face south [or north] move(d); // Line heading south [or north] hilbert1(n-1); addAngle(90); // Face east [or west] } /** Precondition: The turtle faces north [or south] * Draw a Hilbert space-filling curve of order n * north/east [or south/west] * of the current turtle position. * End up facing north [or south]*/ public void hilbert1(int n) { pause(ms); if (n == 0) return; addAngle(-90); // Face east [or west] hilbert0(n-1); move(d); // Line heading east [or west] addAngle(90); // Face north [or south] hilbert1(n-1); move(d); // Line heading north [or south] hilbert1(n-1); addAngle(90); // Face west [or east] move(d); // Line heading west [or east] hilbert0(n-1); addAngle(-90); // Face north [or south] } /** Draw a Hilbert space-filling curve of depth n. * Each line is d units long. * Wait ms milliseconds at each recursive call */ public void drawHilbert(int n, int d, int ms) { this.d= d; this.ms= ms; int SIZE= 512; double max= Math.pow(2, n); clear(); moveTo(5, getHeight()-5, 0); System.out.println("Hilbert " + n + "-curve. Line length " + d); hilbert0(n); } }