LABTITLE=: 'Turtle Geometry - JTurtle User Guide'
LABAUTHOR=: 0 : 0
L. Fraser Jackson 
I am indebted to Brian M. Schott for 
many helpful comments.  He also has a
different Turtle graphics system which 
has a range of 3D tools and multiple turtles. 
It can be downloaded from 
http://www.gsu.edu/~dscbms/tgsj/
)
LABCOMMENTS=: 'Copyright 2004 Version 0.006'
LABFOCUS=: 1
 
NB. =========================================================
Lab Chapter Introduction
NB. =========================================================
Lab Section Is this for you?  (JTurtle Version 1)
This lab is an introduction to JTurtle for J users.

If you are a K-8 student then other material separate from the J distribution is more appropriate and you should contact the author.

The Lab assumes some experience of J at the J Primer level.

Tne classical reference for Turtle Geometry is: 
H. Abelson and A. diSessa, Turtle Geometry: The computer as a medium for exploring mathematics.  MIT Press, 1980.

To load, enter:
)
PREPARE
4!:55[4!:1[i.4 NB. clear base
PREPARE
load 'turtle'

NB. =========================================================
Lab Section Introduction to JTurtle
Turtle geometry makes it easy to draw diagrams. It is designed for you to have fun constructing and exploring diagrams and their properties.  Try out your own ideas at any stage of this Lab.

JTurtle uses functions and statements very similar to those in the widely used Logo turtle geometry.  Teaching materials based on Logo should be able to be used with little change.

Look at the Chapter headings to give yourself an idea of the subjects covered in this Lab.
)

NB. =========================================================
Lab Section
In Windows move the displayed graph to the right of your screen, so you can see the graph window and the Lab text.  In the Java version the graph may be hidden. You may find it easier to move the top of the *.ijx session window to the bottom of the graph. 

To advance the Lab you must have focus on the  Lab  window.  Click within the lab window to give it focus if necessary. 

The code below generates the displayed graph. It will be explained fully later in this chapter of the Lab.
)

show repeat 20,(repeat 5 fd 1 rt 72) rt 18

NB. =========================================================
Lab Section The idea of a turtle
Turtle geometry uses movements of a 'turtle' from its current position to draw diagrams. The middle of the bottom side of the small teal coloured triangle is the position of the turtle.  The turtle is facing the point of the triangle opposite to the base which is the shortest side.  The turtle can only go straight forward or straight backwards.

To clear the screen and start a drawing use one of the show verbs illustrated below.  An empty right argument just displays the turtle.
)
showf ''

NB. =========================================================
Lab Section Starting a diagram - The show verbs 
There are two variants of the show verb.

    show    scales the graph to use nearly all the graph
            window

    showf   gives a predefined window, which permits 
            movement of about 100 units in any direction 
            from the origin at the center of the window

          
The right argument of a show verb is the turtle path to be displayed.  

The verb  turtle  generates a path which displays a turtle shape with the length argument specifying the length of the long sides. Try

    show  turtle 40
and
    showf turtle 40
)
showf turtle 40

NB. =========================================================
Lab Section Initialising the turtle
A show  verb always resets the turtle to the origin and sets the heading to the top of the screen.   This heading is sometimes called heading North.  To the right of the screen is called East, to the left West and to the bottom South.
)

NB. =========================================================
Lab Section Basic Commands  - fd, bk, rt, lt (1 of 2) 
There are four basic verbs or commands to create components of a turtle path.

    fd    moves the turtle forward
    bk    moves the turtle backwards

These commands must be followed by a distance in the chosen direction.
    
    rt    turns the turtle towards the right 
    lt    turns the turtle towards the left

These commands must be followed by the number of degrees to turn.

Try the following examples 
    showf fd 30
    showf bk 50
    showf rt 90 

and make changes to them to see what these verbs do.
)

NB. =========================================================
Lab Section Basic Commands  - fd, bk, rt, lt ((2 of 2) 
Diagrams with one step are boring.  To make multiple steps just list them in the order you want them done.
)
show rt 30 fd 40 rt 60 fd 40 rt 60 fd 40 rt 120 fd 80

NB. =========================================================
Lab Section Basic Commands  - fd, bk, rt, lt  (3 of 3)
The path verbs  fd, bk, rt and lt  construct a path from their right argument.  They expect a right argument which is a scalar or vector.  If it is a scalar it constructs a single step. If the number is followed by another path verb it defines the first step and the process is repeated until there are no further path verbs.

