// // IMPORTANT NOTE: // This code is not meant to serve as an example of good coding style. // In fact, it is an ugly hack of some very old code written for DOS // and ported to Java. // import java.applet.Applet; import java.awt.*; // for Graphics, Color, Image, Point, ... import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.lang.Math; public class HilbertCurve extends Applet implements MouseListener { int width, height; Color fgcolor = Color.black, bgcolor = Color.white; int maxGeneration = 6; int generation = 1; double x, y; // current plotting position double s; // segment length double page; // the size of the square viewport Graphics global_g; int x0, y0; // upper left pixel of square viewport public void init() { width = getSize().width; height = getSize().height; try { maxGeneration = Integer.parseInt( getParameter("max_generation") ); } catch (Exception E) { } try { fgcolor = new Color(Integer.parseInt( getParameter("fgcolor"), 16 )); } catch (Exception E) { } try { bgcolor = new Color(Integer.parseInt( getParameter("bgcolor"), 16 )); } catch (Exception E) { } setBackground( bgcolor ); setForeground( fgcolor ); setup(); addMouseListener( this ); } void setup() { if (width > height) { page = width; x0 = (int)(width-page)/2; y0 = 0; } else { page = height; x0 = 0; y0 = (int)(height-page)/2; } s = page / Math.round( Math.pow( 2, generation ) ); } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { ++ generation; if ( generation > maxGeneration ) { generation = 1; } setup(); repaint(); e.consume(); } public void mousePressed( MouseEvent e ) { } public void mouseReleased( MouseEvent e ) { } void plot( double x_new, double y_new ) { global_g.drawLine( x0 + (int)Math.round( x ), y0 + (int)Math.round( y ), x0 + (int)Math.round( x_new ), y0 + (int)Math.round( y_new ) ); x = x_new; y = y_new; } void A( int g ) { if ( g > 0 ) { --g; D( g ); plot(x,y-s); A( g ); plot(x+s,y); A( g ); plot(x,y+s); B( g ); } } void B( int g ) { if ( g > 0 ) { --g; C( g ); plot(x-s,y); B( g ); plot(x,y+s); B( g ); plot(x+s,y); A( g ); } } void C( int g ) { if ( g > 0 ) { --g; B( g ); plot(x,y+s); C( g ); plot(x-s,y); C( g ); plot(x,y-s); D( g ); } } void D( int g ) { if ( g > 0 ) { --g; A( g ); plot(x+s,y); D( g ); plot(x,y-s); D( g ); plot(x-s,y); C( g ); } } public void paint( Graphics g ) { global_g = g; // this is a hack to avoid having to pass g around int tmp = s*( (int)Math.round( Math.pow(2,generation) ) - 1 ) + 1; x = ( page - tmp ) / 2; y = x + tmp; A( generation ); } public String getAppletInfo() { return "Written by Michael McGuffin"; } }