////////////////////////////////////////////////////////////////// // // sierpinski.cpp // // Started in Pascal by Jeff Ondich on 2/19/96 // Last modified 11/10/99 // // This program uses the g2 graphics library, // and should be compiled like so: // // g++ -o sierpinski sierpinski.cpp -L/usr/X11R6/lib -lm -lX11 -lgd -lg2 // /////////////////////////////////////////////////////////////////// #include #include #include const int windowHeight= 800; const int windowWidth = 800; void DrawTriangle( int window, double left, double bottom, double legLength ); void DrawPicture( int window, double x, double y, int depth, double legLength ); int main() { int window = g2_open_X11( windowWidth, windowHeight ); int black_ink = g2_ink( window, 0, 0, 0 ); int white_ink = g2_ink( window, 1, 1, 1 ); g2_set_background( window, white_ink ); g2_pen( window, black_ink ); int howDeep = 6; double howWide = 200; double startingX = 300; double startingY = 300; DrawPicture( window, startingX, startingY, howDeep, howWide ); cin.ignore(); return( 0 ); } /////////////////////////////////////////////////////////////////// // DrawTriangle draws the 45-45-90 triangle whose legs // have length legLength and extend left and down from // the point upperRight. /////////////////////////////////////////////////////////////////// void DrawTriangle( int window, double left, double bottom, double legLength ) { g2_move( window, left, bottom ); g2_line_to( window, left + legLength, bottom ); g2_line_to( window, left, bottom + legLength ); g2_line_to( window, left, bottom ); } /////////////////////////////////////////////////////////////////// // DrawPicture draws a picture. Note the recursion. /////////////////////////////////////////////////////////////////// void DrawPicture( int window, double x, double y, int depth, double legLength ) { if( depth > 0 ) { DrawTriangle( window, x, y, legLength ); // LINE A double halfLeg = legLength / 2; double newX, newY; newX = x - halfLeg; newY = y + halfLeg; DrawPicture( window, newX, newY, depth-1, halfLeg ); newX = x + halfLeg; newY = y - halfLeg; DrawPicture( window, newX, newY, depth-1, halfLeg ); newX = x + halfLeg; newY = y + halfLeg; DrawPicture( window, newX, newY, depth-1, halfLeg ); // LINE B } }