If a path verb is used without a left argument it returns a turtle path.  If it is used with a left argument, it returns the left argument followed by a turtle path.  This result will be processed by the path verb on its left.

Turtle paths are represented in the computer by a list of numbers.  You do not need to know about the details of how they are represented to use JTurtle.
)

NB. =========================================================
Lab Section Creating additional steps and displaying 
The commands in the next section illustrate some turtle paths. 

Moving your cursor back to a line and pressing enter will transfer the line to the bottom of the .ijx or execution window.  You can then modify the line and when you have the expression you want, execute it by pressing  Enter.
)

NB. =========================================================
Lab Section Building diagrams from earlier diagrams
Add additional actions (a verb and its argument) and re-execute the line to do simple experiments and explore the effect of the actions and adding steps to a path.  You should begin by adding steps at the end of the path.  Then explore adding steps earlier in the path. 

Try commands like

    showf rt 30 fd 40 rt 60 fd 40 rt 60 fd 40 rt 120 fd 80
    showf bk 40 fd 20
    showf rt 90 fd 50 bk 100 fd 50

Construct a line from northwest to southeast and place the turtle in the middle of the line.
)

NB. =========================================================
Lab Section Logo CS in JTurtle
If you have used Logo and think of beginning a diagram with CS (Clear Screen), then you can use  cs  to replace the 'show' command by entering 

    cs  =:  show

Now  cs  can be used wherever we had used show  or showf before. You can always rename verbs in J in this way to give them a name you prefer.

Note that JTurtle completely redraws the diagram each time a show verb is used.
)
   cs fd 20 rt 90 fd 30 rt 90 fd 20 rt 90 fd 30

NB. =========================================================
Lab Section set functions
 Turtle geometry focuses on changes from the current position.  Often we want to combine these movements with a bigger pattern on the plane, and for that we use movements to coordinate positions.

setxy  x,y    places the turtle at x,y without altering the                heading

setx   x      sets the x coordinate without altering heading

sety   y      sets the y coordinate without altering heading

seth   h      sets the heading in degrees from North, with                 positive values clockwise

sethm  h      sets the heading in degrees from East, with 
              positive values anticlockwise - the                          mathematics convention
)

NB. =========================================================
Lab Section Turtle paths and top down thinking 
In J a verb treats the whole expression on its right as its argument.  This means you can generate very complex arguments which depend on both functions and data.  A convenient way to think of the J verb  fd  is to regard it as making a forward step of the specified length, followed by all of the steps in the rest of the argument.  This is a top down way of thinking.

The J sentences to build paths are executed from the right, but the functions have been defined in a way which makes it natural to read them in the order of actions sequenced from the left.
)

NB. =========================================================
Lab Section The show verbs - multiple graph windows
You can display several paths at once using multiple graph windows. If a text left argument is used for the show verb the name will be used to label a new graph window. 

These windows will appear on top of the default graph display position.  You can move them to a new position and display them as well as the 'graph' window.  The 'graph' window is used for the 'base' locale.  For other locales the locale name is added to the graph title.

It is convenient to move the 'a', 'b' and 'c' windows used in this and later sections to positions where you can see them as well as the graph window

The next section illustrates how to overlay graphs in a single window using a list of boxed paths.
)

'a' show  T =: rt 90 fd 2 bk 1 rt 90 fd 2  NB.  Draw T

NB. =========================================================
Lab Section
We saved the path with a name.  We could also construct and save a path which generates an H.

We can overlay them simply by creating a boxed list with Link (;).
)
H =: bk 2 fd 1 rt 90 fd 2 lt 90 fd 1 bk 2  NB.  Construct H
'b' show H
NB.  Over lay them in the 'c' window.
'c' show H;T

NB. =========================================================
Lab Section Drawing a square
Now draw a square before moving to the next section.
)

NB. =========================================================
Lab Section Repeating sequences
The sequence 

    show fd 1 rt 90 fd 1 rt 90 fd 1 rt 90 fd 1 rt 90

draws a square with the turtle back in its initial position.  
The diagram was built up from 4 repetitions of the sequence 
    fd 1 rt 90
so we add a repeat command

    show repeat 4 fd 1 rt 90

The right argument of repeat specifies the number of repetitions followed by the path steps to be repeated.

NOTE:  In Logo you would enter  repeat 4 [fd 1 rt 90] but 
the brackets have a different meaning in J and must not
be used in JTurtle.  Parentheses around the whole repeat expression are often useful to restrict the expression repeated.
)

   show repeat 4 fd 1 rt 90

NB. =========================================================
Lab Section Regular Polygons
The verb repeat can be used to construct any regular polygon.

