From J Wiki
Jump to navigation Jump to search

Here we introduce a minimalistic implementation of turtle graphics -- much less ambitious than the Brian Schott's addon.

We can represent 2d coordinates with a complex number. And a list of these numbers can represent a turtle's path.

We can also represent an orientation as a complex number.

We can also support the traditional turtle "left-to-right" evaluation order by using conjunctions, instead of verbs, for our turtle commands. Here, we'll use a list of complex numbers representing the turtle path, except that the rightmost element will be the direction the turtle is facing.

F=: {{ (}:m),(_2{.m)+/ .*1 0,:n,1 }} NB. forward
L=: {{ (}:m),({:m)**^j.n*1r180p1  }} NB. left
R=: {{ (}:m),({:m)**^j.n*_1r180p1 }} NB. right

The m for these conjunctions would be the turtle data structure. The n would be the parameter for the command.

Thus, for example:

   plot }: 0 1 F 1 L 90 F 1 L 30 F 1 L 120 F 1 L 30 F 1

gives us a stick figure house TurtleHouse.png

Here, 0 1 set our initial turtle at the origin (0), facing right (1). We moved right 1 unit (F 1), turned left (L 90), moved up one unit (F 1), turned slightly left (F 30), moved up and to the left 1 unit (F 1), flipped over (L 120), moved down and to the left 1 unit (F 1), finished turning left, and moved down 1 unit (F 1). The "trick" here is that the x component of our "roof movement" is one half of a unit

   {: 0 1 F 1 L 90 F 1 L 30

Also, a left turn of 30 + 120 + 30 degrees gives us a 180 degree rotation.

And this kind of mathematical stunt -- where we carefully pick values so that they have nice properties in the resulting image -- is characteristic of turtle graphics.

Similarly, here's a "star":

  plot}:{{ y F 9 R 144 }}^:5(0 1)


Note that because we are using 'plot' and because of our simplistic approach, we don't have penup/pendown nor color commands. We just have a minimalistic set of turtle commands which let us extend turtle "curves". Also, be aware that plot will not let us draw a horizontal line by itself in this fashion unless that line is above or below the x axis (because, in its current revision, plot does not recognize complex numbers when there are no complex values present).

TODO: go further