Turtle graphics is a popular way to write graphics programs. You may have seen turtle graphics before if you used LOGO. The idea is that there is a ``turtle'' (it really just looks like a triangle), that you can move around the screen. As the turtle moves it draws a track, so you can make just about any line drawing by giving turtle commands. Even though there are just a few turtle graphics commands, they are perfect for playing around with recursion, which is when a function in a program calls itself. Here are the commands in our version of turtle graphics:
right( int angle ) - turn (in one place) "angle" degrees clockwise left( int angle ) - turn (in one place) "angle" degrees counter-clockwise forward( int steps ) - move "steps" distance in the direction you're heading back( int steps ) - move "step" opposite the direction you're heading hide() - make turtle invisible (this makes drawing faster) show() - make turtle visible (this makes drawing slower) clear() - clear window repeat( int num ) - this is like a 'C' for loop init_turtle() - set up turtle graphics wait_button() - wait for user to click right mouse button
Here's an example of a simple turtle graphics function to draw a triangle:
tri( int length, int level ) { if( level == 0 ) return; repeat( 3 ) { forward( length ); right( 120 ); } }
lab6
directory somewhere in your home
directory and copy files to it, as follows.
> mkdir lab6 > cd lab6 > cp /cs/cs2005/pub/labs/lab6/* .
square()
in the
section where it says /* ADD COMMANDS HERE */
, and make it draw a
square. Use the triangle function as a guide.
To compile and run your program type:
> make squares > squares
square()
function, and
say what gets drawn when you run square? Explain why.
square( length/2, level-1 );
square()
function. What gets drawn when you run
squares now? Explain why.square( 100, 6 );
vee()
draws a 'V', like
a branch of a tree. Try running tree to see what it does. To compile
and run the tree program type:
> make tree > tree
vee()
function (you only have to add 2 lines!), so that a
smaller 'v' is drawn at the end of every branch.
/cs/cs2005/bin/turnin lab6 squares.c tree.c lab6.questions
snow.c
file in your directory that you can compile and run.