It can also be used to repeat any path even if of irregular shape.

Try
)
   'a' show tri  =: repeat 3 fd 1 rt 120     NB.  A triangle
    show sq   =: repeat 4 fd 1 rt 90
    'b' show pent =: repeat 5 fd 1 rt 72      NB.  A pentagon
    'c' show hex  =: repeat 6 fd 1 rt 60      NB.  hexagon
    show sep  =: repeat 7 fd 1 rt 360%7   NB.  septagon
    show oct  =: repeat 8 fd 1 rt 45      NB.  octagon
NB. to over lay them
    show tri;sq;pent;hex;sep;oct

NB. =========================================================
Lab Section
The example in Section 3

show repeat 20,(repeat 5 fd 1 rt 72) rt 18

is based on repeating a pentagon followed by a turn of 18 degrees.

Try some similar actions for a hexagon or other regular figure.
)
'a' show repeat 18 , (repeat 6 fd 1 rt 60) rt 20
'b' show repeat 20 , (repeat 6 fd 1 rt 60) rt 18

NB. =========================================================
Lab Section Squares
The verb square is a path verb which constructs a square with its side given by the argument and returns the turtle to the starting position.
)
show square 1 square 2 square 3

NB. =========================================================
Lab Section
You can also display paths represented by an array.  This enables use of J's rank conjunction.  The expression "0 (read as Rank 0) specifies that the verb is to be applied to each scalar in the list.
)
show square "0 (1 2 3 4 5 6 7 8 9 10)

NB. =========================================================
Lab Section Good style in path expressions
It is often regarded as 'good style' to construct path elements which lead to a natural repetion.  For example construct a shelter of inverted U shape with the turtle facing north and on the opposite leg to its starting position with
)
  show shelter =: fd 10 rt 90 fd 5 rt 90 fd 10 rt 180

NB. =========================================================
Lab Section Saving paths as nouns
Note how naturally we can now generate repetitions of the shape.  

The name shelter represents a noun.  Note the comma to join the two nouns, the number of repetitions and the turtle path in the right argument.
)
show repeat 5 , shelter

NB. =========================================================
Lab Section Repeat as a component within a repeat
If you want to repeat a more complex path you may need to use parentheses. Again note the comma to join the nouns.

The following generates a clock face.
)
 show repeat 12  rt 30 fd 1 ,(repeat 3 fd 1 rt 120) fd 2

NB. =========================================================
Lab Section Penup and pendown
When using the set commands it is often useful to stop drawing and reposition the pen before drawing starts.  We do this using penup and pendown.
)
showf   penup setxy 30 30 pendown square 20

NB.  Use showf above because it does not rescale the diagram
NB.  and it preserves the position of the origin showing the 
NB.  movement clearly

NB. =========================================================
Lab Section
Penup and pendown are defined as path verbs.  They change the character of the path drawing, but change neither position nor heading.  When the pen is up the path still exists, but is not drawn.

You can abbreviate penup as pu  and pendown as pd.  

Note the use of pd conflicts with use of a different verb  pd  in the 'plot' package of J so that cannot be used at the same time as JTurtle unless you enter erase_jturtle_ 'pd' and use the full form pendown.
)

NB. =========================================================
Lab Section Varying features of the drawings (1 of 3) (2 of 3) (3 of 3)
The ability to control the pen provides a way of drawing spaced identical objects.

penup and pendown are verbs and if at the end of an expression must have an empty argument, hence use  penup''  or  pendown''.
)
show repeat 4 pendown square 1 pu fd 2 rt 90 fd 2 lt 90

NB. =========================================================
Lab Section Varying features of the drawings 
In printed diagrams you may not want to show the turtle.  The turtle display is controlled by a global variable and can be changed by the functions

     showturtle''
     hideturtle''

They can be abbreviated to  st and ht.

They can be used in a path but only affect the display of the turtle in the final diagram.

To control the colour of the turtle path use

     color  rgb

A range of colours are available as standard isigraph global nouns e.g. RED, BLUE, GREEN etc.
)

NB. =========================================================
Lab Section
In the Chapter 2 we will explore ways of defining new verbs.  In Chapter 3 you will learn more about varying features of the drawings, including the line color, fill color, line types and  coloring shapes.  Chapter 4 will introduce Boxed objects and a range of ideas for placing multiple shapes on a diagram. It will also illustrate recursion and draw some fractal shapes. Chapter 5 will give more examples including using some geometric forms.
)

