sourcelib/Turtle.xtl
1⍝│ Turtle: turtle graphics as arrays (a standard library, built into
2⍝│ xetal). Import it with an alias of your choice: "t:" u_se< "Turtle".
3⍝│ A walk is a vector of turns in degrees, one before each step forward;
4⍝│ the turtle starts at the origin facing east (0 degrees, counting
5⍝│ anticlockwise). No turtle moves: the headings are a running sum of
6⍝│ the turns, the steps are their cosines and sines, and the positions
7⍝│ are running sums of the steps. Draw the points with []P_ATH.
8⍝│ Names with l: are exported; names with h: are private to this file.
9
10⍝│ Degrees as radians, a Float.
11ʰr̲adians ← { (f̲loat ⍵) × (p̲i @) ÷ 180 } ⍝ private
12
13⍝━━ Points of a walk
14
15⍝│ The points of a walk with steps of the given lengths, 2 rows (x over
16⍝│ y), starting at the origin: lengths ᵗw̲alk turns; a single length
17⍝│ serves every step. A walk of n turns gives n + 1 points.
18⍝│ >> "t:" u_se< "Turtle"
19⍝│ >> f_loor 0.5 + 2 t:w_alk 0 90 90
20⍝│ 0 2 2 0
21⍝│ 0 0 2 2
22ˡw̲alk ← { lengths turns →
23 h ← ʰr̲adians '+ s̲\ turns
24 xs ← 0 c̲at '+ s̲\ (f̲loat lengths) × c̲os h
25 ys ← 0 c̲at '+ s̲\ (f̲loat lengths) × s̲in h
26 (2 c̲at t̲ally xs) r̲eshape xs c̲at ys
27}
28
29⍝│ The points of a walk of unit steps: ᵗp̲oints turns.
30⍝│ >> "t:" u_se< "Turtle"
31⍝│ >> f_loor 0.5 + t:p_oints t:p_olygon 4
32⍝│ 0 0 -1 -1 0
33⍝│ 0 1 1 0 0
34ˡp̲oints ← { turns → 1 ˡw̲alk turns }
35
36⍝━━ Building walks
37
38⍝│ The walk w with t degrees more turned before its first step: how
39⍝│ pieces of a curve are joined (60 ᵗt̲urn w).
40⍝│ >> "t:" u_se< "Turtle"
41⍝│ >> 60 t:t_urn 0 120 120
42⍝│ 60 120 120
43ˡt̲urn ← { t w → (t + 1 t̲ake w) c̲at 1 d̲rop w }
44
45⍝│ A regular polygon of n sides, as a walk: n turns of 360 / n degrees,
46⍝│ so it closes where it began.
47⍝│ >> "t:" u_se< "Turtle"
48⍝│ >> t:p_olygon 4
49⍝│ 90.0 90.0 90.0 90.0
50ˡp̲olygon ← { n → n r̲eshape 360 ÷ n }