Langton's ant: Difference between revisions
Content deleted Content added
m →{{header|Uiua}}: Upscaled image |
|||
(48 intermediate revisions by 22 users not shown) | |||
Line 28:
;Related task:
*
* [[Elementary_cellular_automaton|Elementary cellular automaton]]
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">T.enum Dir
UP
RIGHT
DOWN
LEFT
-V color_WHITE = Char(‘ ’)
-V color_BLACK = Char(‘#’)
F invert_color(&grid, x, y)
‘Invert the color of grid at x, y coordinate.’
I grid[y][x] == :color_BLACK
grid[y][x] = :color_WHITE
E
grid[y][x] = :color_BLACK
F next_direction(grid, x, y, =direction)
‘Compute next direction according to current position and direction.’
V turn_right = grid[y][x] != :color_BLACK
V direction_index = Int(direction)
I turn_right
direction_index = (direction_index + 1) % 4
E
direction_index = (direction_index + 4 - 1) % 4
V directions = [Dir.UP, Dir.RIGHT, Dir.DOWN, Dir.LEFT]
direction = directions[direction_index]
R direction
F next_position(=x, =y, direction)
‘Compute next position according to direction.’
I direction == UP
y--
E I direction == RIGHT
x--
E I direction == DOWN
y++
E I direction == LEFT
x++
R (x, y)
F print_grid(grid)
‘Display grid.’
print(80 * ‘#’)
print(grid.map(row -> row.join(‘’)).join("\n"))
F ant(width, height, max_nb_steps)
‘Langton's ant.’
V grid = [[:color_WHITE] * width] * height
V x = width I/ 2
V y = height I/ 2
V direction = Dir.UP
V i = 0
L i < max_nb_steps & x C 0 .< width & y C 0 .< height
invert_color(&grid, x, y)
direction = next_direction(grid, x, y, direction)
(x, y) = next_position(x, y, direction)
i++
print_grid(grid)
ant(width' 75, height' 52, max_nb_steps' 12000)</syntaxhighlight>
{{out}}
<pre>
################################################################################
## ############ ##
# #### # ##
### ## ## #
# # # # # #
## ## # # ### #
### # # # # ## ## ###
# # ### ## #### ## # # # ## ##
# ### ## # ## ### # # ### ###
# # ##### # # #### # ### # # #
### ## # #### ## ## ###### # ### # #
# ### # ## # # ## ## ## # ##### ### ##
# # # ## ### # # # #### # ##
# # ## ## # ## ## # ##
### # # ## ### # ## # ### ## ## #
# ### ## ## ## ### # # ## #### #
### # # # # # #### ## # ## ### # #
# ### # ## # # ### # ### ## # # ##
### # # ## # ## ## ##### #### #### ## #
# ### # # # # ### # # ## ## # # # # #
### # ## ### ## # ## #### #### # #
# ### # # # ## ########### # #### # # #
### # ## # #### ## ######### # ## # ##
# ### # # ## # ## ## ## ### ### # # ## #### #
### # ## # # ###### ## # ## # # ### ### ## #
# ### # # # ##### # ##### # # ## # ## #
### # ## # # ## ##### ## # # # # ## # # #
# ### # # # # #### # ##### ## ########## ##
### # ## # ## ## # # #### # ## #### ##
# ### # # ##### # ## ## # # # # # # # #
### # ## ## ## # # # ## ## # # ## # ## ##
# ### # # # # # ######## # # ## #### #
### # ## # # # ## ## # # ## #
## # # # # # # ## ## ## ####
## # ## ## # ## ## # # ###
# # # # # ## #### #### ### ####
#### ## ## #### ## # ## # # #
# ## # ## ## ## ### ## #####
#### # ## # ####
## ## ## ##
##
# ## #### #
# # ### ###
# ## # # #
## ##
##
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE DIRN="0"
DEFINE DIRE="1"
DEFINE DIRS="2"
DEFINE DIRW="3"
DEFINE BLACK="1"
DEFINE WHITE="2"
DEFINE MAXX="159"
DEFINE MAXY="95"
BYTE FUNC TurnLeft(BYTE dir)
IF dir=DIRN THEN
RETURN (DIRW)
FI
RETURN (dir-1)
BYTE FUNC TurnRight(BYTE dir)
IF dir=DIRW THEN
RETURN (DIRN)
FI
RETURN (dir+1)
PROC DrawAnt(INT x,y)
BYTE c,dir
dir=DIRN
DO
c=Locate(x,y)
IF c=BLACK THEN
Color=WHITE
Plot(x,y)
dir=TurnLeft(dir)
ELSE
Color=BLACK
Plot(x,y)
dir=TurnRight(dir)
FI
IF dir=DIRN THEN
y==-1
IF y<0 THEN EXIT FI
ELSEIF dir=DIRE THEN
x==+1
IF X>MAXX THEN EXIT FI
ELSEIF dir=DIRS THEN
y==+1
IF Y>MAXY THEN EXIT FI
ELSE
x==-1
IF x<0 THEN EXIT FI
FI
OD
RETURN
PROC Main()
BYTE CH=$02FC
BYTE y
Graphics(7+16)
SetColor(0,0,2)
SetColor(1,0,12)
Color=2
FOR y=0 TO MAXY
DO
Plot(0,y) DrawTo(MAXX,y)
OD
DrawAnt(80,48)
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Langton's_ant.png Screenshot from Atari 8-bit computer]
=={{header|Ada}}==
<
procedure Langtons_Ant is
Line 88 ⟶ 285:
Ada.Text_IO.Put_Line("# Iteration:" & Integer'Image(Iteration));
end Langtons_Ant;
</syntaxhighlight>
Ouptut (to save space, I have removed the all-blank lines):
<pre style="height:30ex;overflow:scroll"> ## ############ ##
Line 146 ⟶ 343:
=={{header|Aime}}==
[[File:ant_phpoFTAAk.png|100px|Output png]]
<
ant(integer x, y, d, list map)
{
Line 178 ⟶ 375:
0;
}</
=={{header|ALGOL 68}}==
<
# size of board for Langton's ant #
INT max board = 100;
Line 247 ⟶ 444:
print( ( board[ r, min col : max col ], newline ) )
OD
END</
{{out}}
<pre>
Line 303 ⟶ 500:
##
</pre>
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">
⍝ initialize a Langton's Ant setup with a grid of size left x right (square by default)
langton ← {
⍝ If rows not specified, set equal to columns
⍺ ← ⍵
⍝ 0=white, 1=black. Start with all white
grid ← ⍺ ⍵ ⍴ 0
⍝ Start the ant in the middle
ant ← 2 ÷⍨ ⍺ ⍵
⍝ Aimed in a random direction
dir ← ?4
⍝ return everything in a tuple
grid ant dir
}
⍝ iterate one step: takes and returns state as created by langton function
step ← {
grid ant dir ← ⍵
⍝ Turn left or right based on grid cell
dir ← 1 + 4|dir+2×grid[⊂ant]
⍝ Toggle cell color
grid[⊂ant] ← 1 - grid[⊂ant]
⍝ Advance along dir. Since coordinates are matrix order (row,col),
⍝ up is -1 0, right is 0 1, down is 1 0, and left is 0 -1
ant +← (4 2 ⍴ ¯1 0, 0 1, 1 0, 0 ¯1)[dir;]
grid ant dir
}
⍝ to watch it run, open the variable pic in the monitor before executing this step
{} { state ∘← ⍵ ⋄ pic ∘← '.⌺'[1+⊃1⌷⍵] ⋄ _←⎕dl ÷200 ⋄ step ⍵} ⍣≡ langton 100</syntaxhighlight>
{{Out}}
The final contents of <tt>pic</tt> (eliding trailing blank lines)
<pre>.......................⌺⌺.⌺.⌺.......................................................................
......................⌺.⌺⌺⌺.⌺⌺......................................................................
.....................⌺⌺⌺⌺...⌺.⌺.....................................................................
.....................⌺⌺⌺⌺⌺.⌺..⌺⌺....................................................................
......................⌺...⌺⌺.⌺⌺.⌺...................................................................
.......................⌺⌺⌺...⌺..⌺⌺..................................................................
........................⌺...⌺⌺.⌺⌺.⌺.................................................................
.........................⌺⌺⌺...⌺..⌺⌺................................................................
..........................⌺...⌺⌺.⌺⌺.⌺...............................................................
...........................⌺⌺⌺...⌺..⌺⌺..............................................................
............................⌺...⌺⌺.⌺⌺.⌺.............................................................
.............................⌺⌺⌺...⌺..⌺⌺............................................................
..............................⌺...⌺⌺.⌺⌺.⌺...........................................................
...............................⌺⌺⌺...⌺..⌺⌺..........................................................
................................⌺...⌺⌺.⌺⌺.⌺.........................................................
.................................⌺⌺⌺...⌺..⌺⌺........................................................
..................................⌺...⌺⌺.⌺⌺.⌺.......................................................
...................................⌺⌺⌺...⌺..⌺⌺......................................................
....................................⌺...⌺⌺.⌺⌺.⌺.....................................................
.....................................⌺⌺⌺...⌺..⌺⌺....................................................
......................................⌺...⌺⌺.⌺⌺.⌺...................................................
.......................................⌺⌺⌺...⌺..⌺⌺..................................................
........................................⌺...⌺⌺.⌺⌺.⌺.................................................
.........................................⌺⌺⌺...⌺..⌺⌺................................................
..........................................⌺...⌺⌺.⌺⌺.⌺...............................................
...........................................⌺⌺⌺...⌺..⌺⌺..............................................
............................................⌺...⌺⌺.⌺⌺.⌺.............................................
.............................................⌺⌺⌺...⌺..⌺⌺............................................
..............................................⌺...⌺⌺.⌺⌺.⌺...........................................
...............................................⌺⌺⌺...⌺..⌺⌺..........................................
................................................⌺...⌺⌺.⌺⌺.⌺..⌺⌺.....................................
.................................................⌺⌺⌺...⌺..⌺⌺..⌺⌺....................................
..................................................⌺...⌺⌺.⌺⌺..⌺⌺...⌺.................................
............................................⌺⌺⌺⌺...⌺⌺⌺...⌺...⌺..⌺⌺⌺.................................
...........................................⌺....⌺...⌺...⌺⌺.⌺⌺⌺⌺...⌺.................................
..........................................⌺⌺⌺....⌺...⌺.⌺......⌺.⌺⌺.⌺................................
..........................................⌺⌺⌺....⌺.⌺⌺.....⌺.⌺⌺..⌺.⌺⌺................................
...........................................⌺....⌺...⌺⌺.⌺.⌺.....⌺⌺...................................
...........................................⌺.⌺......⌺.⌺⌺⌺⌺⌺..⌺...⌺..................................
..........................................⌺...⌺⌺⌺⌺⌺..........⌺⌺.⌺⌺⌺⌺⌺⌺..............................
..........................................⌺⌺⌺..⌺⌺..⌺.⌺⌺.⌺.⌺.⌺...⌺⌺.⌺.⌺⌺.............................
........................................⌺⌺..⌺.⌺⌺⌺⌺⌺⌺⌺.⌺...⌺..⌺⌺⌺....⌺⌺.⌺............................
.......................................⌺..⌺..⌺⌺⌺⌺⌺⌺.⌺⌺...⌺..⌺.⌺⌺...⌺...⌺............................
......................................⌺....⌺.⌺.⌺⌺.⌺..⌺⌺⌺⌺⌺⌺.⌺⌺⌺⌺⌺⌺⌺...⌺.............................
......................................⌺.⌺⌺⌺⌺.⌺⌺.⌺.⌺⌺⌺⌺....⌺⌺..⌺⌺.⌺.⌺⌺.⌺.............................
.......................................⌺....⌺⌺⌺⌺...⌺..⌺.⌺⌺⌺⌺⌺⌺.⌺⌺....⌺⌺⌺............................
..........................................⌺...⌺.⌺⌺.⌺.⌺⌺⌺.⌺..⌺⌺..⌺⌺...⌺⌺⌺............................
.............................................⌺⌺⌺⌺⌺⌺⌺....⌺..⌺⌺.⌺⌺.⌺.....⌺............................
.....................................⌺⌺⌺⌺..⌺⌺.⌺⌺..⌺⌺⌺⌺.⌺⌺.⌺⌺.⌺⌺..⌺.....⌺............................
....................................⌺....⌺.⌺...⌺⌺⌺.⌺⌺.⌺⌺⌺....⌺.⌺⌺⌺⌺....⌺............................
...................................⌺⌺⌺.......⌺⌺⌺.⌺.⌺.⌺⌺⌺⌺⌺....⌺.⌺......⌺............................
...................................⌺.⌺...⌺⌺⌺.⌺⌺⌺⌺.⌺⌺.⌺...⌺⌺.⌺⌺⌺.⌺⌺.....⌺............................
.........................................⌺⌺.⌺⌺..⌺⌺⌺⌺....⌺⌺⌺⌺.⌺.⌺.⌺.....⌺............................
....................................⌺....⌺..⌺⌺...⌺⌺⌺..⌺⌺⌺.....⌺⌺⌺......⌺............................
....................................⌺⌺...⌺⌺.⌺⌺⌺.⌺⌺⌺⌺..⌺......⌺⌺⌺...⌺⌺..⌺............................
....................................⌺⌺.⌺.⌺⌺⌺⌺.....⌺...⌺..⌺.⌺⌺.⌺⌺⌺.⌺⌺...⌺............................
...................................⌺⌺⌺⌺.⌺⌺...⌺⌺.⌺⌺⌺⌺..⌺.⌺..⌺..⌺..⌺⌺⌺...⌺............................
...................................⌺.⌺⌺.⌺⌺⌺..⌺.⌺.⌺⌺.⌺.⌺.....⌺.⌺.....⌺.⌺.............................
.......................................⌺.⌺..⌺....⌺⌺.⌺⌺..⌺.⌺..⌺⌺⌺.⌺⌺.................................
.......................................⌺⌺.⌺....⌺..⌺⌺⌺⌺⌺.⌺....⌺....⌺..⌺.⌺............................
......................................⌺.⌺⌺.⌺..⌺....⌺⌺.⌺⌺.⌺..⌺⌺⌺......⌺⌺⌺............................
....................................⌺.⌺...⌺..⌺..⌺..⌺..⌺⌺⌺...⌺⌺..⌺⌺....⌺.............................
...................................⌺⌺⌺.⌺.⌺⌺⌺⌺⌺.⌺⌺⌺⌺⌺⌺.⌺⌺⌺.⌺⌺⌺⌺⌺⌺⌺.⌺.⌺⌺..............................
...................................⌺.⌺.⌺....⌺⌺⌺⌺⌺...⌺⌺..⌺⌺⌺⌺⌺.⌺⌺⌺⌺⌺.................................
.....................................⌺..⌺⌺...⌺......⌺..⌺.⌺⌺..⌺⌺⌺.⌺⌺⌺................................
..................................⌺⌺⌺⌺...⌺⌺⌺⌺⌺.⌺⌺⌺⌺⌺⌺⌺⌺⌺...⌺.⌺......................................
.............................⌺⌺....⌺..⌺.....⌺⌺⌺.⌺.⌺...⌺.⌺⌺⌺..⌺⌺⌺....................................
............................⌺..⌺..⌺⌺⌺⌺.⌺⌺...⌺⌺⌺.⌺⌺...⌺⌺⌺.⌺⌺.....⌺⌺..................................
...........................⌺⌺⌺....⌺.⌺⌺.⌺.⌺⌺⌺⌺⌺...⌺....⌺..⌺..⌺⌺.⌺⌺⌺..................................
...........................⌺.⌺⌺⌺⌺⌺.⌺.⌺...⌺⌺..⌺⌺.....⌺....⌺...⌺..⌺...................................
...............................⌺⌺⌺⌺⌺⌺.⌺⌺⌺⌺..⌺⌺.⌺...⌺..⌺⌺..⌺.⌺.⌺⌺....................................
.............................⌺⌺......⌺.⌺⌺⌺.⌺⌺..⌺⌺⌺⌺...⌺...⌺⌺⌺.......................................
..............................⌺..⌺.⌺⌺⌺⌺⌺..⌺...⌺.⌺⌺...⌺..⌺..⌺........................................
..............................⌺⌺.⌺⌺⌺.⌺⌺⌺⌺⌺⌺⌺.....⌺.....⌺.⌺⌺.........................................
.............................⌺.⌺..⌺⌺.⌺⌺......⌺...⌺⌺....⌺............................................
............................⌺..⌺.⌺⌺⌺⌺........⌺⌺⌺..⌺⌺..⌺.............................................
............................⌺.⌺⌺.⌺⌺⌺............⌺⌺..⌺⌺..............................................
.............................⌺⌺.....................................................................
..............................⌺⌺....................................................................</pre>
=={{header|Applesoft BASIC}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="gwbasic"> 0 IF T THEN FOR Q = 0 TO T STEP 0: XDRAW T AT X * S,H - Y * S:D = FN M(D + D( PEEK (234)) + F):X = X + X(D):Y = Y + Y(D):Q = X > M OR X < 0 OR Y > M OR Y < 0: NEXT Q: END : DATA 100,50,50,3,220,1,4,-1,1,1,1,-1,-1
1 HGR : SCALE= 1: ROT= 0
2 LET S$ = CHR$ (1) + CHR$ (0) + CHR$ (4) + CHR$ (0) + "5'" + CHR$ (0)
3 POKE 236, PEEK (131): POKE 237, PEEK (132)
4 LET S = PEEK (236) + PEEK (237) * 256 + 1
5 POKE 232, PEEK (S)
6 POKE 233, PEEK (S + 1)
7 READ M,X,Y,S,H,T,F,D(0),D(4),Y(0),X(1),Y(2),X(3)
8 DEF FN M(N) = N - INT (N / F) * F
9 GOTO</syntaxhighlight>
=={{header|AutoHotkey}}==
ahk forum: [http://ahkscript.org/boards/viewtopic.php?f=17&t=1363 discussion]
{{works with|AutoHotkey 1.1}} (Fixed by just me)
<
SetBatchLines, -1
; Directions
Line 362 ⟶ 695:
HBM := DllCall("User32.dll\CopyImage", "Ptr", HBM, "UInt", 0, "Int", 0, "Int", 0, "Int", 8, "UPtr")
return DllCall("User32.dll\CopyImage", "Ptr", HBM, "UInt", 0, "Int", BMW, "Int", BMH, "UInt", 0x200C, "UPtr")
} ; http://ahkscript.org/boards/viewtopic.php?f=6&t=3203</
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
Global $iCountMax = 100000
Global $aFields[100][100][2]
Line 442 ⟶ 775:
Return 1
EndFunc ;==>_SetAnt
</syntaxhighlight>
[http://www.imgbox.de/users/BugFix/langtons_ant.png To see the GUI output, click here.]
--[[User:BugFix|BugFix]] ([[User talk:BugFix|talk]]) 14:48, 16 November 2013 (UTC)
=={{header|AWK}}==
<
# usage: awk -v debug=0 -f langton.awk
Line 541 ⟶ 874:
}
END { print("END.") }
</syntaxhighlight>
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbc basic">
REM Implementation of Langton's ant for Rosetta Code
fieldsize%=100
Line 566 ⟶ 899:
UNTIL x%>fieldsize% OR x%<0 OR y%>fieldsize% OR y%<0
END
</syntaxhighlight>
=={{header|bc}}==
The output function <code>o</code> prints the resulting image (as a [[wp:Netpbm_format|PBM image]]) to <code>stdout</code>. One can either store it into a file or pipe it through an image viewer (e.g. <code>bc langton.bc | display</code>).
<
auto i, j
Line 620 ⟶ 953:
l(100, 100, 50, 50)
quit</
=={{header|Befunge}}==
<
!"$(0@`vp00_^#!:p+7/"P"<<^g+7/*5"p"\%"P"/7::+g03*"d":_$,1+>:40g`!^1g03<
_::10g\v>00g+4%:00p::3\`\1-*50g+50p:2\-\0`*+::0\`\"c"`+50g:0\`\"c"`++#^
-*84g1<v^+1*2g09pg08g07-*g06-1*2p09:%2/g06:gp08:+7/*5"p"\p07:%"P"/7:p06
0p+:7%^>>-:0`!*+10p::20g\-:0`*+20p:"d"*50g::30g\-:0`!*+30p::40g\-:0`*+4</
{{out}}
Line 683 ⟶ 1,016:
####
##</pre>
=={{header|BQN}}==
<code>Ant</code> is the main function, which runs the ant simulation given a starting point, direction and grid of zeros.
<code>Fmt</code> then formats into hashes and spaces.
<code>_while_</code> is an idiom from [https://mlochbaum.github.io/bqncrate/ BQNcrate] which helps with conditional looping.
<syntaxhighlight lang="bqn">Rot ← ¬⊸{-⌾(𝕨⊸⊑)⌽𝕩}
Fmt ← ⊏⟜" #"
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
Ant ← 2⊑{ # Generator Block
p‿d‿g:
r ← d Rot˜ p⊑g
⟨
p + r
r
¬⌾(p⊸⊑)g
⟩
} _while_ { # Condition Block
p‿d‿g:
∧´(p≥0‿0)∧p<≢g
}
•Show Fmt Ant ⟨50‿50, 0‿1, 100‿100⥊0⟩</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=Um90IOKGkCDCrOKKuHst4oy+KPCdlajiirjiipEp4oy98J2VqX0KRm10IOKGkCDiio/in5wiICMiCl93aGlsZV8g4oaQIHvwnZS94o2f8J2UvuKImPCdlL1f8J2Vo1/wnZS+4oiY8J2UveKNn/CdlL7wnZWpfQoKQW50IOKGkCAy4oqReyAjIEdlbmVyYXRvciBCbG9jawogIHDigL9k4oC/ZzoKICByIOKGkCBkIFJvdMucIHDiipFnCiAg4p+oCiAgICBwICsgcgogICAgcgogICAgwqzijL4ocOKKuOKKkSlnCiAg4p+pCn0gX3doaWxlXyB7ICAgIyBDb25kaXRpb24gQmxvY2sKICBw4oC/ZOKAv2c6CiAg4oinwrQocOKJpTDigL8wKeKIp3A84omiZwp9CgrigKJTaG93IEZtdCBBbnQg4p+oNTDigL81MCwgMOKAvzEsIDEwMOKAvzEwMOKlijDin6k=&norun Try It!] (Running will take some time due to JS, ≈40 secs on my machine)
=={{header|C}}==
Requires ANSI terminal.
<
#include <stdlib.h>
#include <string.h>
Line 760 ⟶ 1,121:
walk();
return 0;
}</
=={{header|C sharp|C#}}==
<
namespace LangtonAnt
Line 856 ⟶ 1,217:
}
}
</syntaxhighlight>
Output:
<pre>
Line 945 ⟶ 1,306:
If you want to see it running infinitely, set the const bool INFINIT_RUN = true
<
#include <windows.h>
#include <string>
Line 1,244 ⟶ 1,605:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
=={{header|Chapel}}==
<
config const gridHeight: int = 100;
config const gridWidth: int = 100;
Line 1,316 ⟶ 1,677:
image.writeImage( "output.png" );
}
</syntaxhighlight>
=={{header|Clojure}}==
In keeping with the spirit of Clojure, this program eschews mutable state entirely. Instead, all computation occurs within a single recursive loop whose "variables" are "adjusted" at each iteration, a natural fit for this particular execution model.
<
xs [1 0 -1 0] ys [0 -1 0 1]]
(loop [dir 0 x 50 y 50
Line 1,333 ⟶ 1,694:
(apply str
(map #(if (grid [% col]) \# \.)
(range 100))))))))</
=={{header|COBOL}}==
The following program displays the simulation in the console, and a very small font size (~4pt) will be needed to fit it into the window.
{{works with|OpenCOBOL}}
<
PROGRAM-ID. langtons-ant.
Line 1,428 ⟶ 1,789:
WITH BACKGROUND-COLOR White-Background
END-PERFORM
.</
=={{header|CoffeeScript}}==
<
class Ant
constructor: (@world) ->
Line 1,511 ⟶ 1,872:
console.log "Ant is at #{ant.location}, direction #{ant.direction}"
world.draw()
</syntaxhighlight>
output
<syntaxhighlight lang="text">
> coffee langstons_ant.coffee
Ant is at -24,46, direction W
Line 1,596 ⟶ 1,957:
_____##_________________________________________
______##________________________________________
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(defun langtons-ant (width height start-x start-y start-dir)
Line 1,630 ⟶ 1,991:
(setf *random-state* (make-random-state t))
(show-grid (langtons-ant 100 100 (+ 45 (random 10)) (+ 45 (random 10)) (random 4)))</
=={{header|D}}==
===Textual Version===
<
import std.stdio, std.traits;
Line 1,659 ⟶ 2,020:
writefln("%(%-(%c%)\n%)", M);
}</
{{out}}
<pre>...........................................................................
Line 1,716 ⟶ 2,077:
===Image Version===
This similar version requires the module from the Grayscale Image Task to generate and save a PGM image.
<
void main() {
Line 1,740 ⟶ 2,101:
M.savePGM("langton_ant.pgm");
}</
=={{header|Dyalect}}==
<
func move(ant) {
ant
ant
}
func Array.
var ptCur = (var x
var leftTurn = this[ptCur
ant.direction =
if leftTurn {
leftTurns[ant
} else {
rightTurns[ant
}
this[ptCur
move(ant)
ptCur = (x
ant
ptCur
ptCur
ptCur
ptCur
ant
}
func newAnt(width, height) {
(
var position
var origin
)
}
func run() {
while !ant
blacks.
}
Line 1,819 ⟶ 2,180:
}
run()</
{{out}}
Line 1,908 ⟶ 2,269:
=={{header|EasyLang}}==
[https://easylang.dev/show/#cod=bZHLDoIwEEX3/Yq7VAlNa0wMifgjhIXhEUiUmopA/94ZKILBJn3k9M70zvReNCiTFFopHHgVT2syvCrTQ0IKAKWxcIih0BpEESNPhw2lUZeU0E3JEJAmgE5JqBcJjYfpCrpzP9AWWQu9Vkqx2qWQkzv7bjgWeW1nk/mQ8CMJ+dE0Q410xM7jUPubEfdVfefnr+z/1uR0vIx++ewW7CbsTXSUaVva3I+/NSNE5wVsNsaOtwBH0nZ76kKOE4u9hgJjLoVEc143IvdF3ASu/6xwUlCCf0p8AA== Run it]
<syntaxhighlight lang="text">
len f[] 100 * 100
proc show . .
rect 1 1
.
.
.
dx[] = [ 0 1 0 -1 ]
dy[] = [ -1 0 1 0 ]
while x >= 0 and x < 100 and y >= 0 and y < 100
v = f[y * 100 + x + 1]
f[y * 100 + x + 1] = 1 - v
dir = (dir
x += dx[dir]
y += dy[dir]
.
.
</syntaxhighlight>
=={{header|EchoLisp}}==
We implement multi-colored ants, as depicted in the article. An ant is described using L(eft)R(ight) patterns. LR is the basic black and white ant, other are RRLLLRRL or RRLLLRLLLRRR. See results for s [http://www.echolalie.org/echolisp/images/ant-1.png black-and-white] or [http://www.echolalie.org/echolisp/images/ant-2.png colored] ants.
<
(lib 'plot)
(lib 'types)
Line 1,997 ⟶ 2,360:
(ant) ;; run
</syntaxhighlight>
=={{header|Ela}}==
Line 2,003 ⟶ 2,366:
A straightforward implementation (assumes that we start with ant looking forward):
<
type Field = Field a
Line 2,053 ⟶ 2,416:
left Bwd = Rgt
left Rgt = Fwd
left Fwd = Lft</
This implementation is pure (doesn't produce side effects).
Line 2,059 ⟶ 2,422:
Testing:
<
Output (empty lines are skipped to save space):
Line 2,119 ⟶ 2,482:
{{works with|Elixir|1.1+}}
{{trans|Ruby}}
<
def ant(sizex, sizey) do
{px, py} = {div(sizex,2), div(sizey,2)} # start position
Line 2,145 ⟶ 2,508:
end
Langtons.ant(100, 100)</
{{out}}
Line 2,254 ⟶ 2,617:
=={{header|Elm}}==
<
import Matrix
import Time exposing (Time, every, second)
Line 2,385 ⟶ 2,748:
, update = update
, subscriptions = subscriptions
}</
Link to live demo: https://dc25.github.io/langtonsAntElm/
Line 2,391 ⟶ 2,754:
=={{header|Erlang}}==
Over-engineered sine I have summer vacation. Ex: Display function only display lines with black cells.
<syntaxhighlight lang="erlang">
-module( langtons_ant ).
Line 2,504 ⟶ 2,867:
plane_create( Controller, Max_x, Max_y ) -> [{plane_create_cell(Controller, Max_x, Max_y, {X, Y}), {X,Y}} || X <- lists:seq(1, Max_x), Y<- lists:seq(1, Max_y)].
plane_create_cell( Controller, Max_x, Max_y, Position ) -> erlang:spawn_link( fun() -> loop( #state{controller=Controller, max_x=Max_x, max_y=Max_y, position=Position} ) end ).
</syntaxhighlight>
{{out}}
Line 2,591 ⟶ 2,954:
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.3, 4.0.0 RC1 and later}}
<
include std\graphics.e
Line 2,655 ⟶ 3,018:
printf(1,"\n%d Iterations\n",iterations)
any_key()--wait for keypress, put default message 'press any key..'</
Code needed to run SDL example with Mark Akita's SDL_gfx_Test1.exw (as template) included with his SDL_gfx package from rapideuphoria.com's archive -
In initialization section :<
sequence grid = repeat(repeat(1,100),100) --fill 100 by 100 grid with white (1)
sequence antData = {48, 53, 360} --x coordinate, y coordinate, facing angle</
In main() , after keystate=SDL_GetKeyState(NULL) , you can adapt the program above to draw the ant's step each frame.
Use dummy=pixelColor(surface,x+20,y+12,#000000FF) (for example) to replace the text output.
Just before the close of the while loop, use dummy=pixelColor(surface,antData[1]+20,antData[2]+12,#FF0000FF) for the ant
and SDL_UpdateRect(surface,0,0,0,0) to display the graphic.
=={{header|F Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Langton's ant F# https://rosettacode.org/wiki/Langton%27s_ant
// A list of cells which are black is maintained and then printed out at the end
type Cell = { X : int; Y : int }
type Direction = | North | South | East| West // direction the ant is facing
let withinBounds (dim:int) (cell: Cell) = // ant's cell within dimensions ?
cell.X < dim && cell.Y < dim && cell.X >= 0 && cell.Y >= 0
let rotateLeft (currentDirection: Direction) =
match currentDirection with
| North -> West | South -> East | East -> North | West -> South
let rotateRight (currentDirection: Direction ) =
match currentDirection with
| North -> East | South -> West | East -> South | West -> North
let nextCell (dir:Direction) (cell: Cell) = // compute next cell based on the direction
match dir with
| North -> {cell with Y = cell.Y + 1 }
| South -> {cell with Y = cell.Y - 1 }
| East -> {cell with X = cell.X + 1 }
| West -> {cell with X = cell.X - 1 }
let isBlackCell (blackCells: Cell list) (cell:Cell) =
blackCells |> List.exists ( fun c -> c = cell)
let toggleCellColor (blackCells: Cell list) (cell: Cell) =
if cell |> isBlackCell blackCells
then blackCells |> List.where( fun c -> c <> cell) // remove the cell from list of black cells
else cell::blackCells // add the cell to the list of black cells
let moveToCell (blackCells: Cell list) (currentDir : Direction) (cell: Cell) =
let ndir = if cell |> isBlackCell blackCells // next step direction is computed
then rotateLeft currentDir
else rotateRight currentDir
let nlst = cell |> toggleCellColor blackCells // next step updated list of black cells is computed
let ncell = cell |> nextCell ndir // next step cell is computedd
(nlst, ndir, ncell) // return next step list of black cells, direction it will enter the cell, new cell
let rec doStep (dim:int) (blackCells: Cell list) (dir : Direction) (cell: Cell) =
let (nlst, ndir, ncell) = moveToCell blackCells dir cell
if withinBounds dim ncell // check if the next step is within bounds
then doStep dim nlst ndir ncell // recursive call to next step
else nlst, ndir, ncell
[<EntryPoint>]
let main _ =
let dim = 100
let (blacklist, _, _) = doStep dim [] North { X = dim/2 ; Y = dim/2 } // start with empty blacklist, facing north in the center
// print out by row, 0th row is at the bottom
seq { for row in [dim-1..-1..0] do for col in [0..dim-1] -> (col,row) }
|> Seq.iter (fun (row,col) -> if {X = row; Y = col } |> isBlackCell blacklist
then printf "#" else printf " "
if row = (dim - 1 )
then printf "\n" else ()
)
0
</syntaxhighlight>
<pre>
## ############ ##
# #### # ##
### ## ## #
# # # # # #
## ## # # ### #
### # # # # ## ## ###
# # ### ## #### ## # # # ## ##
# ### ## # ## ### # # ### ###
# # ##### # # #### # ### # # #
### ## # #### ## ## ###### # ### # #
# ### # ## # # ## ## ## # ##### ### ##
# # # ## ### # # # #### # ##
# # ## ## # ## ## # ##
### # # ## ### # ## # ### ## ## #
# ### ## ## ## ### # # ## #### #
### # # # # # #### ## # ## ### # #
# ### # ## # # ### # ### ## # # ##
### # # ## # ## ## ##### #### #### ## #
# ### # # # # ### # # ## ## # # # # #
### # ## ### ## # ## #### #### # #
# ### # # # ## ########### # #### # # #
### # ## # #### ## ######### # ## # ##
# ### # # ## # ## ## ## ### ### # # ## #### #
### # ## # # ###### ## # ## # # ### ### ## #
# ### # # # ##### # ##### # # ## # ## #
### # ## # # ## ##### ## # # # # ## # # #
# ### # # # # #### # ##### ## ########## ##
### # ## # ## ## # # #### # ## #### ##
# ### # # ##### # ## ## # # # # # # # #
### # ## ## ## # # # ## ## # # ## # ## ##
# ### # # # # # ######## # # ## #### #
### # ## # # # ## ## # # ## #
# ### # # # # # # ## ## ## ####
### # ## ## # ## ## # # ###
# ### # # # ## #### #### ### ####
### # ## ## #### ## # ## # # #
# ### # # ## ## ## ### ## #####
### # ## # ## # ####
# ### # # ## ## ##
### # ## ##
# ### # # # ## #### #
### # ## # # ### ###
# ### # # # ## # # #
### # ## ## ##
# ### # # ##
### # ##
# # # # #
#### ##
# ## #
####
##
</pre>
=={{header|Fantom}}==
<
class World
{
Line 2,798 ⟶ 3,285:
}
}
</syntaxhighlight>
Output (snipping the blank lines):
Line 2,859 ⟶ 3,346:
{{works with|GNU Forth|0.7.0}}
All array manipulations were taken from Rosetta Code examples.
<
1 0 0 0 \ pushes orientation of the ant to the stack.
Line 2,926 ⟶ 3,413:
: langton.ant run.ant draw.grid ; \ launches the ant, outputs the result
</
{{out}}
<pre style="height:60ex;overflow:scroll">
Line 3,013 ⟶ 3,500:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 3,060 ⟶ 3,547:
write(*,*)
end do
end program</
{{out}} (Cropped to save space)
<pre style="height:60ex;overflow:scroll">
Line 3,120 ⟶ 3,607:
===But, if one remembers complex numbers===
<syntaxhighlight lang="fortran">
PROGRAM LANGTONSANT
C Langton's ant wanders across an initially all-white board, stepping one cell at a go.
Line 3,167 ⟶ 3,654:
Completed.
END
</syntaxhighlight>
Output is the same, except for orientation. Here I have stuck to (x,y) Cartesian orientation rather than lines (y) increasing downwards. Just for fun, + signs mark cells that have been trampled and then cleaned. But not to pure white... Notice that some interior cells have never been trampled.
Line 3,256 ⟶ 3,743:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s gui
Line 3,320 ⟶ 3,807:
'Print : Print "hit any key to end program"
Sleep
End</
=={{header|Furor}}==
<syntaxhighlight lang="furor">
###sysinclude X.uh
$ff0000 sto szin1
$ffffff sto szin2
2 sto pausetime
maxypixel 100 - sto YRES
maxxpixel sto XRES
zero ant
// Az ant iránykódjai:
// 0 : fel
// 1 : le
// 2 : jobbra
// 3 : balra
@XRES 2 / sto antx // Az ant kezdeti koordinátái
@YRES 2 / sto anty
myscreen "Furor monitor" @YRES @XRES graphic // Create the graphic screen
."Kilépés: ESC\n"
infiniteloop: {... // infinite loop begins
myscreen @anty @antx [[]][[]] // A pixel színe amin az ant ül épp
@szin2 == { myscreen @anty @antx @szin1 [][] // másik színre átállítjuk a pixelt
2 // Jobbra fog fordulni
}{ myscreen @anty @antx @szin2 [][] // másik színre átállítjuk a pixelt
3 // Balra fog fordulni
}
// Elvégezzük az új koordináta beállítását:
sto direction
@ant 0 == { @direction 2 == then §r1 @direction 3 == then §r2 }
@ant 2 == { @direction 2 == then §r3 @direction 3 == then §r4 }
@ant 1 == { @direction 3 == { r1: antx @XRES ring 2 goto §beolvas } @direction 2 == { r2: antx @XRES !ring 3 goto §beolvas } }
@ant 3 == { @direction 3 == { r3: anty @YRES !ring 1 goto §beolvas } @direction 2 == { r4: anty @YRES ring 0 goto §beolvas } }
beolvas: sto ant
myscreen key? sto! billkód @pausetime usleep $1b ==
|...}
."Made " {...}§infiniteloop print ." steps.\n"
."XRES = " @XRES printnl
."YRES = " @YRES printnl
myscreen !graphic
end
{ „myscreen” }
{ „billkód” }
{ „pausetime” }
{ „XRES” }
{ „YRES” }
{ „szin1” }
{ „szin2” }
{ „ant” }
{ „antx” }
{ „anty” }
{ „direction” }
</syntaxhighlight>
=={{header|Peri}}==
<syntaxhighlight lang="peri">
###sysinclude standard.uh
###sysinclude system.uh
###sysinclude str.uh
###sysinclude X.uh
#g
$ff0000 sto szin1
$ffffff sto szin2
10 sto pausetime
//maxypixel 100 - sto YRES
//maxypixel 20 - sto YRES
//maxypixel 7 - sto YRES
//maxypixel 13 - sto YRES
maxypixel 20 - sto YRES
maxxpixel sto XRES
zero ant
// Az ant iránykódjai:
// 0 : fel
// 1 : le
// 2 : jobbra
// 3 : balra
@XRES 2 / sto antx // Az ant kezdeti koordinátái
@YRES 2 / sto anty
myscreen "Furor monitor" @YRES @XRES graphic // Create the graphic screen
."Kilépés: ESC\n"
{.. // infinite loop begins
myscreen @anty @antx getpixel // A pixel színe amin az ant ül épp
@szin2 == {
myscreen @anty @antx @szin1 setpixel // másik színre átállítjuk a pixelt
2 // Jobbra fog fordulni
}{
myscreen @anty @antx @szin2 setpixel // másik színre átállítjuk a pixelt
3 // Balra fog fordulni
}
// Elvégezzük az új koordináta beállítását:
sto direction
@ant 0 == @direction 2 == & { ++() antx @antx @XRES == { zero antx } 2 sto ant goto §beolvas }
@ant 0 == @direction 3 == & { @antx inv { @XRES -- sto antx }{ --() antx } 3 sto ant goto §beolvas }
@ant 1 == @direction 3 == & { ++() antx @antx @XRES == { zero antx } 2 sto ant goto §beolvas }
@ant 1 == @direction 2 == & { @antx inv { @XRES -- sto antx }{ --() antx } 3 sto ant goto §beolvas }
@ant 2 == @direction 2 == & { @anty inv { @YRES -- sto anty }{ --() anty } 1 sto ant goto §beolvas }
@ant 2 == @direction 3 == & { ++() anty @anty @YRES == { zero anty } 0 sto ant goto §beolvas }
@ant 3 == @direction 2 == & { ++() anty @anty @YRES == { zero anty } 0 sto ant goto §beolvas }
@ant 3 == @direction 3 == & { @anty inv { @YRES -- sto anty }{ --() anty } 1 sto ant goto §beolvas }
beolvas:
myscreen key !sto billkód @pausetime inv sleep $1b == {
."Made " {..} print ." generations.\n" {.>.} }
..}
myscreen inv graphic
end
{ „myscreen” }
{ „billkód” }
{ „pausetime” }
{ „XRES” }
{ „YRES” }
{ „szin1” }
{ „szin2” }
{ „ant” }
{ „antx” }
{ „anty” }
{ „direction” }
</syntaxhighlight>
=={{header|Gambas}}==
<
hGridView As GridView 'The display is on a GridView
Line 3,398 ⟶ 4,006:
End With
End</
'''[http://www.cogier.com/gambas/Langton's%20ant.png Click here for an image of the result]'''
Line 3,405 ⟶ 4,013:
To make it easier to see the output on small Atari screens, the output is written to a text file.
<
'
' Langton's ant
Line 3,499 ⟶ 4,107:
WEND
RETURN
</syntaxhighlight>
=={{header|Go}}==
[[file:GoAnt.png|right|thumb|Output png]]
<
import (
Line 3,555 ⟶ 4,163:
fmt.Println(err)
}
}</
=={{header|Haskell}}==
Line 3,562 ⟶ 4,170:
Necessary import:
<
In order to express the ant's algorithm literally we define two operators:
<
(>>>) = flip (.)
-- functional choice
p ?>> (f, g) = \x -> if p x then f x else g x</
Finally define the datatype representing the state of ant and ant's universe
<
, antDirection :: Point
, getCells :: Set Point }
type Point = (Float, Float)</
Now we are ready to express the main part of the algorithm
<
step = isBlack ?>> (setWhite >>> turnRight,
setBlack >>> turnLeft) >>> move
Line 3,589 ⟶ 4,197:
turnRight (State p (x,y) m) = State p (y,-x) m
turnLeft (State p (x,y) m) = State p (-y,x) m
move (State (x,y) (dx,dy) m) = State (x+dx, y+dy) (dx, dy) m</
That's it.
Here is the solution of the task:
<
task = iterate step
>>> dropWhile ((< 50) . distance . antPosition)
>>> getCells . head
where distance (x,y) = max (abs x) (abs y)</
For given initial configuration it returns the set of black cells at the end of iterations.
We can display it graphically using Gloss library
<
main = display w white (draw (task initial))
Line 3,610 ⟶ 4,218:
initial = State (0,0) (1,0) mempty
draw = foldMap drawCell
drawCell (x,y) = Translate (10*x) (10*y) $ rectangleSolid 10 10</
Or animate the ant's trajectory
<
where
w = InWindow "Langton's Ant" (400,400) (0,0)
initial = State (0,0) (1,0) mempty
draw (State p _ s) = pictures [foldMap drawCell s, color red $ drawCell p]
drawCell (x,y) = Translate (10*x) (10*y) $ rectangleSolid 10 10</
=={{header|Icon}} and {{header|Unicon}}==
[[file:LangtonsAnt_unicon_100x100_11655.gif|right|thumb]]
<
procedure main(A)
Line 3,673 ⟶ 4,281:
WAttrib(label)
WDone()
end</
{{libheader|Icon Programming Library}}
Line 3,681 ⟶ 4,289:
=={{header|J}}==
<
langton=:3 :0
loc=. <.-:$cells=. (_2{.y,y)$dir=. 0
Line 3,691 ⟶ 4,299:
end.
' #' {~ cells
)</
<pre style="font-size: 2px"> langton 100 100
Line 3,797 ⟶ 4,405:
=={{header|Java}}==
This implementation allows for sizes other than 100x100, marks the starting position with a green box (sometimes hard to see at smaller zoom levels and the box is smaller than the "pixels" so it doesn't cover up the color of the "pixel" it's in), and includes a "zoom factor" (<code>ZOOM</code>) in case the individual "pixels" are hard to see on your monitor.
<
import java.awt.Graphics;
Line 3,864 ⟶ 4,472:
return plane;
}
}</
Output (click for a larger view):
Line 3,873 ⟶ 4,481:
Utilises the HTML5 canvas element to procedurally generate the image... I wanted to see the progress of the grid state as it was generated, so this implementation produces a incrementally changing image until an 'ant' hits a cell outside of the coordinate system. It can also accept multiple ants, this adds minimal complexity with only the addition of an 'ants' array which is iterated in each step, no additional conditions are necessary to simulate multiple ants, they coexist quite well... good ants ! 1st argument is an array of ant objects, 2nd argument is an object property list of options to change grid size, pixel size and interval (animation speed).
<syntaxhighlight lang="javascript">
// create global canvas
var canvas = document.createElement('canvas');
Line 3,975 ⟶ 4,583:
simulate();
}
</syntaxhighlight>
Usage: default ants, custom opts
<syntaxhighlight lang="javascript">
langtonant({}, {
gridsize: 100,
Line 3,985 ⟶ 4,593:
interval: 4
});
</syntaxhighlight>
{{out}}
Line 3,995 ⟶ 4,603:
Usage: custom ants, default opts
<syntaxhighlight lang="javascript">
langtonant([
{
Line 4,015 ⟶ 4,623:
}
]);
</syntaxhighlight>
{{out}}
Line 4,027 ⟶ 4,635:
Requires lodash. Wants a canvas with id = "c"
<
///////////////////
// LODASH IMPORT //
Line 4,096 ⟶ 4,704:
updateWorld(world, ant, RUNS);
</syntaxhighlight>
=={{header|jq}}==
In the following, the grid is boolean, and white is represented by true.
<syntaxhighlight lang="jq">
def matrix(m; n; init):
if m == 0 then [range(0;n)] | map(init)
Line 4,111 ⟶ 4,719:
| ($grid|length) as $height
| ($grid[0]|length) as $width
| reduce range(0;$height) as $i ("\
. + reduce range(0;$width) as $j ("\n";
. + if $grid[$i][$j] then " " else "#" end ) );
Line 4,158 ⟶ 4,766:
;
langtons_ant(100)</
{{Out}}
The output is the same as for [[#Rexx|Rexx]] below.
Line 4,164 ⟶ 4,772:
=={{header|Julia}}==
{{works with|Julia|1.0}}
<syntaxhighlight lang="julia">
function ant(width, height)
y, x = fld(height, 2), fld(width, 2)
Line 4,183 ⟶ 4,791:
ant(100, 100)
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|D}}
<
enum class Direction { UP, RIGHT, DOWN, LEFT }
Line 4,220 ⟶ 4,828:
println()
}
}</
{{out}}
Line 4,232 ⟶ 4,840:
"Go to the ant, O sluggard; consider her ways, and be wise. Without having any chief, officer, or ruler, she prepares her bread in summer and gathers her food in harvest." For Dr. Kaser.
<syntaxhighlight lang="lc-3">
.orig x3000
Line 4,950 ⟶ 5,558:
.end
</syntaxhighlight>
=={{header|Liberty BASIC}}==
Native graphics.
[[Image:langtonsant.png]]
<
black=0
white=not(black)
Line 5,010 ⟶ 5,618:
end
end sub
</
Text version.
<syntaxhighlight lang="lb">
'move up=1 right=2 down=3 left=4
' ---------------------------------
Line 5,042 ⟶ 5,650:
next x
</
=={{header|Locomotive Basic}}==
<
20 ink 1,0:ink 0,26
30 x=50:y=50:ang=270
Line 5,059 ⟶ 5,667:
120 y=y+cos(ang)
130 if x<1 or x>100 or y<1 or y>100 then end
140 goto 70</
Output:
Line 5,066 ⟶ 5,674:
=={{header|Logo}}==
<
make "white 1
make "black 2
Line 5,116 ⟶ 5,724:
]
]
bye</
{{Output}}
Line 5,174 ⟶ 5,782:
=={{header|LOLCODE}}==
<
I HAS A plane ITZ A BUKKIT
Line 5,212 ⟶ 5,820:
IM OUTTA YR printer BTW, UR OUTTA CYAN
KTHXBYE</
=={{header|Lua}}==
For this example, the lua Socket and Curses modules and a terminal with enough lines are needed.
<
local curses = require 'curses' -- used for graphics
Line 5,323 ⟶ 5,931:
socket.sleep(naptime)
until false
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Ant {
Form 120,102
Line 5,383 ⟶ 5,991:
}
Ant
</syntaxhighlight>
{{out}}
Line 5,471 ⟶ 6,079:
</pre >
=={{header|
[[File:make_langton_ant.png|right]]
<syntaxhighlight lang="make"># Langton's ant Makefile
# netpbm is an ancient collection of picture file formats
# convert and display are from imagemagick
.PHONY: display
display: ant.png
display $<
ant.png: ant.pbm
convert $< $@
n9:=1 2 3 4 5 6 7 8 9
n100:=$(n9) $(foreach i,$(n9),$(foreach j,0 $(n9),$i$j)) 100
ndec:=0 $(n100)
ninc:=$(wordlist 2,99,$(n100))
$(foreach i,$(n100),$(eval row$i:=$(foreach j,$(n100),0)))
.PHONY: $(foreach i,$(ndec),row$i)
row0:
@echo >ant.pbm P1
@echo >>ant.pbm '#' Langton"'"s ant
@echo >>ant.pbm 100 100
rowrule=row$i: row$(word $i,$(ndec)); @echo >>ant.pbm $$($$@)
$(foreach i,$(n100),$(eval $(rowrule)))
ant.pbm: Makefile row100
@:
x:=50
y:=50
direction:=1
turn=$(eval direction:=$(t$(xy)$(direction)))
xy=$(word $x,$(row$y))
t01:=4
t02:=1
t03:=2
t04:=3
t11:=2
t12:=3
t13:=4
t14:=1
flip=$(eval row$y:=$(start) $(not$(xy)) $(end))
start=$(wordlist 1,$(word $x,$(ndec)),$(row$y))
not0:=1
not1:=0
end=$(wordlist $(word $x,$(ninc) 100),100,$(row$y))
step=$(eval $(step$(direction)))
step1=y:=$(word $y,exit $(n100))
step2=x:=$(word $x,$(ninc) exit)
step3=y:=$(word $y,$(ninc) exit)
step4=x:=$(word $x,exit $(n100))
iteration=$(if $(filter exit,$x $y),,$(turn)$(flip)$(step))
$(foreach i,$(n100) $(n100),$(foreach j,$(n100),$(iteration)))
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
[[File:LangtonsAnt.png|right|thumb|Output]]
<
data = SparseArray[{{50, 50} -> -1}, {100, 100}, 1];
NestWhile[
{Re@#, Im@#} &@(direction *= (data[[Sequence @@ #]] *= -1) I) + # &,
{50, 50}, 1 <= Min@# <= Max@# <= 100 &];
Image@data</
=={{header|MATLAB}} / {{header|Octave}}==
<
if nargin<1, n=100; end;
A = sparse(n,n); % white
Line 5,502 ⟶ 6,168:
if (~mod(k,100)),spy(A);pause(.1);end; %display after every 100 interations
end;
end</
=={{header|Nim}}==
{{trans|Python}}
<
type
Line 5,524 ⟶ 6,190:
var i = 0
while i < maxSteps and x in 0 ..
let turn = m[y][x] == black
m[y][x] = if m[y][x] == black: white else: black
Line 5,539 ⟶ 6,205:
for row in m:
echo map(row, proc(x: Color): string =
if x == white: "." else: "#").join("")</
=={{header|OCaml}}==
<
type dir = North | East | South | West
Line 5,574 ⟶ 6,240:
if not(key_pressed()) then loop (move pos dir) dir
in
loop (size_x()/2, size_y()/2) North</
Run with:
Line 5,580 ⟶ 6,246:
=={{header|Octave}}==
<
E=100 % Size of lattice.
N=11200 % Number of iterations.
Line 5,591 ⟶ 6,257:
endfor;
imagesc(reshape(z,E,E)) % Draw the Lattice
</syntaxhighlight>
=={{header|Ol}}==
{{libheader|OpenGL}}
<
#!/usr/bin/ol
(import (otus random!))
Line 5,667 ⟶ 6,333:
)))
</syntaxhighlight>
=={{header|PARI/GP}}==
[[File:Langton-pari.png|right|thumb]]
<
my(M=matrix(100,100),x=50,y=50,d=0);
while(x && y && x<=100 && y<=100,
Line 5,685 ⟶ 6,351:
plothraw(u,v)
};
show(langton())</
=={{header|Pascal}}==
Line 5,695 ⟶ 6,361:
{{works with|Turbo Pascal}} Except, the green arrow on step 4 does not appear!
<syntaxhighlight lang="pascal">
{$B- Early and safe resolution of If x <> 0 and 1/x...}
Program LangtonsAnt; Uses CRT;
Line 5,809 ⟶ 6,475:
END.
</syntaxhighlight>
=={{header|Perl}}==
<
use strict;
# Perl 5 implementation of Langton's Ant
Line 5,852 ⟶ 6,518:
}
print "\n";
}</
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">grid</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">),</span><span style="color: #000000;">100</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">aX</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">50</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">aY</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">50</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">gXY</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">angle</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- ' '/'#'; 0,1,2,3 = NESW</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">dX</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- (dY = reverse(dX))</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">aX</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">aX</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">100</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">aY</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">aY</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">gXY</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">grid</span><span style="color: #0000FF;">[</span><span style="color: #000000;">aX</span><span style="color: #0000FF;">][</span><span style="color: #000000;">aY</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">grid</span><span style="color: #0000FF;">[</span><span style="color: #000000;">aX</span><span style="color: #0000FF;">][</span><span style="color: #000000;">aY</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">67</span><span style="color: #0000FF;">-</span><span style="color: #000000;">gXY</span> <span style="color: #000080;font-style:italic;">-- ' '<=>'#', aka 32<->35</span>
<span style="color: #000000;">angle</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">gXY</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- +/-1, ie 0,1,2,3 -> 1,2,3,0 or 3,0,1,2</span>
<span style="color: #000000;">aX</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">dX</span><span style="color: #0000FF;">[</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">aY</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">dX</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">-</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">grid</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre style="font-size: 2px">
Line 5,933 ⟶ 6,601:
''to the halves of width and height.)''<br>
<br>
<
// INIT AND DEFINITION
define('dest_name', 'output.png'); // destination image
Line 5,985 ⟶ 6,653:
// SAVE IMAGE
imagepng($img, dest_name);
</syntaxhighlight>
=={{header|PicoLisp}}==
[[File:Picolisp_ant.gif|right|thumb]]
This code pipes a PBM into ImageMagick's "display" to show the result:
<
(let (Field (make (do Height (link (need Width)))) Dir 0)
(until (or (le0 X) (le0 Y) (> X Width) (> Y Height))
Line 6,007 ⟶ 6,675:
(out '(display -) (ant 100 100 50 50))
(bye)
</syntaxhighlight>
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
To simplify the steps within the loop, -1 and 1 are used to represent the binary state of the spaces in the grid. As neither state is now a default value, to simplify setting the starting states, an array of arrays is used instead of a two dimensional array.
<syntaxhighlight lang="powershell">
$Size = 100
Line 6,040 ⟶ 6,708:
# Convert to strings for output
ForEach ( $Row in $G ) { ( $Row | ForEach { ( ' ', '', '#')[$_+1] } ) -join '' }
</syntaxhighlight>
{{out}}
Default PowerShell console colors reverse the colors from black on white to white on dark blue. Most blank lines not included below.
Line 6,101 ⟶ 6,769:
=={{header|Processing}}==
Processing implementation, this uses two notable features of Processing, first of all, the animation is calculated with the draw() loop, second the drawing on the screen is also used to represent the actual state.
<
* we use the following conventions:
* directions 0: up, 1: left, 2: down: 3: right
Line 6,181 ⟶ 6,849:
void setBool(int x, int y, boolean white) {
set(x,y,white?#ffffff:#000000);
}</
==={{header|Processing Python mode}}===
<
we use the following conventions:
directions 0: up, 1: left, 2: down: 3: right
Line 6,250 ⟶ 6,918:
def setBool(x, y, white):
set(x, y, -1 if white else 0)</
=={{header|Prolog}}==
Line 6,256 ⟶ 6,924:
{{works with|SWI Prolog|6.2.6 by Jan Wielemaker, University of Amsterdam}}
[[File:ant.jpg|thumb|right|Sample output]]
<
% Langtons ant.
:-dynamic
Line 6,288 ⟶ 6,956:
(direction(Row,Col,right), R is Row - 1, !, move(north, R, Col)).
go :- retractall(black(_)), move(north,49,49), update_win.</
=={{header|PureBasic}}==
[[File:PureBasic_Langtons_ant.png|thumb|Sample display of PureBasic solution]]
<
#Black = 0
#planeHeight = 100
Line 6,346 ⟶ 7,014:
Delay(10) ;control animation speed and avoid hogging CPU
Until quit = 1</
Sample output:
<pre>Out of bounds after 11669 steps.</pre>
=={{header|Python}}==
<
"""Langton's ant implementation."""
from enum import Enum, IntEnum
Line 6,433 ⟶ 7,101:
if __name__ == "__main__":
ant(width=75, height=52, max_nb_steps=12000)
</syntaxhighlight>
The output is similar to the basic D version.
=={{header|Quackery}}==
<syntaxhighlight lang="Quackery"> [ stack 50 ] is xpos ( --> s )
[ stack 50 ] is ypos ( --> s )
[ xpos share 0 100 within
ypos share 0 100 within
and ] is inside ( --> b )
[ -1 ypos ] is north ( --> n s )
[ 1 xpos ] is east ( --> n s )
[ 1 ypos ] is south ( --> n s )
[ -1 xpos ] is west ( --> n s )
[ stack 0 ] is heading ( --> s )
[ 1 ] is right ( --> n )
[ -1 ] is left ( --> n )
[ heading take
+ 4 mod
heading put ] is turn ( --> )
[ heading share
[ table
north east south west ]
do tally ] is move ( --> )
[ ypos share peek
xpos share bit & 0 > ] is black? ( [ --> b )
[ ypos share
2dup peek
xpos share bit ~ &
unrot poke ] is white ( [ --> [ )
[ ypos share
2dup peek
xpos share bit |
unrot poke ] is black ( [ --> [ )
[ 50 xpos replace
50 ypos replace
0 heading replace ] is reset ( --> )
[ witheach
[ 100 times
[ dup i^ bit &
iff say "[]"
else say " " ]
cr
drop ] ] is draw ( [ --> )
[ reset
0 100 of
[ inside while
dup black? iff
[ white left ]
else
[ black right ]
turn
move
again ]
draw ] is ant ( --> )</syntaxhighlight>
{{out}}
Surplus whitespace trimmed. Shown at <sup>'''2'''</sup>/<sub>'''3'''</sub> size.
<pre style="font-size:67%">
[][] [][][][][][][][][][][][] [][]
[] [][][][] [] [][]
[][][] [][] [][] []
[] [] [] [] [] []
[][] [][] [] [] [][][] []
[][][] [] [] [] [] [][] [][] [][][]
[] [] [][][] [][] [][][][] [][] [] [] [] [][] [][]
[] [][][] [][] [] [][] [][][] [] [] [][][] [][][]
[] [] [][][][][] [] [] [][][][] [] [][][] [] [] []
[][][] [][] [] [][][][] [][] [][] [][][][][][] [] [][][] [] []
[] [][][] [] [][] [] [] [][] [][] [][] [] [][][][][] [][][] [][]
[] [] [] [][] [][][] [] [] [] [][][][] [] [][]
[] [] [][] [][] [] [][] [][] [] [][]
[][][] [] [] [][] [][][] [] [][] [] [][][] [][] [][] []
[] [][][] [][] [][] [][] [][][] [] [] [][] [][][][] []
[][][] [] [] [] [] [] [][][][] [][] [] [][] [][][] [] []
[] [][][] [] [][] [] [] [][][] [] [][][] [][] [] [] [][]
[][][] [] [] [][] [] [][] [][] [][][][][] [][][][] [][][][] [][] []
[] [][][] [] [] [] [] [][][] [] [] [][] [][] [] [] [] [] []
[][][] [] [][] [][][] [][] [] [][] [][][][] [][][][] [] []
[] [][][] [] [] [] [][] [][][][][][][][][][][] [] [][][][] [] [] []
[][][] [] [][] [] [][][][] [][] [][][][][][][][][] [] [][] [] [][]
[] [][][] [] [] [][] [] [][] [][] [][] [][][] [][][] [] [] [][] [][][][] []
[][][] [] [][] [] [] [][][][][][] [][] [] [][] [] [] [][][] [][][] [][] []
[] [][][] [] [] [] [][][][][] [] [][][][][] [] [] [][] [] [][] []
[][][] [] [][] [] [] [][] [][][][][] [][] [] [] [] [] [][] [] [] []
[] [][][] [] [] [] [] [][][][] [] [][][][][] [][] [][][][][][][][][][] [][]
[][][] [] [][] [] [][] [][] [] [] [][][][] [] [][] [][][][] [][]
[] [][][] [] [] [][][][][] [] [][] [][] [] [] [] [] [] [] [] []
[][][] [] [][] [][] [][] [] [] [] [][] [][] [] [] [][] [] [][] [][]
[] [][][] [] [] [] [] [] [][][][][][][][] [] [] [][] [][][][] []
[][][] [] [][] [] [] [] [][] [][] [] [] [][] []
[] [][][] [] [] [] [] [] [] [][] [][] [][] [][][][]
[][][] [] [][] [][] [] [][] [][] [] [] [][][]
[] [][][] [] [] [] [][] [][][][] [][][][] [][][] [][][][]
[][][] [] [][] [][] [][][][] [][] [] [][] [] [] []
[] [][][] [] [] [][] [][] [][] [][][] [][] [][][][][]
[][][] [] [][] [] [][] [] [][][][]
[] [][][] [] [] [][] [][] [][]
[][][] [] [][] [][]
[] [][][] [] [] [] [][] [][][][] []
[][][] [] [][] [] [] [][][] [][][]
[] [][][] [] [] [] [][] [] [] []
[][][] [] [][] [][] [][]
[] [][][] [] [] [][]
[][][] [] [][]
[] [] [] [] []
[][][][] [][]
[] [][] []
[][][][]
[][]</pre>
=={{header|R}}==
<syntaxhighlight lang="r">
langton.ant = function(n = 100) {
map = matrix(data = 0, nrow = n, ncol = n)
Line 6,458 ⟶ 7,248:
image(langton.ant(), xaxt = "n", yaxt = "n", bty = "n")
</syntaxhighlight>
=={{header|Racket}}==
Line 6,465 ⟶ 7,255:
This Racket program attempts to avoid mutation.
<
;; contracts allow us to describe expected behaviour of funcitons
Line 6,528 ⟶ 7,318:
((#t) (place-image (circle 2 "solid" "black") (* x 4) (* y 4) scn)))))
(show-grid/png (langton (make-ant 'u 50 50) (hash)))
</syntaxhighlight>
Output (text):
<pre style="height:60ex;overflow:scroll">
Line 6,589 ⟶ 7,379:
{{trans|Perl}}
In this version we use 4-bits-per-char graphics to shrink the output to a quarter the area of ASCII graphics.
<syntaxhighlight lang="raku"
constant @blocky = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'.comb;
constant $size = 100;
Line 6,613 ⟶ 7,403:
+ 8 * @plane[$x+1][$y+1] ];
}
}</
{{out}}
<pre>Out of bounds after 11669 moves at (-1, 26)
Line 6,663 ⟶ 7,453:
<br>the screen to display the maximum area of the ant's path (walk).
<br>Or in other words, this REXX program only shows the pertinent part of the ant's walk─field.
<
parse arg dir char seed . /*obtain optional arguments from the CL*/
if datatype(seed, 'W') then call random ,,seed /*Integer? Then use it as a RANDOM SEED*/
if dir=='' | dir=="," then dir= random(1, 4)
if char=='' | char=="," then char= '#' /*binary colors: 0≡white, 1≡black. */
parse value scrSize() with sd sw . /*obtain the terminal's depth and width*/
sd= sd -6;
xHome= 1000000;
$.= 1
minX= x;
@.=
do #=1 until (maxX-minY>sw)|(maxY-minY>sd) /*is the path out─of─bounds for screen?*/
black= @.x.y;
if black then dir= dir - 1
else dir= dir + 1
dir= $.dir
select /*ant walks the direction it's facing. */
when dir==1 then y= y + 1 /*is ant walking north? Then go up. */
Line 6,686 ⟶ 7,476:
when dir==4 then x= x - 1 /* " " " west? " " left. */
end /*select*/ /*the DIRection is always normalized.*/
minX= min(minX, x);
minY= min(minY, y);
end /*steps*/ /* [↑] ant walks hither and thither. */
/*finished walking, it's
say center(" Langton's ant walked " # ' steps ', sw, "─")
@.xHome.yHome= '█'
@.x.y= '∙'
/* [↓] show Langton's ant's trail. */
do y=maxY to minY by -1; _= /*display a single row of cells. */
do x=minX to maxX; _=_ || @.x.y /*build a cell row for the display. */
end /*x*/ /* [↓] strip trailing blanks from line*/
_= strip( translate(_, char, 10), 'T')
if _\=='' then say _ /*display line (strip trailing blanks).*/
end /*y*/ /*stick a fork in it, we're all done. */</
Programing note: the 23<sup>rd</sup> REXX line:
<
could've been coded as:
<
The terminal's screen size used was '''80'''<small>x</small>'''160'''.
Line 6,794 ⟶ 7,584:
=={{header|Ring}}==
<
load "guilib.ring"
load "stdlib.ring"
Line 6,850 ⟶ 7,640:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
Output:
Line 6,857 ⟶ 7,647:
=={{header|Ruby}}==
<
class OutOfBoundsException < StandardError; end
Line 6,946 ⟶ 7,736:
moves = ant.run
puts "out of bounds after #{moves} moves: #{ant.position}"
puts ant</
{{out}}
Line 7,051 ⟶ 7,841:
....................................................................................................</pre>
'''Simple Version:'''
<
MOVE = [[1,0], [0,1], [-1,0], [0,-1]] # [0]:east, [1]:south, [2]:west, [3]:north
Line 7,077 ⟶ 7,867:
end
puts Ant.new(100, 100).to_s</
;Output is the same above.
=={{header|Run BASIC}}==
<
x = 50: y = 50: minY = 100
Line 7,110 ⟶ 7,900:
next y
render #g
#g "flush""</
Ouptut (Produces both character and graphic):[[File:Langtons_ant_run_basic.png|right|graphic]]
Line 7,197 ⟶ 7,987:
=={{header|Rust}}==
<
x: usize,
y: usize,
Line 7,273 ⟶ 8,063:
println!("{}", string);
}
}</
=={{header|Scala}}==
<
import Langton._
val rows=matrix.size
Line 7,318 ⟶ 8,108:
println(l)
}
}</
Output:
<pre style="height: 40ex; overflow: scroll">Out of bounds after 11669 moves
Line 7,424 ⟶ 8,214:
=={{header|Scilab}}==
{{works with|Scilab|5.4.1 or above}}
<syntaxhighlight lang="text">grid_size=100; //side length of the square grid
ant_pos=round([grid_size/2 grid_size/2]); //ant's initial position at center of grid
head_direction='W'; //ant's initial direction can be either
Line 7,494 ⟶ 8,284:
end
disp(ascii_grid);</
{{out}}
<pre style="font-size: 10px">
Line 7,700 ⟶ 8,490:
=={{header|Seed7}}==
<
const type: direction is new enum UP, RIGHT, DOWN, LEFT end enum;
Line 7,729 ⟶ 8,519:
writeln;
end for;
end func;</
{{out}}
Line 7,789 ⟶ 8,579:
=={{header|Sidef}}==
{{trans|Raku}}
<
define size = 100
Line 7,812 ⟶ 8,602:
say "Out of bounds after #{moves} moves at (#{x}, #{y})"
plane.map{.map {|square| square == Black ? '#' : '.' }}.each{.join.say}</
=={{header|Swift}}==
{{trans|C#}}
<
let WIDTH = 100
Line 7,888 ⟶ 8,678:
}
println()
}</
{{out}}
Blank lines omitted
Line 7,976 ⟶ 8,766:
{{libheader|Tk}}
[[File:LangtonAnt_Tcl.gif|thumb|Output of Tcl solution of Langton's ant task]]
<
proc step {workarea} {
Line 8,008 ⟶ 8,798:
# Produce output in file
antgrid write ant.gif -format gif</
=={{header|TI-83 BASIC}}==
The variable N counts the generation number.
<
:ClrDraw
:0→N
Line 8,030 ⟶ 8,820:
:N+1→N
:End
</syntaxhighlight>
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Z Shell}}
This uses the terminal dimensions, so shrink the font and make the window big; should be at least 80 lines by 100 columns.
<syntaxhighlight lang="sh">function main {
typeset -i width=$(tput cols)
typeset -i height=$(tput lines)
typeset -a grid
typeset -i i
for (( i=0; i<height; ++i )); do
grid+=("$(printf "%${width}s" ' ')")
done
typeset -i x=$(( width / 2 )) y=$(( height / 2 ))
(( dx=0, dy = 1 - 2*RANDOM%2 ))
if (( RANDOM % 2 )); then
(( dy=0, dx = 1 - 2*RANDOM%2 ))
fi
printf '\e[H';
printf '%s\n' "${grid[@]}"
tput civis
while (( x>=0 && x < width && y >=0 && y< height)); do
(( i=y ))
if [[ -n $ZSH_VERSION ]]; then
(( i += 1 ))
fi
ch=${grid[i]:$x:1}
if [[ $ch == '#' ]]; then
(( t=dx, dx=dy, dy=-t ))
grid[i]=${grid[i]:0:$x}' '${grid[i]:$x+1}
else
(( t=dx, dx=-dy, dy=t ))
grid[i]=${grid[i]:0:$x}'#'${grid[i]:$x+1}
fi
(( x += dx, y += dy ))
tput cup $y 0 && printf '%s' "${grid[i]}"
done
tput cnorm
read line
return
}
main "$@"</syntaxhighlight>
{{Out}}
Example final state:
<pre> ## # #
### # #
# ## ##
## ## #
# # # ##
## # ### #
# # ### ##
## # ####
# # ### ##
## # ####
# # ### ##
## # ####
# # ### ##
## # ####
# # ### ##
## # ####
# # ### ##
## # ####
## # # ### ##
## ## ## # ####
# # # ## # # # ### ##
### ### # # ## # ####
# #### ## # # # ### ##
## ## # ####
## ## ## # # ### ##
#### # ## # ## # ####
##### ## ### ## ## ## # # ### ##
# # # ## # ## #### ## ## # ####
#### ### #### #### ## # # # ### ##
### # # ## ## # ## ## # ####
#### ## ## ## # # # # # # ### ##
# ## # # ## ## # # # ## # ####
# #### ## # # ######## # # # # # ### ##
## ## # ## # # ## ## # # # ## ## ## # ####
# # # # # # # # ## ## # ##### # # ### ##
## #### ## # #### # # ## ## # ## # ####
## ########## ## ##### # #### # # # # ### ##
# # # ## # # # # ## ##### ## # # ## # ####
# ## # ## # # ##### # ##### # # # ### ##
# ## ### ### # # ## # ## ###### # # ## # ####
# #### ## # # ### ### ## ## ## # ## # # ### ##
## # ## # ######### ## #### # ## # ####
# # # #### # ########### ## # # # ### ##
# # #### #### ## # ## ### ## # ####
# # # # # ## ## # # ### # # # # ### ##
# ## #### #### ##### ## ## # ## # # ####
## # # ## ### # ### # # ## # ### ##
# # ### ## # ## #### # # # # # ####
# #### ## # # ### ## ## ## ### ##
# ## ## ### # ## # ### ## # # ####
## # ## ## # ## ## # ##
## # #### # # # ### ## # ###
## ### ##### # ## ## ## # # ## ### #
# # ### # ###### ## ## #### # # ###
# # # ### # #### # # ##### # # #
### ### # # ### ## # ## ###
## ## # # # ## #### ## ### # ##
### ## ## # # # # # #
# ### # # ## #
# # # # #
# ## ## # #
## # #### ##
## ############ #
</pre>
=={{header|Uiua}}==
[https://www.uiua.org/pad?src=0_12_0-dev_1__IyBEcmF3IExhbmd0b24ncyBBbnQuCgpOIOKGkCAxMDAKIyBpbml0aWFsaXNlIGRpciBwb3MgbWFwClvCrzEgMF0gWzUwIDUwXSDihq9OX04gMQojIFJ1biB1bnRpbCBvdXQgb2YgYm91bmRzCuKNoigKICDiipko4p-cKOKNnOKKoSgtOjEpKSkKICDin6jijZwo4oqhMXzCrynih4x84oeM4o2cKOKKoTF8wq8p4p-pOuKKmSjiiqEsLCkKICDin5wrCnwg4omlMOKLhS_ihqcKKQojIFNjYWxlIHVwCuKWveKfnOKJoeKWvTTil4zil4wK Run it in Uiua Pad!]
<syntaxhighlight lang="Uiua">
# Draw Langton's Ant.
N ← 100
# initialise dir pos map
[¯1 0] [50 50] ↯N_N 1
# Run until out of bounds
⍢(
⊙(⟜(⍜⊡(-:1)))
⟨⍜(⊡1|¯)⇌|⇌⍜(⊡1|¯)⟩:⊙(⊡,,)
⟜+
| ≥0⋅/↧
)
# Scale up
▽⟜≡▽4◌◌
</syntaxhighlight>
{{out}}
[[File:Uiua Langton's Ant Upscaled.png|thumb|center]]
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Sub Ant()
Dim TablDatas(1 To 200, 1 To 256) As String, sDir As String, sFile As String, Str As String
Dim ColA As Integer, LigA As Long, ColF As Integer, LigF As Long, i As Long, j As Integer, Num As Long
Dim Top As Boolean, Left As Boolean, Bottom As Boolean, Right As Boolean
'init variables
Select Case Int(Rnd(4) * 4)
Case 0: Top = True
Case 1: Right = True
Case 2: Bottom = True
Case 3: Left = True
End Select
LigF = 80
ColF = 50
Line 8,052 ⟶ 8,980:
Next
'directory
sDir = "
'name txt file
sFile = "Langton_Ant.txt"
'start
Dim Dir As String
For i = 1 To 15000
LigA = LigF
ColA = ColF
If LigA = 1 Or ColA = 1 Or ColA = 256 Or LigA = 200 Then GoTo Fin
If TablDatas(LigA, ColA) = " " Then
TablDatas(LigA, ColA) = "#"
Select Case True
Case Top: Top = False: Right = True: LigF = LigA: ColF = ColA + 1
Line 8,076 ⟶ 8,998:
Case Bottom: Bottom = False: Left = True: LigF = LigA: ColF = ColA - 1
Case Right: Right = False: Bottom = True: LigF = LigA + 1: ColF = ColA
End Select
Else
TablDatas(LigA, ColA) = " "
Select Case True
Case Top: Top = False: Left = True: LigF = LigA: ColF = ColA - 1
Case Left: Left = False: Bottom = True: LigF = LigA + 1: ColF = ColA
Case Bottom: Bottom = False: Right = True: LigF = LigA: ColF = ColA + 1
Case Right: Right = False: Top = True: LigF = LigA - 1: ColF = ColA
End Select
End If
Next i
Fin:
'result in txt file
Num = FreeFile
Open sDir & sFile For Output As #Num
For i = 1 To UBound(TablDatas, 1)
Str = vbNullString
Line 8,087 ⟶ 9,019:
Str = Str & TablDatas(i, j)
Next j
Print #
Next i
Close #Num
Exit Sub
End Sub
</syntaxhighlight>
{{out}}
Blank lines elided
<pre> ## ##
######
## ## #
# # ##
#### ### #
##### # ##
# ## ## #
### # ##
# ## ## #
### # ##
# ## ## #
### # ##
# ## ## #
### # ##
# ## ## #
### # ##
# ## ## #
### # ##
# ## ## #
### # ##
# ## ## #
###
#
### #
# #
### # ##
###
#
###
#
#
### # ##
# ## ## #
### # ##
# ## ## #
### # ##
# ## ## #
### # ##
# ## ## # ##
### # ## ##
# ## ## ## #
#### ### # # ###
# # # ## #### #
### # # # # ## #
### # ## # ## # ##
# # ## # # ##
# # # ##### # #
# ##### ## ######
### ## # ## # # # ## # ##
## # ####### # # ### ## #
# # ###### ## # # ## # #
# # # ## # ###### ####### #
# #### ## # #### ## ## # ## #
# #### # # ###### ## ###
# # ## # ### # ## ## ###
####### # ## ## # #
#### ## ## #### ## ## ## # #
# # # ### ## ### # #### #
### ### # # ##### # # #
# # ### #### ## # ## ### ## #
## ## #### #### # # # #
# # ## ### ### ### #
## ## ### #### # ### ## #
## # #### # # # ## ### ## #
#### ## ## #### # # # # ### #
# ## ### # # ## # # # # # #
# # # ## ## # # ### ##
## # # ##### # # # # #
# ## # # ## ## # ### ###
# # # # # # ### ## ## #
### # ##### ###### ### ####### # ##
# # # ##### ## ##### #####
# ## # # # ## ### ###
#### ##### ######### # #
## # # ### # # # ### ###
# # #### ## ### ## ### ## ##
### # ## # ##### # # # ## ###
# ##### # # ## ## # # # #
###### #### ## # # ## # # ##
## # ### ## #### # ###
# # ##### # # ## # # #
## ### ####### # # ##
# # ## ## # ## #
# # #### ### ## #
# ## ### ## ##
##
##
</pre>
=={{header|Vim Script}}==
<
function! CurrChar()
return matchstr(getline('.'), '\%' . col('.') . 'c.')
Line 8,211 ⟶ 9,193:
endif
endwhile
endfunction</
=={{header|Whitespace}}==
<
Line 8,306 ⟶ 9,288:
</
Following is the pseudo-Assembly from which the above was generated.
<
push 10003 dup push 100 store
push 1 sub dup push -1 store
Line 8,346 ⟶ 9,328:
5: ; Print a newline and jump back to the counter check.
push 10 ochr jump 4</
=={{header|Wren}}==
{{trans|D}}
The textual version only.
<syntaxhighlight lang="wren">var width = 75
var height = 52
var maxSteps = 12000
var up = 0
var right = 1
var down = 2
var left = 3
var direction = [up, right, down, left]
var white = 0
var black = 1
var x = (width/2).floor
var y = (height/2).floor
var m = List.filled(height, null)
for (i in 0...height) m[i] = List.filled(width, 0)
var dir = up
var i = 0
while (i < maxSteps && 0 <= x && x < width && 0 <= y && y < height) {
var turn = (m[y][x] == black)
var index = (dir + (turn ? 1 : -1)) & 3
dir = direction[index]
m[y][x] = (m[y][x] == black) ? white : black
if (dir == up) {
y = y - 1
} else if (dir == right) {
x = x - 1
} else if (dir == down) {
y = y + 1
} else {
x = x + 1
}
i = i + 1
}
for (j in 0...height) {
for (k in 0...width) System.write((m[j][k] == white) ? "." : "#")
System.print()
}</syntaxhighlight>
{{out}}
<pre>
Same as D entry.
</pre>
=={{header|XPL0}}==
[[File:AntXPL0.gif|right]]
<
int X, Y, Dir;
[SetVid($13); \set 320x200 graphic video mode
Line 8,366 ⟶ 9,396:
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
]</
=={{header|zkl}}==
Line 8,372 ⟶ 9,402:
{{trans|XPL0}}
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
<
w:=h:=100; bitmap:=PPM(w,h,white);
x:=w/2; y:=h/2; dir:=0; // start in middle facing east
Line 8,386 ⟶ 9,416:
}while((0<=x<w) and (0<=y<h));
bitmap.write(File("foo.ppm","wb"));</
{{out}}
Same as XPL0 (and using their image).
|