NB. =========================================================
Lab Chapter Adding New Functions
NB. =========================================================
Lab Section Path Functions
In addition to the standard function definition in J there is a special form to simplify adding path components.

The verb 'to'  constructs verbs to define components which can be included in turtle paths.  It behaves very similar to the Logo command  TO  but does not need the colon to define variables and uses quotes to separate its parts.  

The conjunction  'of'  from the script fndef.ijs is also used.

If you are constructing new verbs it is best to use a script window for the definitions and use the Run menu or its key equivalents for testing.
)
PREPARE
load '~system\packages\misc\jturtle.ijs'
PREPARE

NB. =========================================================
Lab Section Writing new functions with one argument
Using 'to' to define path verbs.

Suppose we want a component which is a square of side length 'side' which we can add to a path.  In Logo the following would define a function to draw a square
   
    to mysquare :side
    repeat 4 [fd :side rt 90]
    end

In J turtle we define the function  mysquare as follows:

    to 'mysquare side';'repeat 4 fd side rt 90'

The first component in quotes following the to  gives the function name and its arguments.  If you list more than one argument the the verb will use that number of items from the right argument to define the action of the verb. 

The second component specifies the path actions to be taken.
The two components must be linked by a semicolon.

Compared with Logo, the first line is reproduced with quotes around the function name and the arguments.  The body of the definition is in quotes following the semicolon.  Neither the brackets nor colon are needed.
)

NB. =========================================================
Lab Section
Execution of this function will add a verb  mysquare  to the current locale and enable you to incorporate it in turtle paths.  

    show mysquare 2 fd 4 mysquare 2 fd 4 mysquare 2

Define mysquare using the line from the previous section, and enter an expression like that above which uses it in a path.

Then add penup and pendown commands to separate the squares.
)

NB. =========================================================
Lab Section Using the new verb
Verbs defined with  to  can be included in further path verbs. To rotate a square we can define
    to 'rsquare s';'rt 45 mysquare s lt 45'
    'rotsq'  show rsquare 2

To have a square with its centre on the x-axis we can translate the start point with locsq which uses setxy

 to 'locsq side';'penup setxy(0.5*1 1 *-side)pendown''''' 

Note the double quotes needed to put a quote in a string for the empty argument of pendown. 

    to 'tsquare side';'locsq side mysquare side'
    show tsquare 1 tsquare 2 tsquare 3 tsquare 4

Execute these J sentences.

Use each to generate a set of translated squares.
)
PREPARE
    to 'mysquare side';'repeat 4 fd side rt 90'
    to 'rsquare s';'rt 45 mysquare s lt 45'
    to 'locsq side';'penup setxy(0.5*1 1*- side)pendown'''''
    to 'tsquare side';'locsq side mysquare side'
    'rsquare' show rsquare 2
PREPARE
    show repeat 4  mysquare 1 fd 4 rt 90

NB. =========================================================
Lab Section Verbs with two or more arguments
A rectangle is defined by the lengths of two sides.  We could define a rectangle function and use it to construct a diagram.

Note how the two parameters in the argument are entered as a vector
)
to 'rect s1 s2';'repeat 2 fd s1 rt 90 fd s2 rt 90'
show rect 2 4 penup fd 4 rt 90 fd 4 lt 90 pendown rect 4 2

NB. =========================================================
Lab Section Verbs with control structures
The 'to' form of path function definition used above handles simple path components.  In general it does not permit conditional steps within the path.  For more complex definitions including those which use J control structures see Chapter 4 Section 5.
)

NB. =========================================================
Lab Section A string argument for show
Using a string argument for show.

The show verbs will also accept a string argument or a noun consisting of a series of path verbs. If you define triangle with
)
triangle =: noun define
fd 3 
rt 120
fd 3
rt 120
fd 3 
rt 120
)

NB.  then you can display it with

show triangle

NB. =========================================================
Lab Section
When a string argument is used it is executed before the show command is called.

The repeat verb also permits a string argument but since it then has a number and string as arguments they must be Lined with a semicolon.
)
show repeat 4 ;'fd 3 rt 90'

NB. =========================================================
Lab Section
This permits some very interesting forms of repetition since you can change a variable within the expression. 

The example sets a value of a variable x and the second line  generates a show command which modifies that value during execution.
)
x =: 0
show repeat 40 ;'fd (x=:x+1) rt 90'

NB. =========================================================
Lab Section Paths using J features
Path verbs can also often be used with the each conjunction
)
show tsquare each i.5

NB. =========================================================
Lab Section
To create a regular polygon we need to know the number of repetions required for a given angle.  If it is not a divisor of 360 it is the result of the LCM of 360 and the angle, divided by the angle.  We round to ensure an integer result.

