sourcedemos/langtons-ant/langtons-ant.xtl
1⍝!/usr/bin/env xetal
2⍝# Langton's ant: on a white cell it turns right, on a black cell
3⍝# left; it flips the cell and steps forward. From two rules comes
4⍝# chaos, and then, after about 10000 steps, a "highway" the ant
5⍝# builds forever. Here the ant is arrays: its position is a mask
6⍝# with a single 1, its direction a number; no indexing, no loops,
7⍝# just whole-array steps. Run it with "xetal run
8⍝# demos/langtons-ant/langtons-ant.xtl"; it prints the state's shape,
9⍝# the board drawn with characters (black, white, the ant), and how
10⍝# many cells are black. The live page runs it frame by frame and
11⍝# pauses when the highway forms:
12⍝# https://softwarewrighter.github.io/X_eTaL-demos/langtons-ant/
13
14⍝# The board's size and the number of steps.
15rows ← 21
16cols ← 21
17steps ← 400
18
19⍝## One step of the ant
20
21⍝# u:s_tep (b, a, d): the state is a tuple, the board (0 white, 1
22⍝# black), the ant's mask (1 where it stands), and its direction (0
23⍝# up, 1 right, 2 down, 3 left), taken apart by the pattern and given
24⍝# back as a new tuple (D7, landed); d is a plain scalar now, not a
25⍝# plane carrying the same number everywhere. cell looks up the color
26⍝# under the ant (the board times its mask, summed); turn is right
27⍝# (+1) on white, left (+3, that is -1) on black; flip turns the
28⍝# cell's color over where the mask is 1; dy, dx move the mask one
29⍝# row or column, by its new direction.
30ᵘs̲tep ← { (b, a, d) →
31 cell ← '+ r̲/ r̲avel a × b
32 turn ← (d + 1 + 2 × cell) m̲od 4
33 flip ← b + a × 1 − 2 × b
34 dy ← (1 × turn = 0) − 1 × turn = 2
35 dx ← (1 × turn = 3) − 1 × turn = 1
36 step ← dy o̲-₁ dx o̲-₂ a
37 (flip, step, turn)
38}
39⍝ -- end of the core ---------------------------------------------------
40
41⍝ Start: a white board, the ant in the middle facing up.
42row ← (o̲ffsets rows) 'l̲eft t̲able o̲ffsets cols
43col ← (o̲ffsets rows) 'r̲ight t̲able o̲ffsets cols
44b0 ← 0 × row
45a0 ← 1 × (row = rows d̲iv 2) ∧ col = cols d̲iv 2
46(b, a, d) ← steps 'ᵘs̲tep p̲ower (b0, a0, 0)
47s̲hape b
48
49⍝ The board after the steps: # black, . white, A the ant.
50((1 + b + 2 × a) m̲in 3) s̲elect ".#A"
51'+ r̲/ r̲avel b