We use the  'of'  form of function definition for the number of repetitions because we do not want a path function, but just a number returned.  

The following illustrate the steps.
)
repetitions =: function of 'angle'
roundint (360 *. angle) % angle
)

to 'poly side deg';'repeat(repetitions deg) fd side rt deg'

show poly 1 72

NB. =========================================================
Lab Section
You get more interesting shapes when the angle is not a divisor of 360
)
'a' show poly 1 144
'b' show poly 1 75

NB. =========================================================
Lab Section Summary on movements
You have now completed the first steps toward using turtle geometry.  You can move the turtle to anywhere on your screen,  and have it heading in any desired direction.  You can also repeat sequences of steps to generate patterns and define new functions.
)

NB. =========================================================
Lab Section Saving graphs
To save a graph it is usually easiest to save it to a file.  Use a file name of type  .wmf  in windows.

   save 'c:\temp\mydiagram.wmf'

will save the file as a windows metafile in your temp directory.  You can only use this command once with a graph.

To save to the clipboard use

   clip''

BUT the available gl2 commands invert the diagram so this is only satisfactory for diagrams with reflective symmetry about a horizontal line.
)

NB. =========================================================
Lab Section Multiple plots on the same graph
In Logo turtle the  penup  and  pendown  commands are used to begin and start separate plots. In JTurtle boxed paths are plotted on the same graph.  Each item is separately initialised at the origin with heading 0.  See Chapter 4 for other alternatives to using penup and pendown and setxy in each path.

   show(square 2);(square 4);poly 1 72
)
PREPARE
  show(square 2);(square 4);poly 1 72

PREPARE

NB. =========================================================
Lab Chapter Color and other Graphics Controls
NB. =========================================================
Lab Section Color
To change color use the color verb in a path.

You can specify any rgb comination, using three integers up to 255 as the argument for this path verb.

Standard isigraph colors are available as RED, GREEN, BLUE, TEAL, AQUA, YELLOW, WHITE, BLACK
)
PREPARE
load '~system\packages\misc\jturtle.ijs'
PREPARE
show fd 1 rt 90 color BLUE fd 1 rt 90 color GREEN fd 1 rt 90 color AQUA fd 1 rt 90

NB. =========================================================
Lab Section Lines and fill.
You can use lines or fill.

The fill verb will fill the figure created as a polygon on points drawn.  If there is overlap white space will occur. This can create interesting patterns.  Consider the perspective effect when the diagram 'vase' is enlarged.
)
'vase' show fill poly 1 138

NB. =========================================================
Lab Section
You can mix lines and fill with path verbs  line and fill.
)
show repeat 6 rt 60 fd 1 lt 30 fill poly 1 120  line rt 30 bk 1

NB. =========================================================
Lab Section glcall
You have access to the underlying gl2 functions provided with J.  The verb  glcall inserted in a path permits any of these functions which operates within the 'graph' utility to be used.

The right argument of glcall is a boxed list of two items.
The first item is the gl2 command.  The second is the path to be followed after the change associated with the glcall.
The example illustrates changing the pen size and line type.
)
  show repeat 6 rt 60 fd 1 lt 30 glcall 'glpen 3 2'; poly 1 120 glcall'glpen 0.5 0'; line rt 30 bk 1

NB. =========================================================
Lab Section Saving positions within a path
The function  xyh  entered in a path will record the (x,y) coordinates and the heading at the current position as a named variable.  The name is given as a string for the first boxed item in the argument, and the path to be followed from this point is the second.

After drawing the path below, displaying a1 yields

   a1
1 1.73205 60
)

show rt 30 fd 2 xyh 'a1';poly 1 120

NB. =========================================================
Lab Section position and heading at end of path
To find the values of xyh at the end of the path the verbs  

lastxy  and  lasth  

can be used.

Display  z which is an intermediate point and the results of lastxy and lasth.
)
 show(repeat 3 fd 1 rt 20 fd 2 rt 15 fd 3 rt 20 fd 1)xyh'z'; repeat 3 fd 4 rt 45

NB. =========================================================
Lab Chapter Repeating Shapes and Recursion
NB. =========================================================
Lab Section Repeating shapes
If we mix turtle geometry and cartesian coordinates we can generate complex diagrams very quickly.

Suppose we wish to place a graphic at each point on a grid.

J enables us to find the points on a grid with its Catalogue verb.  

To generate the points in a square with x and y in (1,2,3)
use the following
 
   {1 2 3;1 2 3

The start verb enables us to place a graphic at each of these points.  The following illustrates the steps
)
PREPARE
load '~system\packages\misc\jturtle.ijs'
PREPARE
{1 2 3;1 2 3
show ({1 2 3;1 2 3) start square 0.8

NB. =========================================================
Lab Section Repeating shapes - 2
Any list of shapes can be used.  The function start will repeat use of the shapes if it runs out. The example uses a single shape.
)
show ({1 2 3;1 2 3) start (rt 18 poly 0.5 144)

NB. =========================================================
Lab Section Repeating shapes - 3
Now use a list of shapes one of which is empty
)
show ({1 2 3 4 5;1 2 3 4 5 ) start (rt 18 poly 0.5 144);''

NB. =========================================================
Lab Section Repeating shapes - using complex numbers
Since complex numbers can be used to specify positions in the plane it is sometimes useful to use complex numbers and the startj  function which expects complex numbers in the left argument.

To generate a grid use an expression of the form

    , a j./ b

and perhaps take segments from it.

The following is an example
)
show  (23 {. ,a j./a =. i.10) startj  square 0.8

NB. =========================================================
Lab Section Recursive definitions
Recursion is a very powerful computing tool and easily applied in turtle geometry.  The following generates a simple tree structure.

It uses the extended form of definition using 'to'. In this form you enter the first part - verb name and argument names  and press Enter.  You then enter commands to generate the path steps required. 

You can enter any J commands you like.  The result of the commands must be the path steps which are to begin the turtle path.

The end of the definition is defined by a right parenthesis in the first position in a row.
)
NB.  tree0

to 'branch length level'
if. level = 0 do. i.0 return. end.
len2 =. 0.6* length
fd length,lt 45,(branch len2,level-1), rt 90,( branch len2,level-1),lt 45 bk length
)

'a' show branch 2 5

NB.  Compare    
'b' show branch 2 6

NB. =========================================================
Lab Section
The first row of the definition specifies how the recursion ends and returns an empty vector  (i.0) when it ends.

The second row provides an abbreviated expression for the new length at each level of branches.

The final row goes from the root of a branch out to the next level of branches and then back to the root again.
)

NB. =========================================================
Lab Section
Another famous recursive problem is drawing the space-filling curves due to Hilbert.  The functions are defined below.  Note these functions could be defined using the standard J verb definition procedures.
)
to 'lhilbert size level'
if. level = 0 do. i.0 return. end.  
lt 90 ,(rhilbert size,level-1), fd size rt 90 ,(lhilbert size,level-1), fd size, (lhilbert size,level-1), rt 90 fd size, (rhilbert size,level-1),lt 90
)

to 'rhilbert size level'
if. level = 0 do. i.0  return. end.
rt 90 ,(lhilbert size,level-1), fd size lt 90 ,(rhilbert size,level-1), fd size, (rhilbert size,level-1), lt 90 fd size, (lhilbert size,level-1),rt 90
)

show rhilbert 2 2

NB. =========================================================
Lab Section
You can compare a right handed and a left handed curve with

show lhilbert 2 2

show rhilbert 2 2

Notice that they form a reflection in a vertical axis.
Study the effect of varying the number of levels by increasing the last digit.
)
'a' show lhilbert 2 2

'b' show rhilbert 2 2

NB. =========================================================
Lab Section
The above has provided a very brief introduction but should have given the reader enough information to explore many of the concepts introduced in books like Abelson and diSessa.  Some further examples are in Chapter 5.
)

NB. =========================================================
Lab Section Using locales
J has capabilities for object oriented programming.  The functions are saved in a locale  'fjturtle'.  A locale can provide a complete execution environment including different turtle path objects.

To create two locales named a and b enter
)
a =: conew 'fjturtle'
b =: conew 'fjturtle'

NB. =========================================================
Lab Section
We can create objects in a locale by appending two underscores and the locale name.
)
triobject__a =: poly 1 120 poly 2 120 poly 3 120
sqobject__b  =: square 1 square 2 square 3

NB.  Now display one of these objects 

show__a  triobject__a

NB. =========================================================
Lab Section
Note that the graph window has a number.  That number is a reference to the locale which is maintained by the system.  It is unique for each instance of the locale.  We can change objects in the locale, or display objects from another locale.

Move the graph for b so you can see both graphs simultaneously.
)
NB.  To display an object from b in locale a

show__b  triobject__a

NB. =========================================================
Lab Section
We can display an object in  a  using locale  b at the same time as we display an object in b in locale a.
)
show__b  triobject__a

show__a  sqobject__b

NB. =========================================================
Lab Chapter Examples and Demos
NB. =========================================================
Lab Section Rectangular objects
For rectangular objects it is usually good programming style to have the turtle finish with the same heading as it started.  

Consider the following
)
PREPARE
load '~system\packages\misc\jturtle.ijs'
PREPARE
to 'rowsquare s';'square s rt 90 fd s lt 90'
to 'rowsquares n s';'(repeat n rowsquare s )lt 90 fd (n*s) rt 90 fd s'
to 'blocksquares r c s';'repeat r rowsquares c,s'
show blocksquares 3 4 6

NB. =========================================================
Lab Section Arrows
To add an arrow at the current turtle position enter

    arrow size
)
show repeat 4 fd 10 arrow 1 rt 90

NB. =========================================================
Lab Section
To make a solid arrow try the following
)
to 'solida s';'fill rt 150 fd s rt 120 fd s rt 120 fd s lt 30'
show repeat 4 fd 10 solida 1 rt 90

NB. =========================================================
Lab Section Arcs
To create an arc with a given radius and angle from the center of the circle use

    arcr  radius,degrees    for turning right
    arcl  radius,degrees    for turning left

Draw a radius, the arc and the radius back to the center of the circle.
)
show fd 10 rt 90 arcr 10 45 arrow 1 rt 90 fd 10

NB. =========================================================
Lab Section
This function enables us to draw a famous spiral based on the fibonacci sequence.
)
show  arcl "1  [ 1 1 2 3 5 8 13 21 ,.90

NB. =========================================================
Lab Section Some recursions
Consider a square where the turtle begins at the middle of the base, and finishes at the middle of the top.
)

to 'sqpart s';' fd s rt 90 fd (2*s) rt 90 fd s'
to 'recursivesq s';'lt 90 ,(repeat 3 sqpart s) lt 90'
show recursivesq 3

NB. =========================================================
Lab Section
It is now easy to construct many patterns
)
'a' show recursivesq "0] 1 1 1 1 1 1
'b' show b =: recursivesq "0] 1 2 3 4 5 4 3 2 1

NB.  Note the Shape of b
Shape b
NB.  convert b to a vector to represent a path
'c' show repeat 5 ,(,b) rt 72

NB. =========================================================
Lab Section Some recursions - the snowflake
To construct the snowflake curve we use two verbs, one for the sides and one to combine them.
)
to 'side size level'
if. level = 0
 do. fd size  return.
 else.
 s3 =. size%3
 lev1 =. level-1
 side(s3,lev1) lt 60 side(s3,lev1) rt 120 side (s3,lev1) lt 60 side(s3,lev1)
end.
)

to 'snowflake size level';'repeat 3 side size,level rt 120'
'a' show snowflake 3 2
'b' show snowflake 3 4

NB. =========================================================
Lab Section
The following example provides a pattern of variable sized checkerboard squares.  The result is displayed after you move to the next section.  It may take some time on slower machines.

You can view the script which generated this example after that section.
)

NB. =========================================================
Lab Section
)
NB.  Strips

to 'rect r c';'repeat 2 fd r rt 90 fd c rt 90'
to 'rv r c';'rect r ,c  pu fd r pendown'''''
RED =: 255 255 0   NB.  Orange and yellow
BLUE =: 255 155 0


NB.  Globals for size  

N =: 5
WINSIZE =: 250

k =: (1+%:5)%2



stack1 =: 3 : 0
g =. (rv "_1 y.)
h =. (color RED fill'' ),:color BLUE fill''
,((#g)$h),.g
:
(,x.),stack y.
)

stack2 =: 3 : 0
g =. (rv "_1 y.)
h =. (color BLUE fill'' ),:color RED fill''
,((#g)$h),.g
:
(,x.),stack y.
)

stackv1 =: 3 : 0
w1 =. 0{y.
w2 =. 1{y. 
((stack1 (([:,],.|.)>:i.N),.w1),pu line rt 90 fd w1 rt 90 fd (2*+/>:i.N) lt 180 pendown  stack2  (([:,],.|.)>:i.N),.w2),pu line rt 90 fd w2 rt 90 fd (2*+/>:i.N) lt 180 pendown '',2}.y.
: 
(,x.),stackv1 y.c =. ((<1)=0{"1 gp)#gp
)
stackv2 =: 3 : 0
w1 =. 0{y.
w2 =. 1{y. 
((stack2 (([:,],.|.)>:i.N),.w1),pu line rt 90 fd w1 rt 90 fd (2*+/>:i.N) lt 180 pendown  stack1  (([:,],.|.)>:i.N),.w2),pu line rt 90 fd w2 rt 90 fd (2*+/>:i.N) lt 180 pendown'',2}.y.
: 
(,x.),stackv2 y.
)
N1=: (N, 2) $(([:,],.|.)>:i.N)
NN=:  2*+/>:i.N

g1 =: , stackv1"1 ]N1
g2 =: , stackv2"1 ]N1=: (N, 2) $(([:,],.|.)>:i.N)
NB. g1221 =: g1,g2,pu line bk fd NN lt 90 fd (2*NN)rt 90 pendown ,g2,g1
NB. 17.42
show g1,g2, pu home  bk NN pendown , g2,g1

NB. =========================================================
Lab Chapter A Dictionary of JTurtle
NB. =========================================================
Lab Section Functions available in JTurtle
TURTLE GEOMETRY FUNCTIONS

All path verbs have a right argument which is 
a path, and for those below with x, y or d a
single number prior to the remaining path.

x and y represent distances, d degrees
p a path  and  s  a string n an integer

Synonyms are shown in parentheses at the right
of a line.


PATH VERBS
Basic Movements

fd x        Move turtle forward x   (forward)

bk x        Move turtle back x  (back)

rt d        turn turtle right d degrees  (right)

lt d        turn turtle left d degrees   (left)

repeat n    repeat the following path n times

Movements from current position
leaving heading unchanged

plusx x     move turtle in xdirection x

plusy x     move turtle in ydirection x

Setting position and heading
These change only the item specified

seth d      set heading from North d degrees
            positive values clockwise    (setheading)

sethm d     set heading from East d degrees
            positive values anticlockwise

setxy (x,y) set position (x,y)             (setpos)

setx  x     set position x leaving y unchanged

sety  y     set position y leaving x unchanged

home        set position to origin and heading North

Controls which act as path verbs

penup       set pen up  (pu)

pendown     set pen down  (pd)

color rgb   set color to values of rgb vector (3 items)

glcall s;p  apply a gl2 call at this point in path

xyh    s;p  save (x,y,h) at point on path

line        draw a line through points on path

fill        fill the polygon defined by points on path

showturtle  sets global to show turtle on graph  (st)

hideturtle  sets global to hide turtle on graph  (ht)


OTHER VERBS

turns d     Returns the number of repetitions to give
            a multiple of 360 degrees   (repetitions)

process p   process the path the assign any values set by
            xyh  calls or to find values of lastxy or lasth

lastxy ''   query last position of a path after calls to 
            either process or show a path

lasth''     query the last heading of a path after calls to 
            either process or show a path

start       use as  (x,y) start p  to place a path p with 
            starting position (x,y)  Used for boxed paths

startj      equivalent to start but start positions denoted 
            by a complex number  xjy

show        show a path.  Valid right arguments are
              an unboxed path (vector or array)
              a boxed path
              a list of boxed paths
              a character string whose execution generates
               a path
              a boxed character string or list of boxed
               character strings

            A right argument which is a name gives the 
            display form the name

showf       The same as show but with a window size fixed by
            WINSIZE

save f      save displayed graph with file name f
            (for windows use a full path name and type .wmf)

clip''      clip display to clipboard. (Note caution in Lab)

VERB DEFINITION  (See Lab for details)

to s;s      definition of simple path functions. 

to s        definition of conditional path functions.

of          definition for monadic and dyadic functions


GLOBALS

SHOWTURTLE =: 1

TS =: 0.12    NB.  Scale unit for turtles

COLOR =: RED

WINSIZE =: 200

TURTLECOLOR =: TEAL



Some Turtle Path Functions

square s   draw a square of side s

squarec s  draw a square of side s about the current
           position

circle r   draw a circle of radius r 

circlec r  draw a circle radius r about the current
           position 

poly s,d   draw a polygon with side length s and 
           exterior angle d

polyrd r,d draw an inscribed polygon with exterior angle
           d in a circle of radius r   Tangent at start
           position

polyrn r,n draw an inscribed polygon with n sides
           in a circle of radius r   Tangent at start
           position

arcr r,d   arc right on a circle radius r for d degrees

arcl r,d   arc left on a circle radius r for d degrees

arrow x    place an arrow length x on the path at the 
           current position

THIS ENDS A SECTION CONTAINING A DICTIONARY OF JTURTLE FUNCTIONS.  SCROLL BACK TO SEE IT.
)
PREPARE
load '~system\packages\misc\jturtle.ijs'
PREPARE
