Conway's Game of Life: Difference between revisions

Content added Content deleted
m (→‎{{header|APL}}: correct spelling of Dyalog)
m (syntax highlighting fixup automation)
Line 36: Line 36:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<lang 11l>V cellcountx = 6
<syntaxhighlight lang="11l">V cellcountx = 6
V cellcounty = 5
V cellcounty = 5
V celltable = [(1, 2) = 1,
V celltable = [(1, 2) = 1,
Line 62: Line 62:
col-1..col+1, (r, c) -> :universe[(r, c)]))
col-1..col+1, (r, c) -> :universe[(r, c)]))
), 0)
), 0)
universe = nextgeneration</lang>
universe = nextgeneration</syntaxhighlight>


===More optimal solution===
===More optimal solution===
<lang 11l>V cellcountx = 6
<syntaxhighlight lang="11l">V cellcountx = 6
V cellcounty = 5
V cellcounty = 5
V universe = [[0B] * cellcountx] * cellcounty
V universe = [[0B] * cellcountx] * cellcounty
Line 104: Line 104:
s += universe[row+1][col+1]
s += universe[row+1][col+1]
nextgeneration[row][col] = I universe[row][col] {s C 2..3} E s == 3
nextgeneration[row][col] = I universe[row][col] {s C 2..3} E s == 3
universe = nextgeneration</lang>
universe = nextgeneration</syntaxhighlight>


{{out}}
{{out}}
Line 140: Line 140:
{{works with|http://www.6502asm.com/ 6502asm.com|1.2}}
{{works with|http://www.6502asm.com/ 6502asm.com|1.2}}


<lang 6502asm>randfill: stx $01 ;$200 for indirect
<syntaxhighlight lang="6502asm">randfill: stx $01 ;$200 for indirect
ldx #$02 ;addressing
ldx #$02 ;addressing
stx $02
stx $02
Line 262: Line 262:
lda $01
lda $01
sta $03
sta $03
rts</lang>
rts</syntaxhighlight>


=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==
Line 278: Line 278:
* popLong = <tt>MOVE.L (SP)+,___</tt>
* popLong = <tt>MOVE.L (SP)+,___</tt>


<lang 68000devpac>include "\SrcALL\68000_Macros.asm"
<syntaxhighlight lang="68000devpac">include "\SrcALL\68000_Macros.asm"
;Ram Variables
;Ram Variables
Cursor_X equ $00FF0000 ;Ram for Cursor Xpos
Cursor_X equ $00FF0000 ;Ram for Cursor Xpos
Line 755: Line 755:
DC.B $80 ;23 DMA source address high (C=CMD) CCHHHHHH
DC.B $80 ;23 DMA source address high (C=CMD) CCHHHHHH
VDPSettingsEnd:
VDPSettingsEnd:
even</lang>
even</syntaxhighlight>
{{out}}
{{out}}
[https://ibb.co/VN4KbSL Screenshot of emulator]
[https://ibb.co/VN4KbSL Screenshot of emulator]
Line 762: Line 762:
{{works with|ABAP|7.4 SP05 or Above only}}
{{works with|ABAP|7.4 SP05 or Above only}}
For the proposed task use ''10,9;10,10;10,11'' on screen field P_POS. Can be left blank for random filling
For the proposed task use ''10,9;10,10;10,11'' on screen field P_POS. Can be left blank for random filling
<syntaxhighlight lang="abap">
<lang ABAP>
*&---------------------------------------------------------------------*
*&---------------------------------------------------------------------*
*& Report ZCONWAYS_GAME_OF_LIFE
*& Report ZCONWAYS_GAME_OF_LIFE
Line 965: Line 965:
leave list-processing.
leave list-processing.
endcase.
endcase.
</syntaxhighlight>
</lang>


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun print-row (row)
<syntaxhighlight lang="lisp">(defun print-row (row)
(if (endp row)
(if (endp row)
nil
nil
Line 1,072: Line 1,072:
nil
nil
(progn$ (print-grid grid)
(progn$ (print-grid grid)
(conway (conway-step grid) (1- steps)))))</lang>
(conway (conway-step grid) (1- steps)))))</syntaxhighlight>


{{out}}
{{out}}
Line 1,092: Line 1,092:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>
<syntaxhighlight lang="ada">
WITH Ada.Text_IO; USE Ada.Text_IO;
WITH Ada.Text_IO; USE Ada.Text_IO;
Line 1,148: Line 1,148:
Put_And_Step_Generation (3, "Blinker", Blinker);
Put_And_Step_Generation (3, "Blinker", Blinker);
Put_And_Step_Generation (5, "Glider", Glider);
Put_And_Step_Generation (5, "Glider", Glider);
END Life;</lang>
END Life;</syntaxhighlight>
The solution uses one cell thick border around square Petri dish
The solution uses one cell thick border around square Petri dish
as uninhabited dire land. This simplifies computations of neighborhood.
as uninhabited dire land. This simplifies computations of neighborhood.
Line 1,221: Line 1,221:
The following APL \ 1130 code will need APL385 font installed to display correctly. <br>
The following APL \ 1130 code will need APL385 font installed to display correctly. <br>
See [http://www.dyalog.com/apl-font-keyboard.htm Download APL TT Font]<br>
See [http://www.dyalog.com/apl-font-keyboard.htm Download APL TT Font]<br>
<lang>
<syntaxhighlight lang="text">
∇LIFE[⎕]∇
∇LIFE[⎕]∇
[0] NG←LIFE CG;W
[0] NG←LIFE CG;W
Line 1,248: Line 1,248:
0 0 0 0 0
0 0 0 0 0


</syntaxhighlight>
</lang>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Line 1,254: Line 1,254:
This handler creates and returns a "universe" script object initialised with given "seed" text and dimensions. For convenience, the seed text's visible characters can be anything, the set-up code itself replacing them with "■" characters. The use of the returned universe is demo'd later.
This handler creates and returns a "universe" script object initialised with given "seed" text and dimensions. For convenience, the seed text's visible characters can be anything, the set-up code itself replacing them with "■" characters. The use of the returned universe is demo'd later.


<lang applescript>use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation" -- For the regex at the top of newUniverse()
use framework "Foundation" -- For the regex at the top of newUniverse()
use scripting additions
use scripting additions
Line 1,431: Line 1,431:
return universe
return universe
end newUniverse</lang>
end newUniverse</syntaxhighlight>


In conjunction with the above, this fulfills the task as set:
In conjunction with the above, this fulfills the task as set:


<lang applescript>on RCTask(seed, dimensions, maxGenerations)
<syntaxhighlight lang="applescript">on RCTask(seed, dimensions, maxGenerations)
-- Create a universe and start a list with its initial state.
-- Create a universe and start a list with its initial state.
set universe to newUniverse(seed, dimensions)
set universe to newUniverse(seed, dimensions)
Line 1,456: Line 1,456:


-- Return text containing the original and three generations of a "blinker" in a 3 x 3 grid.
-- Return text containing the original and three generations of a "blinker" in a 3 x 3 grid.
return RCTask("***", {3, 3}, 3)</lang>
return RCTask("***", {3, 3}, 3)</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>"
<syntaxhighlight lang="applescript">"
■■■
■■■
Line 1,481: Line 1,481:
Generation 3
Generation 3
-----"</lang>
-----"</syntaxhighlight>


This alternative to the task code runs an animation of a "Gosper glider gun" in TextEdit, the AppleScriptable text editor included with macOS. The animation's achieved by replacing the entire text of a document with successive universe states. It's faster than it sounds, but the universe size specified shouldn't be much greater than 150 x 150 with current machines.
This alternative to the task code runs an animation of a "Gosper glider gun" in TextEdit, the AppleScriptable text editor included with macOS. The animation's achieved by replacing the entire text of a document with successive universe states. It's faster than it sounds, but the universe size specified shouldn't be much greater than 150 x 150 with current machines.


<lang applescript>on runGame(seed, dimensions, maxGenerations)
<syntaxhighlight lang="applescript">on runGame(seed, dimensions, maxGenerations)
-- Create an RTF file set up for Menlo-Regular 12pt, half spacing, and a reasonable window size.
-- Create an RTF file set up for Menlo-Regular 12pt, half spacing, and a reasonable window size.
set fontName to "Menlo-Regular"
set fontName to "Menlo-Regular"
Line 1,538: Line 1,538:
**"
**"
-- Run for 500 generations in a 100 x 100 universe.
-- Run for 500 generations in a 100 x 100 universe.
runGame(GosperGliderGun, {100, 100}, 500)</lang>
runGame(GosperGliderGun, {100, 100}, 500)</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
Line 1,544: Line 1,544:
{{works with|TI-Nspire}}
{{works with|TI-Nspire}}


<lang ARM Assembly> .string "PRG"
<syntaxhighlight lang="arm assembly"> .string "PRG"


lcd_ptr .req r4
lcd_ptr .req r4
Line 1,640: Line 1,640:
offsets:
offsets:
.hword -321, -320, -319, -1, 1, 319, 320, 321
.hword -321, -320, -319, -1, 1, 319, 320, 321
</syntaxhighlight>
</lang>
http://i.imgur.com/kV9RirP.gif
http://i.imgur.com/kV9RirP.gif


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=143 discussion]
ahk [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=143 discussion]
<lang autohotkey>rows := cols := 10 ; set grid dimensions
<syntaxhighlight lang="autohotkey">rows := cols := 10 ; set grid dimensions
i = -1,0,1, -1,1, -1,0,1 ; neighbors' x-offsets
i = -1,0,1, -1,1, -1,0,1 ; neighbors' x-offsets
j = -1,-1,-1, 0,0, 1,1,1 ; neighbors' y-offsets
j = -1,-1,-1, 0,0, 1,1,1 ; neighbors' y-offsets
Line 1,684: Line 1,684:


GuiClose: ; exit when GUI is closed
GuiClose: ; exit when GUI is closed
ExitApp</lang>
ExitApp</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Line 1,692: Line 1,692:
running for 220 generations,
running for 220 generations,
using [http://en.wikipedia.org/wiki/ANSI_escape_code ANSI escape-codes] for output to terminal:
using [http://en.wikipedia.org/wiki/ANSI_escape_code ANSI escape-codes] for output to terminal:
<syntaxhighlight lang="awk">
<lang AWK>
BEGIN {
BEGIN {
c=220; d=619; i=10000;
c=220; d=619; i=10000;
Line 1,718: Line 1,718:
}
}
}
}
</syntaxhighlight>
</lang>


{{out}} Finally:
{{out}} Finally:
Line 1,749: Line 1,749:


This implementation uses the full screen buffer instead of a 3x3 grid. This naive, unoptimized version gets less than 1 FPS.
This implementation uses the full screen buffer instead of a 3x3 grid. This naive, unoptimized version gets less than 1 FPS.
<lang axe>Full
<syntaxhighlight lang="axe">Full


While getKey(0)
While getKey(0)
Line 1,792: Line 1,792:
End
End
End
End
Return</lang>
Return</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 1,802: Line 1,802:
You can find it in the [[Galton box animation#BASIC256|Galton box animation]] example.
You can find it in the [[Galton box animation#BASIC256|Galton box animation]] example.


<lang basic256># Conway's_Game_of_Life
<syntaxhighlight lang="basic256"># Conway's_Game_of_Life


X = 59 : Y = 35 : H = 4
X = 59 : Y = 35 : H = 4
Line 1,810: Line 1,810:


dim c(X,Y) : dim cn(X,Y) : dim cl(X,Y)
dim c(X,Y) : dim cn(X,Y) : dim cl(X,Y)
</lang><lang basic256>
</syntaxhighlight><syntaxhighlight lang="basic256">
# Thunderbird methuselah
# Thunderbird methuselah
c[X/2-1,Y/3+1] = 1 : c[X/2,Y/3+1] = 1 : c[X/2+1,Y/3+1] = 1
c[X/2-1,Y/3+1] = 1 : c[X/2,Y/3+1] = 1 : c[X/2+1,Y/3+1] = 1
Line 1,874: Line 1,874:
else
else
print "Stabilized in "+(s-2)+" iterations"
print "Stabilized in "+(s-2)+" iterations"
end if</lang>
end if</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,882: Line 1,882:
==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> dx% = 64
<syntaxhighlight lang="bbcbasic"> dx% = 64
dy% = 64
dy% = 64
DIM old&(dx%+1,dy%+1), new&(dx%+1,dy%+1)
DIM old&(dx%+1,dy%+1), new&(dx%+1,dy%+1)
Line 1,916: Line 1,916:
SWAP old&(), new&()
SWAP old&(), new&()
WAIT 30
WAIT 30
UNTIL FALSE</lang>
UNTIL FALSE</syntaxhighlight>
{{out}}
{{out}}
<BR>
<BR>
Line 1,923: Line 1,923:
==={{header|CASIO BASIC}}===
==={{header|CASIO BASIC}}===
{{works with|https://community.casiocalc.org/topic/7586-conways-game-of-life-fx-9750gii9860giii/#entry60579 Conway's Game of Life fx-9750GII/9860GI/II|1.1}}
{{works with|https://community.casiocalc.org/topic/7586-conways-game-of-life-fx-9750gii9860giii/#entry60579 Conway's Game of Life fx-9750GII/9860GI/II|1.1}}
<lang casiobasic>Filename:JG VIDA
<syntaxhighlight lang="casiobasic">Filename:JG VIDA
Cls
Cls
20→D
20→D
Line 1,998: Line 1,998:
Next
Next
Goto 1
Goto 1
</syntaxhighlight>
</lang>


==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
<lang freebasic>' FreeBASIC Conway's Game of Life
<syntaxhighlight lang="freebasic">' FreeBASIC Conway's Game of Life
' May 2015
' May 2015
' 07-10-2016 cleanup/little changes
' 07-10-2016 cleanup/little changes
Line 2,171: Line 2,171:
Print " Press any key to exit "
Print " Press any key to exit "
Sleep
Sleep
End</lang>
End</syntaxhighlight>


==={{header|GFA Basic}}===
==={{header|GFA Basic}}===


<lang>
<syntaxhighlight lang="text">
'
'
' Conway's Game of Life
' Conway's Game of Life
Line 2,319: Line 2,319:
CLOSEW 1
CLOSEW 1
RETURN
RETURN
</syntaxhighlight>
</lang>


==={{header|GW-BASIC}}===
==={{header|GW-BASIC}}===
Allows a blinker to be loaded. It also has a routine for randomising the grid; common objects like blocks, gliders, etc turn up semi-frequently so it won't take long to verify that these all work.
Allows a blinker to be loaded. It also has a routine for randomising the grid; common objects like blocks, gliders, etc turn up semi-frequently so it won't take long to verify that these all work.


<lang gwbasic>10 REM Conway's Game of Life
<syntaxhighlight lang="gwbasic">10 REM Conway's Game of Life
20 REM 30x30 grid, padded with zeroes as the boundary
20 REM 30x30 grid, padded with zeroes as the boundary
30 DIM WORLD(31, 31, 1)
30 DIM WORLD(31, 31, 1)
Line 2,377: Line 2,377:
520 NEXT YY
520 NEXT YY
530 NEXT XX
530 NEXT XX
540 RETURN</lang>
540 RETURN</syntaxhighlight>


==={{header|Liberty BASIC}}===
==={{header|Liberty BASIC}}===
It will run slow for grids above say 25!
It will run slow for grids above say 25!
<syntaxhighlight lang="lb">
<lang lb>
nomainwin
nomainwin


Line 2,450: Line 2,450:
close #w
close #w
end
end
</syntaxhighlight>
</lang>


==={{header|MSX Basic}}===
==={{header|MSX Basic}}===
<lang basic>
<syntaxhighlight lang="basic">
10 DEFINT A-Z
10 DEFINT A-Z
20 DIM L(16,16), N(16,16)
20 DIM L(16,16), N(16,16)
Line 2,498: Line 2,498:
1350 G=G+1
1350 G=G+1
1360 GOTO 1090
1360 GOTO 1090
</syntaxhighlight>
</lang>


==={{header|PureBasic}}===
==={{header|PureBasic}}===
<lang PureBasic>EnableExplicit
<syntaxhighlight lang="purebasic">EnableExplicit
Define.i x, y ,Xmax ,Ymax ,N
Define.i x, y ,Xmax ,Ymax ,N
Xmax = 13 : Ymax = 20
Xmax = 13 : Ymax = 20
Line 2,556: Line 2,556:
Until Inkey() <> ""
Until Inkey() <> ""
PrintN("Press any key to exit"): Repeat: Until Inkey() <> ""</lang>
PrintN("Press any key to exit"): Repeat: Until Inkey() <> ""</syntaxhighlight>
'''Sample output:'''<br>
'''Sample output:'''<br>
[[File:Game-of-life-PureBasic.gif‎]]
[[File:Game-of-life-PureBasic.gif‎]]
Line 2,566: Line 2,566:
Yo solo lo transcrito y comento al español.<br>
Yo solo lo transcrito y comento al español.<br>
I just transcribed it and comment it in Spanish.
I just transcribed it and comment it in Spanish.
<lang qbasic>SCREEN 9, 0, 0, 1
<syntaxhighlight lang="qbasic">SCREEN 9, 0, 0, 1


RANDOMIZE TIMER
RANDOMIZE TIMER
Line 2,663: Line 2,663:
LOOP UNTIL y > 80
LOOP UNTIL y > 80
PCOPY 0, 1
PCOPY 0, 1
LOOP WHILE INKEY$ = ""</lang>
LOOP WHILE INKEY$ = ""</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Line 2,669: Line 2,669:


The graphics character in lines <tt>1030</tt> to <tt>1060</tt> can be obtained by typing <code>SHIFT</code><code>9</code> then <code>SHIFT</code><code>H</code>, and the one in line <tt>1130</tt> by typing <code>SHIFT</code><code>9</code> then <code>SPACE</code>.
The graphics character in lines <tt>1030</tt> to <tt>1060</tt> can be obtained by typing <code>SHIFT</code><code>9</code> then <code>SHIFT</code><code>H</code>, and the one in line <tt>1130</tt> by typing <code>SHIFT</code><code>9</code> then <code>SPACE</code>.
<lang basic>1000 LET M=LEN L$(1)
<syntaxhighlight lang="basic">1000 LET M=LEN L$(1)
1010 DIM N$(M,M)
1010 DIM N$(M,M)
1020 FOR I=0 TO M+1
1020 FOR I=0 TO M+1
Line 2,705: Line 2,705:
1340 NEXT I
1340 NEXT I
1350 LET G=G+1
1350 LET G=G+1
1360 GOTO 1090</lang>
1360 GOTO 1090</syntaxhighlight>
To run the blinker, add this code:
To run the blinker, add this code:
<lang basic>10 DIM L$(3,3)
<syntaxhighlight lang="basic">10 DIM L$(3,3)
20 LET L$(1)="000"
20 LET L$(1)="000"
30 LET L$(2)="111"
30 LET L$(2)="111"
40 LET L$(3)="000"</lang>
40 LET L$(3)="000"</syntaxhighlight>
A screenshot of it running can be found [http://www.edmundgriffiths.com/zx81lifeblinker.jpg here].
A screenshot of it running can be found [http://www.edmundgriffiths.com/zx81lifeblinker.jpg here].


To try a random starting configuration on a 16x16 grid, use this:
To try a random starting configuration on a 16x16 grid, use this:
<lang basic>10 DIM L$(16,16)
<syntaxhighlight lang="basic">10 DIM L$(16,16)
20 FOR I=1 TO 16
20 FOR I=1 TO 16
30 FOR J=1 TO 16
30 FOR J=1 TO 16
Line 2,720: Line 2,720:
50 IF RND>=.7 THEN LET L$(I,J)="1"
50 IF RND>=.7 THEN LET L$(I,J)="1"
60 NEXT J
60 NEXT J
70 NEXT I</lang>
70 NEXT I</syntaxhighlight>
A screenshot is [http://www.edmundgriffiths.com/zx81liferandom.jpg here].
A screenshot is [http://www.edmundgriffiths.com/zx81liferandom.jpg here].


==={{header|TI-83 BASIC}}===
==={{header|TI-83 BASIC}}===
This implementation is loosely based on the [http://www.processing.org/learning/topics/conway.html Processing Version]. It uses the home screen and draws cells as "X"s. It is extremely slow, and limited to a bounding box of 16 by 8. In order for it to work, you need to initialize arrays [A] and [B] to be 18x10.
This implementation is loosely based on the [http://www.processing.org/learning/topics/conway.html Processing Version]. It uses the home screen and draws cells as "X"s. It is extremely slow, and limited to a bounding box of 16 by 8. In order for it to work, you need to initialize arrays [A] and [B] to be 18x10.
<lang ti83b> PROGRAM:CONWAY
<syntaxhighlight lang="ti83b"> PROGRAM:CONWAY
:While 1
:While 1
:For(X,2,9,1)
:For(X,2,9,1)
Line 2,746: Line 2,746:
:[B]→[A]
:[B]→[A]
:End
:End
</syntaxhighlight>
</lang>
Here is an additional, very simple program to input the top corner of the GRAPH screen into the starting array. Make sure to draw on pixels in the rectangle (1,1) to (8,16).
Here is an additional, very simple program to input the top corner of the GRAPH screen into the starting array. Make sure to draw on pixels in the rectangle (1,1) to (8,16).
<lang ti83b>PROGRAM:PIC2LIFE
<syntaxhighlight lang="ti83b">PROGRAM:PIC2LIFE
:For(I,0,17,1)
:For(I,0,17,1)
:For(J,0,9,1)
:For(J,0,9,1)
Line 2,754: Line 2,754:
:End
:End
:End
:End
</syntaxhighlight>
</lang>


==={{header|TI-89 BASIC}}===
==={{header|TI-89 BASIC}}===
Line 2,761: Line 2,761:
A further improvement would be to have an option to start with the existing picture rather than clearing, and stop at a point where the picture has clean 2x2 blocks.
A further improvement would be to have an option to start with the existing picture rather than clearing, and stop at a point where the picture has clean 2x2 blocks.


<lang ti89b>Define life(pattern) = Prgm
<syntaxhighlight lang="ti89b">Define life(pattern) = Prgm
Local x,y,nt,count,save,xl,yl,xh,yh
Local x,y,nt,count,save,xl,yl,xh,yh
Define nt(y,x) = when(pxlTest(y,x), 1, 0)
Define nt(y,x) = when(pxlTest(y,x), 1, 0)
Line 2,836: Line 2,836:
setGraph("Grid", save[2])
setGraph("Grid", save[2])
setGraph("Labels", save[3])
setGraph("Labels", save[3])
EndPrgm</lang>
EndPrgm</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
Line 2,848: Line 2,848:
If no parameters are parsed, it defaults to 5 iterations of the blinking example.
If no parameters are parsed, it defaults to 5 iterations of the blinking example.


<lang dos>
<syntaxhighlight lang="dos">
@echo off
@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion
Line 2,957: Line 2,957:


exit /b
exit /b
</syntaxhighlight>
</lang>
{{out}}
{{out}}
Blinking example:
Blinking example:
Line 3,053: Line 3,053:
In Befunge-93, the maximum value for the width and height of the universe is 127, but there is an additional constraint of 4080 cells in total, so the largest universe would really be something like 120x34 or 68x60. Befunge-98 has no real limit on the size, although in practice a much larger universe will probably be unbearably slow.
In Befunge-93, the maximum value for the width and height of the universe is 127, but there is an additional constraint of 4080 cells in total, so the largest universe would really be something like 120x34 or 68x60. Befunge-98 has no real limit on the size, although in practice a much larger universe will probably be unbearably slow.


<lang befunge>00p10p20p30p&>40p&>50p60p>$#v~>:55+-vv+`1:%3:+*g04p03< >3/"P"%\56v>p\56*8*/8+:v
<syntaxhighlight lang="befunge">00p10p20p30p&>40p&>50p60p>$#v~>:55+-vv+`1:%3:+*g04p03< >3/"P"%\56v>p\56*8*/8+:v
v5\`\"~"::-*3p06!:!-+67:_^#!<*<!g06!<>1+70g*\:3/"P"%v^ ^::+*g04%<*0v`1:%3\gp08<
v5\`\"~"::-*3p06!:!-+67:_^#!<*<!g06!<>1+70g*\:3/"P"%v^ ^::+*g04%<*0v`1:%3\gp08<
>6*`*#v_55+-#v_p10g1+10p>^pg08g07+gp08:+8/*8*65\p07:<^ >/10g-50g^87>+1+:01p/8/v
>6*`*#v_55+-#v_p10g1+10p>^pg08g07+gp08:+8/*8*65\p07:<^ >/10g-50g^87>+1+:01p/8/v
Line 3,060: Line 3,060:
O>"l52?[">:#,_^v/3+2:*g05g04$_>:10p40g0^!:-1,g+4\0%2/+1+`1:%3\g+8<^: $v10!*-g<<
O>"l52?[">:#,_^v/3+2:*g05g04$_>:10p40g0^!:-1,g+4\0%2/+1+`1:%3\g+8<^: $v10!*-g<<
g+70g80gp:#v_$^>1-:::"P"%\"P"/8+:10v >/10g+1-50g+50g%40g*+::3/"P"^>!|>g*70g80g
g+70g80gp:#v_$^>1-:::"P"%\"P"/8+:10v >/10g+1-50g+50g%40g*+::3/"P"^>!|>g*70g80g
:p00%g04:-1<<$_^#!:pg01%"P"\*8%8gp<< ^3\%g04+g04-1+g00%3:%9+4:-1p06\<90p01/g04</lang>
:p00%g04:-1<<$_^#!:pg01%"P"\*8%8gp<< ^3\%g04+g04-1+g00%3:%9+4:-1p06\<90p01/g04</syntaxhighlight>


{{in}}
{{in}}
Line 3,097: Line 3,097:
=={{header|Brat}}==
=={{header|Brat}}==


<lang brat>width = 3
<syntaxhighlight lang="brat">width = 3
height = 3
height = 3
rounds = 3
rounds = 3
Line 3,157: Line 3,157:
p
p
step
step
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,175: Line 3,175:


=={{header|BQN}}==
=={{header|BQN}}==
<lang bqn>Life←{
<syntaxhighlight lang="bqn">Life←{
r←¯1(⌽⎉1)¯1⌽(2+≢𝕩)↑𝕩
r←¯1(⌽⎉1)¯1⌽(2+≢𝕩)↑𝕩
s←∨´ (1∾<r) ∧ 3‿4 = <+´⥊ ¯1‿0‿1 (⌽⎉1)⌜ ¯1‿0‿1 ⌽⌜ <r
s←∨´ (1∾<r) ∧ 3‿4 = <+´⥊ ¯1‿0‿1 (⌽⎉1)⌜ ¯1‿0‿1 ⌽⌜ <r
Line 3,182: Line 3,182:


blinker←>⟨0‿0‿0,1‿1‿1,0‿0‿0⟩
blinker←>⟨0‿0‿0,1‿1‿1,0‿0‿0⟩
(<".#") ⊏¨˜ Life⍟(↕3) blinker</lang>
(<".#") ⊏¨˜ Life⍟(↕3) blinker</syntaxhighlight>
{{out}}
{{out}}
<pre>┌─
<pre>┌─
Line 3,194: Line 3,194:
=={{header|C}}==
=={{header|C}}==
Play game of life on your console: <code>gcc -std=c99 -Wall game.c; ./a.out [width] [height]</code>
Play game of life on your console: <code>gcc -std=c99 -Wall game.c; ./a.out [width] [height]</code>
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <unistd.h>
#include <unistd.h>
Line 3,249: Line 3,249:
if (h <= 0) h = 30;
if (h <= 0) h = 30;
game(w, h);
game(w, h);
}</lang>
}</syntaxhighlight>
Also see [[Conway's Game of Life/C]]
Also see [[Conway's Game of Life/C]]


===C for Arduino===
===C for Arduino===
Play game of life on your arduino (using FastLED) - based on the C example.
Play game of life on your arduino (using FastLED) - based on the C example.
<syntaxhighlight lang="c">
<lang C>
#include <FastLED.h>
#include <FastLED.h>


Line 3,329: Line 3,329:
FastLED.delay(1000/FRAMERATE);
FastLED.delay(1000/FRAMERATE);
}
}
</syntaxhighlight>
</lang>


===C for Arduino===
===C for Arduino===
Play game of life on your arduino (using two MAX7219 led 'screens') - based on the C example.
Play game of life on your arduino (using two MAX7219 led 'screens') - based on the C example.
<syntaxhighlight lang="c">
<lang C>


#include <MaxMatrix.h>
#include <MaxMatrix.h>
Line 3,421: Line 3,421:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.Text;
using System.Text;
Line 3,601: Line 3,601:
}
}


</syntaxhighlight>
</lang>


Output:
Output:
<lang>
<syntaxhighlight lang="text">
Frame 1: Frame 2: Frame 3:
Frame 1: Frame 2: Frame 3:
██
██
██████ ██ ██████
██████ ██ ██████
██
██
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==
Considering that the simplest implementation in C++ would lack any use of the object-oriented paradigm, this code was specifically written to demonstrate the various object-oriented features of C++. Thus, while it is somewhat verbose, it fully simulates Conway's Game of Life and is relatively simple to expand to feature different starting shapes.
Considering that the simplest implementation in C++ would lack any use of the object-oriented paradigm, this code was specifically written to demonstrate the various object-oriented features of C++. Thus, while it is somewhat verbose, it fully simulates Conway's Game of Life and is relatively simple to expand to feature different starting shapes.
<lang c>#include <iostream>
<syntaxhighlight lang="c">#include <iostream>
#define HEIGHT 4
#define HEIGHT 4
#define WIDTH 4
#define WIDTH 4
Line 3,817: Line 3,817:
gol2.iterate(4);
gol2.iterate(4);
}
}
</syntaxhighlight>
</lang>
{{out}} first a glider, then a blinker, over a few iterations
{{out}} first a glider, then a blinker, over a few iterations
(reformatted for convenience).
(reformatted for convenience).
Line 3,837: Line 3,837:
Another aproach - a pretty simple one.<br />
Another aproach - a pretty simple one.<br />
This version allows you to start the automata with different set of rules. Just for the fun of it.
This version allows you to start the automata with different set of rules. Just for the fun of it.
<lang cpp>
<syntaxhighlight lang="cpp">
#include <algorithm>
#include <algorithm>
#include <vector>
#include <vector>
Line 4,024: Line 4,024:
return system( "pause" );
return system( "pause" );
}
}
</syntaxhighlight>
</lang>
{{out}}<pre>
{{out}}<pre>
+--------------------+ +--------------------+ +--------------------+ +--------------------+
+--------------------+ +--------------------+ +--------------------+ +--------------------+
Line 4,042: Line 4,042:
Shows a glider over 20 generations
Shows a glider over 20 generations
Board edges wrap around to simulate infinite board
Board edges wrap around to simulate infinite board
<lang cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include <vector>
#include <vector>
Line 4,127: Line 4,127:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}<pre>
{{out}}<pre>
generation 0:
generation 0:
Line 4,180: Line 4,180:


=={{header|Chapel}}==
=={{header|Chapel}}==
<lang chapel>
<syntaxhighlight lang="chapel">
config const gridHeight: int = 3;
config const gridHeight: int = 3;
config const gridWidth: int = 3;
config const gridWidth: int = 3;
Line 4,247: Line 4,247:
}
}
}
}
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 4,273: Line 4,273:
Based on the implementation by Christophe Grand here: http://clj-me.cgrand.net/2011/08/19/conways-game-of-life/
Based on the implementation by Christophe Grand here: http://clj-me.cgrand.net/2011/08/19/conways-game-of-life/
This implementation models the live cells as a set of coordinates.
This implementation models the live cells as a set of coordinates.
<lang lisp>(defn moore-neighborhood [[x y]]
<syntaxhighlight lang="lisp">(defn moore-neighborhood [[x y]]
(for [dx [-1 0 1]
(for [dx [-1 0 1]
dy [-1 0 1]
dy [-1 0 1]
Line 4,300: Line 4,300:
(def *blinker* #{[1 2] [2 2] [3 2]})
(def *blinker* #{[1 2] [2 2] [3 2]})
(def *glider* #{[1 0] [2 1] [0 2] [1 2] [2 2]})
(def *glider* #{[1 0] [2 1] [0 2] [1 2] [2 2]})
</syntaxhighlight>
</lang>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol>identification division.
<syntaxhighlight lang="cobol">identification division.
program-id. game-of-life-program.
program-id. game-of-life-program.
data division.
data division.
Line 4,371: Line 4,371:
if cell(neighbour-row,neighbour-cell) is equal to '#',
if cell(neighbour-row,neighbour-cell) is equal to '#',
and check-cell is not equal to zero or check-row is not equal to zero,
and check-cell is not equal to zero or check-row is not equal to zero,
then add 1 to living-neighbours.</lang>
then add 1 to living-neighbours.</syntaxhighlight>
{{out}}
{{out}}
<pre>GENERATION 0:
<pre>GENERATION 0:
Line 4,395: Line 4,395:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun next-life (array &optional results)
<syntaxhighlight lang="lisp">(defun next-life (array &optional results)
(let* ((dimensions (array-dimensions array))
(let* ((dimensions (array-dimensions array))
(results (or results (make-array dimensions :element-type 'bit))))
(results (or results (make-array dimensions :element-type 'bit))))
Line 4,436: Line 4,436:
(terpri out) (print-grid world out)
(terpri out) (print-grid world out)
(psetq world (next-life world result)
(psetq world (next-life world result)
result world))))</lang>
result world))))</syntaxhighlight>


<lang lisp>(run-life (make-array '(3 3)
<syntaxhighlight lang="lisp">(run-life (make-array '(3 3)
:element-type 'bit
:element-type 'bit
:initial-contents '((0 0 0)
:initial-contents '((0 0 0)
(1 1 1)
(1 1 1)
(0 0 0)))
(0 0 0)))
3)</lang>
3)</syntaxhighlight>


produces
produces
Line 4,461: Line 4,461:
A version using a sparse list of living cells rather than an explicit board.
A version using a sparse list of living cells rather than an explicit board.


<lang lisp>(defun moore-neighborhood (cell)
<syntaxhighlight lang="lisp">(defun moore-neighborhood (cell)
(let ((r '(-1 0 1)))
(let ((r '(-1 0 1)))
(mapcan
(mapcan
Line 4,502: Line 4,502:


(defparameter *blinker* '((1 . 2) (2 . 2) (3 . 2)))
(defparameter *blinker* '((1 . 2) (2 . 2) (3 . 2)))
(defparameter *glider* '((1 . 0) (2 . 1) (0 . 2) (1 . 2) (2 . 2)))</lang>
(defparameter *glider* '((1 . 0) (2 . 1) (0 . 2) (1 . 2) (2 . 2)))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.string, std.algorithm, std.array, std.conv;
<syntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.array, std.conv;


struct GameOfLife {
struct GameOfLife {
Line 4,568: Line 4,568:
uni.writeln;
uni.writeln;
}
}
}</lang>
}</syntaxhighlight>
{{out|Output, first iteration}}
{{out|Output, first iteration}}
<pre>-------------------------------------------------------------
<pre>-------------------------------------------------------------
Line 4,594: Line 4,594:
===Faster Version===
===Faster Version===
Same output.
Same output.
<lang d>import std.stdio, std.string, std.algorithm, std.typetuple,
<syntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.typetuple,
std.array, std.conv;
std.array, std.conv;


Line 4,664: Line 4,664:
uni.writeln;
uni.writeln;
}
}
}</lang>
}</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>/**
<syntaxhighlight lang="dart">/**
* States of a cell. A cell is either [ALIVE] or [DEAD].
* States of a cell. A cell is either [ALIVE] or [DEAD].
* The state contains its [symbol] for printing.
* The state contains its [symbol] for printing.
Line 4,823: Line 4,823:
loadBlinker(grid) => blinkerPoints().forEach((point) => grid.set(point, State.ALIVE));
loadBlinker(grid) => blinkerPoints().forEach((point) => grid.set(point, State.ALIVE));


blinkerPoints() => [new Point(0, 1), new Point(1, 1), new Point(2, 1)];</lang>
blinkerPoints() => [new Point(0, 1), new Point(1, 1), new Point(2, 1)];</syntaxhighlight>


Test cases driving the design of this code:
Test cases driving the design of this code:
<lang dart>#import('<path to sdk>/lib/unittest/unittest.dart');
<syntaxhighlight lang="dart">#import('<path to sdk>/lib/unittest/unittest.dart');


main() {
main() {
Line 4,923: Line 4,923:
});
});
});
});
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,951: Line 4,951:
{{Trans|Go}}
{{Trans|Go}}
Thanks Rudy Velthuis for the [https://github.com/rvelthuis/Consoles Velthuis.Console] library.
Thanks Rudy Velthuis for the [https://github.com/rvelthuis/Consoles Velthuis.Console] library.
<syntaxhighlight lang="delphi">
<lang Delphi>
program game_of_life;
program game_of_life;


Line 5,084: Line 5,084:
end;
end;
readln;
readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre> * *** * * *
<pre> * *** * * *
Line 5,105: Line 5,105:
Just does three generations of a blinker in a dead-boundary grid, as specified. ([[User:Kevin Reid]] has graphical and wrapping versions.)
Just does three generations of a blinker in a dead-boundary grid, as specified. ([[User:Kevin Reid]] has graphical and wrapping versions.)


<lang e>def gridWidth := 3
<syntaxhighlight lang="e">def gridWidth := 3
def gridHeight := 3
def gridHeight := 3
def X := 0..!gridWidth
def X := 0..!gridWidth
Line 5,165: Line 5,165:
currentFrame := frame
currentFrame := frame
println(currentFrame)
println(currentFrame)
}</lang>
}</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==
Line 5,171: Line 5,171:
[https://easylang.online/apps/game-of-life.html Run it]
[https://easylang.online/apps/game-of-life.html Run it]


<lang>n = 70
<syntaxhighlight lang="text">n = 70
n += 1
n += 1
subr init
subr init
Line 5,231: Line 5,231:
len p[] n * n + n + 1
len p[] n * n + n + 1
call init
call init
timer 0</lang>
timer 0</syntaxhighlight>


=={{header|eC}}==
=={{header|eC}}==
{{libheader|Ecere}}
{{libheader|Ecere}}


<syntaxhighlight lang="ec">
<lang eC>
import "ecere"
import "ecere"


Line 5,332: Line 5,332:


GameOfLife life {};
GameOfLife life {};
</syntaxhighlight>
</lang>


=={{header|Egel}}==
=={{header|Egel}}==


<lang Egel>import "prelude.eg"
<syntaxhighlight lang="egel">import "prelude.eg"
import "io.ego"
import "io.ego"


Line 5,390: Line 5,390:
let _ = map [ G -> let _ = print "generation:\n" in printboard G ] {GEN0, GEN1, GEN2} in
let _ = map [ G -> let _ = print "generation:\n" in printboard G ] {GEN0, GEN1, GEN2} in
nop
nop
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0, using cellular library
ELENA 5.0, using cellular library
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
import system'threading;
import system'threading;
import cellular;
import cellular;
Line 5,509: Line 5,509:


console.readChar()
console.readChar()
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
{{works with|Elixir|1.2}}
{{trans|Ruby}}
{{trans|Ruby}}
<lang elixir>defmodule Conway do
<syntaxhighlight lang="elixir">defmodule Conway do
def game_of_life(name, size, generations, initial_life\\nil) do
def game_of_life(name, size, generations, initial_life\\nil) do
board = seed(size, initial_life)
board = seed(size, initial_life)
Line 5,582: Line 5,582:
Conway.game_of_life("blinker", 3, 2, [{2,1},{2,2},{2,3}])
Conway.game_of_life("blinker", 3, 2, [{2,1},{2,2},{2,3}])
Conway.game_of_life("glider", 4, 4, [{2,1},{3,2},{1,3},{2,3},{3,3}])
Conway.game_of_life("glider", 4, 4, [{2,1},{3,2},{1,3},{2,3},{3,3}])
Conway.game_of_life("random", 5, 10)</lang>
Conway.game_of_life("random", 5, 10)</syntaxhighlight>


{{out}}
{{out}}
Line 5,673: Line 5,673:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang lisp>#!/usr/bin/env emacs -script
<syntaxhighlight lang="lisp">#!/usr/bin/env emacs -script
;; -*- lexical-binding: t -*-
;; -*- lexical-binding: t -*-
;; run: ./conways-life conways-life.config
;; run: ./conways-life conways-life.config
Line 5,766: Line 5,766:
(swap a b))))
(swap a b))))


(simulate-life (elt command-line-args-left 0))</lang>
(simulate-life (elt command-line-args-left 0))</syntaxhighlight>


Configuration file, which defines the size starting patterns and
Configuration file, which defines the size starting patterns and
how long the simulation will run.
how long the simulation will run.
<lang lisp>((rows . 8)
<syntaxhighlight lang="lisp">((rows . 8)
(cols . 10)
(cols . 10)
(generations . 3)
(generations . 3)
Line 5,778: Line 5,778:
;; This is a custom pattern.
;; This is a custom pattern.
(4 4 (".***"
(4 4 (".***"
"***."))))</lang>
"***."))))</syntaxhighlight>


{{out}}
{{out}}
Line 5,812: Line 5,812:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>


-module(life).
-module(life).
Line 6,021: Line 6,021:
list_to_integer(atom_to_list(Atom)).
list_to_integer(atom_to_list(Atom)).


</syntaxhighlight>
</lang>


=={{header|ERRE}}==
=={{header|ERRE}}==
This is a simple implementation of Conway's game of Life with an endless world. Test pattern configuration is 'glider'.
This is a simple implementation of Conway's game of Life with an endless world. Test pattern configuration is 'glider'.
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM LIFE
PROGRAM LIFE


Line 6,099: Line 6,099:
END PROGRAM
END PROGRAM


</syntaxhighlight>
</lang>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
The following F# implementation uses {{libheader|Windows Presentation Foundation}} for visualization and is easily compiled into a standalone executable:
The following F# implementation uses {{libheader|Windows Presentation Foundation}} for visualization and is easily compiled into a standalone executable:
<lang fsharp>let count (a: _ [,]) x y =
<syntaxhighlight lang="fsharp">let count (a: _ [,]) x y =
let m, n = a.GetLength 0, a.GetLength 1
let m, n = a.GetLength 0, a.GetLength 1
let mutable c = 0
let mutable c = 0
Line 6,137: Line 6,137:
Media.CompositionTarget.Rendering.Add update
Media.CompositionTarget.Rendering.Add update
Window(Content=image, Title="Game of Life")
Window(Content=image, Title="Game of Life")
|> (Application()).Run |> ignore</lang>
|> (Application()).Run |> ignore</syntaxhighlight>


=={{header|Fermat}}==
=={{header|Fermat}}==
<lang fermat>;{Conway's Game of Life in Fermat}
<syntaxhighlight lang="fermat">;{Conway's Game of Life in Fermat}
;{square grid with wrap-around boundaries}
;{square grid with wrap-around boundaries}


Line 6,220: Line 6,220:


!!'John Horton Conway (26 December 1937 – 11 April 2020)';
!!'John Horton Conway (26 December 1937 – 11 April 2020)';
</syntaxhighlight>
</lang>
{{out}} One iteration starting from random soup, showing a few well-known objects (blinker, block, glider, beehive, loaf)
{{out}} One iteration starting from random soup, showing a few well-known objects (blinker, block, glider, beehive, loaf)
<pre>
<pre>
Line 6,278: Line 6,278:
'''gencell''' uses an optimization for the core Game of Life rules: new state = (old state | neighbors == 3).
'''gencell''' uses an optimization for the core Game of Life rules: new state = (old state | neighbors == 3).


<lang forth> \ The fast wrapping requires dimensions that are powers of 2.
<syntaxhighlight lang="forth"> \ The fast wrapping requires dimensions that are powers of 2.
1 6 lshift constant w \ 64
1 6 lshift constant w \ 64
1 4 lshift constant h \ 16
1 4 lshift constant h \ 16
Line 6,356: Line 6,356:
**
**
*
*
Generation 1 ok</lang>
Generation 1 ok</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran> PROGRAM LIFE_2D
<syntaxhighlight lang="fortran"> PROGRAM LIFE_2D
IMPLICIT NONE
IMPLICIT NONE
Line 6,459: Line 6,459:
END SUBROUTINE NextgenV2
END SUBROUTINE NextgenV2
!###########################################################################
!###########################################################################
END PROGRAM LIFE_2D</lang>
END PROGRAM LIFE_2D</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:45ex;overflow:scroll">
<pre style="height:45ex;overflow:scroll">
Line 6,586: Line 6,586:
=={{header|Frink}}==
=={{header|Frink}}==
Simple solution using two dictionaries (a display and a toggle) to store grid and track changes. The program outputs an animation of the game.
Simple solution using two dictionaries (a display and a toggle) to store grid and track changes. The program outputs an animation of the game.
<lang frink>
<syntaxhighlight lang="frink">
start = now[]
start = now[]
// Generate a random 10x10 grid with "1" being on and "0" being off
// Generate a random 10x10 grid with "1" being on and "0" being off
Line 6,692: Line 6,692:
end = now[]
end = now[]
println["Program run time: " + ((end - start)*1.0 -> "seconds")]
println["Program run time: " + ((end - start)*1.0 -> "seconds")]
</syntaxhighlight>
</lang>


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>import lists.zipWithIndex
<syntaxhighlight lang="funl">import lists.zipWithIndex
import util.Regex
import util.Regex


Line 6,783: Line 6,783:


repeat 5
repeat 5
iteration()</lang>
iteration()</syntaxhighlight>


{{out}}
{{out}}
Line 6,831: Line 6,831:


=={{header|Furor}}==
=={{header|Furor}}==
<syntaxhighlight lang="furor">
<lang Furor>
// Life simulator (game). Console (CLI) version.
// Life simulator (game). Console (CLI) version.
// It is a 'cellular automaton', and was invented by Cambridge mathematician John Conway.
// It is a 'cellular automaton', and was invented by Cambridge mathematician John Conway.
Line 6,934: Line 6,934:
{ „x” } { „y” } { „n” }
{ „x” } { „y” } { „n” }


</syntaxhighlight>
</lang>


=={{header|Futhark}}==
=={{header|Futhark}}==
{{incorrect|Futhark|Futhark's syntax has changed, so this example will not compile}}
{{incorrect|Futhark|Futhark's syntax has changed, so this example will not compile}}


<syntaxhighlight lang="futhark">
<lang Futhark>
fun bint(b: bool): int = if b then 1 else 0
fun bint(b: bool): int = if b then 1 else 0
fun intb(x: int): bool = if x == 0 then False else True
fun intb(x: int): bool = if x == 0 then False else True
Line 6,983: Line 6,983:
iteration board in
iteration board in
to_int_board board
to_int_board board
</syntaxhighlight>
</lang>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 7,083: Line 7,083:
time.Sleep(time.Second / 30)
time.Sleep(time.Second / 30)
}
}
}</lang>
}</syntaxhighlight>
Running this program will compute and draw the first 300 "frames". The final frame looks like this:
Running this program will compute and draw the first 300 "frames". The final frame looks like this:
<pre>
<pre>
Line 7,105: Line 7,105:
=={{header|Groovy}}==
=={{header|Groovy}}==


<syntaxhighlight lang="groovy">
<lang Groovy>
class GameOfLife {
class GameOfLife {


Line 7,210: Line 7,210:
game.board = game.createGliderBoard()
game.board = game.createGliderBoard()
game.start()
game.start()
</syntaxhighlight>
</lang>


The output of this program:
The output of this program:
Line 7,388: Line 7,388:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.Array.Unboxed
<syntaxhighlight lang="haskell">import Data.Array.Unboxed


type Grid = UArray (Int,Int) Bool
type Grid = UArray (Int,Int) Bool
Line 7,409: Line 7,409:


count :: [Bool] -> Int
count :: [Bool] -> Int
count = length . filter id</lang>
count = length . filter id</syntaxhighlight>


Example of use:
Example of use:


<lang haskell>import Data.List (unfoldr)
<syntaxhighlight lang="haskell">import Data.List (unfoldr)


grid :: [String] -> (Int, Int, Grid)
grid :: [String] -> (Int, Int, Grid)
Line 7,452: Line 7,452:
printGrid w g
printGrid w g


main = printLife 10 glider</lang>
main = printLife 10 glider</syntaxhighlight>


Here's the gridless version. It could probably be improved with some light use of <code>Data.Set</code>, but I leave that as an exercise for the reader. Note that the function <code>lifeStep</code> is the solution in its entirety. The rest of this code deals with printing and test data for the particular model of the world we're using.
Here's the gridless version. It could probably be improved with some light use of <code>Data.Set</code>, but I leave that as an exercise for the reader. Note that the function <code>lifeStep</code> is the solution in its entirety. The rest of this code deals with printing and test data for the particular model of the world we're using.


<lang haskell>module Main where
<syntaxhighlight lang="haskell">module Main where
import Data.List
import Data.List


Line 7,498: Line 7,498:
putStrLn "Blinker >> 3"
putStrLn "Blinker >> 3"
putStrLn "------------"
putStrLn "------------"
runLife 3 blinker</lang>
runLife 3 blinker</syntaxhighlight>


=={{header|HolyC}}==
=={{header|HolyC}}==
Line 7,506: Line 7,506:


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang icon>global limit
<syntaxhighlight lang="icon">global limit


procedure main(args)
procedure main(args)
Line 7,584: Line 7,584:
initial count := 0
initial count := 0
return ((count +:= 1) > \limit) | (trim(!g) == " ")
return ((count +:= 1) > \limit) | (trim(!g) == " ")
end</lang>
end</syntaxhighlight>


A sample run:
A sample run:
Line 7,620: Line 7,620:
=={{header|J}}==
=={{header|J}}==
'''Solution:'''
'''Solution:'''
<lang j>pad=: 0,0,~0,.0,.~]
<syntaxhighlight lang="j">pad=: 0,0,~0,.0,.~]
life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@pad
life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@pad
NB. the above could also be a one-line solution:
NB. the above could also be a one-line solution:
life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@(0,0,~0,.0,.~])
life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@(0,0,~0,.0,.~])
</syntaxhighlight>
</lang>


In other words, given a life instance, the next generation can be found by:
In other words, given a life instance, the next generation can be found by:
Line 7,634: Line 7,634:


'''Example''' (showing generations 0, 1 and 2 of a blinker):
'''Example''' (showing generations 0, 1 and 2 of a blinker):
<lang j> life^:0 1 2 #:0 7 0
<syntaxhighlight lang="j"> life^:0 1 2 #:0 7 0
0 0 0
0 0 0
1 1 1
1 1 1
Line 7,645: Line 7,645:
0 0 0
0 0 0
1 1 1
1 1 1
0 0 0</lang>
0 0 0</syntaxhighlight>


'''Example''' (showing start and six following generations of a glider)
'''Example''' (showing start and six following generations of a glider)


<lang j> blocks=: (2 2$2) ((7 u:' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█') {~ #.@,);._3 >.&.-:@$ {. ]</lang>
<syntaxhighlight lang="j"> blocks=: (2 2$2) ((7 u:' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█') {~ #.@,);._3 >.&.-:@$ {. ]</syntaxhighlight>


<pre style="line-height: 1"> blocks"2 life^:(i.7) 4 5{.#:1 5 3
<pre style="line-height: 1"> blocks"2 life^:(i.7) 4 5{.#:1 5 3
Line 7,675: Line 7,675:
=={{header|JAMES II/Rule-based Cellular Automata}}==
=={{header|JAMES II/Rule-based Cellular Automata}}==
{{libheader|JAMES II}}
{{libheader|JAMES II}}
<lang j2carules>@caversion 1;
<syntaxhighlight lang="j2carules">@caversion 1;


dimensions 2;
dimensions 2;
Line 7,699: Line 7,699:
ALIVE
ALIVE
*/
*/
rule{DEAD}:ALIVE{3}->ALIVE;</lang>
rule{DEAD}:ALIVE{3}->ALIVE;</syntaxhighlight>
Animated output for the blinker example:
Animated output for the blinker example:


Line 7,705: Line 7,705:


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class GameOfLife{
<syntaxhighlight lang="java">public class GameOfLife{
public static void main(String[] args){
public static void main(String[] args){
String[] dish= {
String[] dish= {
Line 7,795: Line 7,795:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Generation 0:
<pre>Generation 0:
Line 7,813: Line 7,813:
This fills in a random 10% of the grid, then activates the Game on it. Uncomment the call to the setCustomConfig function to use your own input. Just mind the grid limits.
This fills in a random 10% of the grid, then activates the Game on it. Uncomment the call to the setCustomConfig function to use your own input. Just mind the grid limits.
Use the input file given below to create a cool screensaver on your terminal.
Use the input file given below to create a cool screensaver on your terminal.
<lang java>
<syntaxhighlight lang="java">
//package conway;
//package conway;


Line 7,968: Line 7,968:
}
}
}
}
</syntaxhighlight>
</lang>


Glider Gun design. Save it in GOLglidergun.txt and uncomment the setCustomConfig function.
Glider Gun design. Save it in GOLglidergun.txt and uncomment the setCustomConfig function.
Line 7,998: Line 7,998:


===Java 10===
===Java 10===
<lang java>
<syntaxhighlight lang="java">
import static java.util.List.of;
import static java.util.List.of;


Line 8,091: Line 8,091:


}
}
</syntaxhighlight>
</lang>
Outputs:
Outputs:
<pre>
<pre>
Line 8,112: Line 8,112:
{{works with|SpiderMonkey}}
{{works with|SpiderMonkey}}
{{works with|V8}}
{{works with|V8}}
<lang javascript>function GameOfLife () {
<syntaxhighlight lang="javascript">function GameOfLife () {


this.init = function (turns,width,height) {
this.init = function (turns,width,height) {
Line 8,210: Line 8,210:
print("---\nRandom 5x10");
print("---\nRandom 5x10");
game.init(5,5,10);
game.init(5,5,10);
game.start();</lang>
game.start();</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:30ex;overflow:scroll">---
<pre style="height:30ex;overflow:scroll">---
Line 8,335: Line 8,335:
{{libheader|HTML5}}
{{libheader|HTML5}}
Essentially the same as the above straight [[JavaScript]] but displayed in an [[HTML5]] Canvas.
Essentially the same as the above straight [[JavaScript]] but displayed in an [[HTML5]] Canvas.
<lang javascript>
<syntaxhighlight lang="javascript">
<html>
<html>
<head>
<head>
Line 8,486: Line 8,486:
</canvas><br>
</canvas><br>
</body>
</body>
</html></lang>
</html></syntaxhighlight>
{{out}} for 3x3 Blinker:
{{out}} for 3x3 Blinker:


Line 8,493: Line 8,493:


'''More functional style''':
'''More functional style''':
<lang javascript>
<syntaxhighlight lang="javascript">
const _ = require('lodash');
const _ = require('lodash');


Line 8,535: Line 8,535:
displayWorld(world);
displayWorld(world);
}, 1000);
}, 1000);
</syntaxhighlight>
</lang>


'''ES6 + ''':
'''ES6 + ''':
<lang javascript>
<syntaxhighlight lang="javascript">
const alive = 1;
const alive = 1;
const dead = 0;
const dead = 0;
Line 8,610: Line 8,610:
run()
run()


</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
Line 8,616: Line 8,616:
In this implementation, a "world" is simply a suitably constructed string as illustrated by world3 and world11 below. The "game" can be played either by creating separate frames (using frames(n))
In this implementation, a "world" is simply a suitably constructed string as illustrated by world3 and world11 below. The "game" can be played either by creating separate frames (using frames(n))
or by calling animation(n; sleep) with sleep approximately equal to the number of milliseconds between refreshes.
or by calling animation(n; sleep) with sleep approximately equal to the number of milliseconds between refreshes.
<lang jq># Notes on the implementation:
<syntaxhighlight lang="jq"># Notes on the implementation:


# 1. For efficiency, the implementation requires that the world
# 1. For efficiency, the implementation requires that the world
Line 8,660: Line 8,660:
end )
end )
| [., $lines, $w] ;
| [., $lines, $w] ;
</syntaxhighlight>
</lang>
'''Animation''':
'''Animation''':
<lang jq># "clear screen":
<syntaxhighlight lang="jq"># "clear screen":
def cls: "\u001b[2J";
def cls: "\u001b[2J";


Line 8,688: Line 8,688:
# Input: a string representing the initial state
# Input: a string representing the initial state
def frames(n): animation(n; -1);
def frames(n): animation(n; -1);
</syntaxhighlight>
</lang>
'''Examples''':
'''Examples''':
<lang jq>def world3:
<syntaxhighlight lang="jq">def world3:
"+---+\n" +
"+---+\n" +
"| |\n" +
"| |\n" +
Line 8,704: Line 8,704:
"| .. |\n" +
"| .. |\n" +
"| |\n" +
"| |\n" +
"+-----------+\n" ;</lang>
"+-----------+\n" ;</syntaxhighlight>


'''Task''':
'''Task''':
<lang jq>world3 | frames(3)</lang>
<syntaxhighlight lang="jq">world3 | frames(3)</syntaxhighlight>
{{Out}}
{{Out}}
<div style="overflow:scroll; height:200px;">
<div style="overflow:scroll; height:200px;">
<lang sh>$ jq -n -r -f Game_of_life.jq
<syntaxhighlight lang="sh">$ jq -n -r -f Game_of_life.jq


+---+
+---+
Line 8,740: Line 8,740:
+---+
+---+


1</lang></div>
1</syntaxhighlight></div>
'''Animation example'''
'''Animation example'''
<lang jq># Animation of 100 frames with approximately 1 second between each update:
<syntaxhighlight lang="jq"># Animation of 100 frames with approximately 1 second between each update:
world11 | animation(100; 1000)</lang>
world11 | animation(100; 1000)</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
From Javascript, SpiderMonkey entry.
From Javascript, SpiderMonkey entry.


<lang javascript>/* Conway's game of life, in Jsish */
<syntaxhighlight lang="javascript">/* Conway's game of life, in Jsish */
function GameOfLife () {
function GameOfLife () {
this.title = "Conway's Game of Life";
this.title = "Conway's Game of Life";
Line 8,887: Line 8,887:


=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 8,898: Line 8,898:
Using the '''CellularAutomata''' package: https://github.com/natj/CellularAutomata.jl
Using the '''CellularAutomata''' package: https://github.com/natj/CellularAutomata.jl


<lang cpp>julia> Pkg.add("CellularAutomata")
<syntaxhighlight lang="cpp">julia> Pkg.add("CellularAutomata")
INFO: Installing CellularAutomata v0.1.2
INFO: Installing CellularAutomata v0.1.2
INFO: Package database updated
INFO: Package database updated
Line 8,908: Line 8,908:


julia> gameOfLife(15, 30, 5)
julia> gameOfLife(15, 30, 5)
30x15x5 Cellular Automaton</lang>
30x15x5 Cellular Automaton</syntaxhighlight>


# ## # ###### ### ### ##
# ## # ###### ### ### ##
Line 8,996: Line 8,996:
=== GPU calculation based version ===
=== GPU calculation based version ===
Requires a CUDA compatible graphics card and uses the ArrayFire library.
Requires a CUDA compatible graphics card and uses the ArrayFire library.
<lang julia>using ArrayFire
<syntaxhighlight lang="julia">using ArrayFire
using Images
using Images
using LinearAlgebra
using LinearAlgebra
Line 9,039: Line 9,039:
lifegame("lwss.gif", lwss)
lifegame("lwss.gif", lwss)
lifegame("glidergun.gif", glidergun, 90, 200)
lifegame("glidergun.gif", glidergun, 90, 200)
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Line 9,050: Line 9,050:
The particular random pattern used now needs only 99 generations to reach stability.
The particular random pattern used now needs only 99 generations to reach stability.


<lang scala>// version 1.2.0
<syntaxhighlight lang="scala">// version 1.2.0


import java.util.Random
import java.util.Random
Line 9,160: Line 9,160:
println()
println()
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 9,260: Line 9,260:
=={{header|Lua}}==
=={{header|Lua}}==
A slight modernization of my original "life.lua" for Lua 3.x circa 2000 -- heck, we didn't even have for loops back then! :D ''(a copy can be found in the 4.0 source distro if interested in comparing syntax)''
A slight modernization of my original "life.lua" for Lua 3.x circa 2000 -- heck, we didn't even have for loops back then! :D ''(a copy can be found in the 4.0 source distro if interested in comparing syntax)''
<lang lua>local function T2D(w,h) local t={} for y=1,h do t[y]={} for x=1,w do t[y][x]=0 end end return t end
<syntaxhighlight lang="lua">local function T2D(w,h) local t={} for y=1,h do t[y]={} for x=1,w do t[y][x]=0 end end return t end


local Life = {
local Life = {
Line 9,296: Line 9,296:
end
end
end
end
}</lang>
}</syntaxhighlight>
Example usage. Coordinates wrap to simulate an infinite universe, so here a glider/lwss are evolved through one complete period, then advanced forward until returning to starting conditions.
Example usage. Coordinates wrap to simulate an infinite universe, so here a glider/lwss are evolved through one complete period, then advanced forward until returning to starting conditions.
<lang lua>print("GLIDER:")
<syntaxhighlight lang="lua">print("GLIDER:")
local life = Life:new(5,5)
local life = Life:new(5,5)
life:set({ 2,1, 3,2, 1,3, 2,3, 3,3 })
life:set({ 2,1, 3,2, 1,3, 2,3, 3,3 })
Line 9,318: Line 9,318:
end
end
for i = 6,20 do life:evolve() end
for i = 6,20 do life:evolve() end
life:render()</lang>
life:render()</syntaxhighlight>
{{out}}
{{out}}
<pre>GLIDER:
<pre>GLIDER:
Line 9,408: Line 9,408:
□ □ □ □ □ □ □ □ □ □</pre>
□ □ □ □ □ □ □ □ □ □</pre>
=={{header|ksh}}==
=={{header|ksh}}==
<lang ksh>
<syntaxhighlight lang="ksh">
#!/bin/ksh
#!/bin/ksh
# # Version AJM 93u+ 2012-08-01
# # Version AJM 93u+ 2012-08-01
Line 9,502: Line 9,502:
_game ${h} ${w}
_game ${h} ${w}


</syntaxhighlight>
</lang>




=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Life {
Module Life {
Font "courier new"
Font "courier new"
Line 9,581: Line 9,581:
}
}
Life
Life
</syntaxhighlight>
</lang>


=={{header|MANOOL}}==
=={{header|MANOOL}}==
Straightforward implementation useful for benchmarking:
Straightforward implementation useful for benchmarking:
<syntaxhighlight lang="manool">
<lang MANOOL>
{ {extern "manool.org.18/std/0.3/all"} in
{ {extern "manool.org.18/std/0.3/all"} in
: let { N = 40; M = 80 } in
: let { N = 40; M = 80 } in
Line 9,638: Line 9,638:
Out.WriteLine["After " G " generations:"]; Display[B]
Out.WriteLine["After " G " generations:"]; Display[B]
}
}
</syntaxhighlight>
</lang>
Using comprehension notation:
Using comprehension notation:
<syntaxhighlight lang="manool">
<lang MANOOL>
{ {extern "manool.org.18/std/0.3/all"} in
{ {extern "manool.org.18/std/0.3/all"} in
: let { N = 40; M = 80 } in
: let { N = 40; M = 80 } in
Line 9,691: Line 9,691:
Out.WriteLine["After " G " generations:"]; Display[B]
Out.WriteLine["After " G " generations:"]; Display[B]
}
}
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica has cellular automaton functionality built in, so implementing Conway's Game of Life is a one-liner:
Mathematica has cellular automaton functionality built in, so implementing Conway's Game of Life is a one-liner:
<lang Mathematica>CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}}, startconfiguration, steps];</lang>
<syntaxhighlight lang="mathematica">CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}}, startconfiguration, steps];</syntaxhighlight>
Example of a glyder progressing 8 steps and showing the 9 frames afterwards as grids of hashes and dots:
Example of a glyder progressing 8 steps and showing the 9 frames afterwards as grids of hashes and dots:
<lang Mathematica>results=CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},{{{0,1,0},{0,0,1},{1,1,1}},0},8];
<syntaxhighlight lang="mathematica">results=CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},{{{0,1,0},{0,0,1},{1,1,1}},0},8];
Do[Print[i-1];Print[Grid[results[[i]]/.{1->"#",0->"."}]];,{i,1,Length[results]}]</lang>
Do[Print[i-1];Print[Grid[results[[i]]/.{1->"#",0->"."}]];,{i,1,Length[results]}]</syntaxhighlight>
gives back:
gives back:
<pre style="height:30ex;overflow:scroll">
<pre style="height:30ex;overflow:scroll">
Line 9,766: Line 9,766:


=={{header|MATLAB}}==
=={{header|MATLAB}}==
MATLAB has a builtin Game of Life GUI. Type <lang matlab>life</lang> to run it. To view the code, type
MATLAB has a builtin Game of Life GUI. Type <syntaxhighlight lang="matlab">life</syntaxhighlight> to run it. To view the code, type


<lang matlab>open(fullfile(matlabroot, 'toolbox', 'matlab', 'demos', 'life.m'))</lang>
<syntaxhighlight lang="matlab">open(fullfile(matlabroot, 'toolbox', 'matlab', 'demos', 'life.m'))</syntaxhighlight>


Here is an example code, more simple (runs the game of life for N generations in a square of side S) :
Here is an example code, more simple (runs the game of life for N generations in a square of side S) :


<lang matlab>function GoL(S, N) %
<syntaxhighlight lang="matlab">function GoL(S, N) %
colormap copper; whitebg('black');
colormap copper; whitebg('black');
G= round(rand(S));
G= round(rand(S));
Line 9,781: Line 9,781:
surf(G); view([0 90]); pause(0.001)
surf(G); view([0 90]); pause(0.001)
end
end
end</lang>
end</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>life(A) := block(
<syntaxhighlight lang="maxima">life(A) := block(
[p, q, B: zerofor(A), s],
[p, q, B: zerofor(A), s],
[p, q]: matrix_size(A),
[p, q]: matrix_size(A),
Line 9,836: Line 9,836:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])</lang>
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
This GUI implementation is for use with [http://miniscript.org/MiniMicro Mini Micro].
This GUI implementation is for use with [http://miniscript.org/MiniMicro Mini Micro].
<lang MiniScript>// Conway's Game of Life
<syntaxhighlight lang="miniscript">// Conway's Game of Life
clear
clear
rows = 64; rowRange = range(0, rows-1)
rows = 64; rowRange = range(0, rows-1)
Line 9,896: Line 9,896:
display(curIdx).mode = displayMode.off
display(curIdx).mode = displayMode.off
curIdx = newIdx
curIdx = newIdx
end while</lang>
end while</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
{{trans|C}}
{{trans|C}}
<lang nim>import os, strutils, random
<syntaxhighlight lang="nim">import os, strutils, random


randomize()
randomize()
Line 9,941: Line 9,941:
swap(univ,utmp)
swap(univ,utmp)


sleep 200</lang>
sleep 200</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let get g x y =
<syntaxhighlight lang="ocaml">let get g x y =
try g.(x).(y)
try g.(x).(y)
with _ -> 0
with _ -> 0
Line 9,990: Line 9,990:
done;
done;
print_newline ()
print_newline ()
done</lang>
done</syntaxhighlight>


put the code above in a file named "life.ml", and then use it in the ocaml toplevel like this:
put the code above in a file named "life.ml", and then use it in the ocaml toplevel like this:
Line 10,053: Line 10,053:
=== A graphical version ===
=== A graphical version ===
This implementation has 6 starting patterns (most get quite large) and a random option, and you can set the grid size.
This implementation has 6 starting patterns (most get quite large) and a random option, and you can set the grid size.
<lang OCaml>let alive = 0
<syntaxhighlight lang="ocaml">let alive = 0
let dead = 0xFFFFFF
let dead = 0xFFFFFF


Line 10,133: Line 10,133:
disp bd2;
disp bd2;
iteration bd2 bd1 width height
iteration bd2 bd1 width height
done</lang>
done</syntaxhighlight>
Compile with: <pre>opam install graphics && ocamlopt -o life -I $(ocamlfind query graphics) graphics.cmxa life.ml</pre> and run with <pre>./life acorn 250 250</pre> If you run the blinker it will probably blink too fast to see unless you choose a large grid size.
Compile with: <pre>opam install graphics && ocamlopt -o life -I $(ocamlfind query graphics) graphics.cmxa life.ml</pre> and run with <pre>./life acorn 250 250</pre> If you run the blinker it will probably blink too fast to see unless you choose a large grid size.


Line 10,139: Line 10,139:
1st order two variable recurrence relation m-file, will also run under MATLAB.
1st order two variable recurrence relation m-file, will also run under MATLAB.


<lang matlab>
<syntaxhighlight lang="matlab">
clear all
clear all
x=55; % Size of the Lattice (same as LAWE)
x=55; % Size of the Lattice (same as LAWE)
Line 10,213: Line 10,213:
pause % each press advances the algorithm one step
pause % each press advances the algorithm one step
endfor
endfor
</syntaxhighlight>
</lang>




=={{header|Ol}}==
=={{header|Ol}}==
{{libheader|OpenGL}}
{{libheader|OpenGL}}
<lang scheme>
<syntaxhighlight lang="scheme">
#!/usr/bin/ol
#!/usr/bin/ol
(import (otus random!))
(import (otus random!))
Line 10,290: Line 10,290:
neighbors)))
neighbors)))
#empty generation)))))
#empty generation)))))
</syntaxhighlight>
</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang oorexx>/* REXX ---------------------------------------------------------------
<syntaxhighlight lang="oorexx">/* REXX ---------------------------------------------------------------
* 07.08.2014 Walter Pachl Conway's Game of life graphical
* 07.08.2014 Walter Pachl Conway's Game of life graphical
* Input is a file containing the initial pattern.
* Input is a file containing the initial pattern.
Line 10,736: Line 10,736:
Else
Else
Return
Return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>blinker.txt
<pre>blinker.txt
Line 10,752: Line 10,752:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
Rules = [rule(c:1 n:[0 1] new:0) %% Lonely
Rules = [rule(c:1 n:[0 1] new:0) %% Lonely
rule(c:1 n:[4 5 6 7 8] new:0) %% Overcrowded
rule(c:1 n:[4 5 6 7 8] new:0) %% Overcrowded
Line 10,855: Line 10,855:
{System.showInfo "\nGen. "#I}
{System.showInfo "\nGen. "#I}
{ForAll {ShowG Gi} System.showInfo}
{ForAll {ShowG Gi} System.showInfo}
end</lang>
end</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Basic implementation; prints a matrix representing the state of the game directly. Supports large games but this example uses only the required 3 X 3 blinker.
Basic implementation; prints a matrix representing the state of the game directly. Supports large games but this example uses only the required 3 X 3 blinker.
<lang parigp>step(M)={
<syntaxhighlight lang="parigp">step(M)={
my(N=M,W=matsize(M)[1],L=#M,t);
my(N=M,W=matsize(M)[1],L=#M,t);
for(l=1,W,for(w=1,L,
for(l=1,W,for(w=1,L,
Line 10,868: Line 10,868:
};
};
M=[0,1,0;0,1,0;0,1,0];
M=[0,1,0;0,1,0;0,1,0];
for(i=1,3,print(M);M=step(M))</lang>
for(i=1,3,print(M);M=step(M))</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 10,875: Line 10,875:
Optimized for speed on a Haswell CPU
Optimized for speed on a Haswell CPU
(without PrintGen ~ 8.5 Cpu-cyles/coordinate )
(without PrintGen ~ 8.5 Cpu-cyles/coordinate )
<lang pascal>program Gol;
<syntaxhighlight lang="pascal">program Gol;
// Game of life
// Game of life
{$IFDEF FPC}
{$IFDEF FPC}
Line 11,054: Line 11,054:
PrintGen;
PrintGen;
end.
end.
</syntaxhighlight>
</lang>


=={{header|Perl}}==
=={{header|Perl}}==
Line 11,064: Line 11,064:
would do 15 iterations over 5 rows and 10 columns.
would do 15 iterations over 5 rows and 10 columns.
<lang perl>my ($width, $height, $generations) = @ARGV;
<syntaxhighlight lang="perl">my ($width, $height, $generations) = @ARGV;


my $printed;
my $printed;
Line 11,122: Line 11,122:
printlife @life;
printlife @life;
}
}
print "\n";</lang>
print "\n";</syntaxhighlight>


Another version, takes up the whole area of your terminal. Using warping edges.<lang Perl>my $w = `tput cols` - 1;
Another version, takes up the whole area of your terminal. Using warping edges.<syntaxhighlight lang="perl">my $w = `tput cols` - 1;
my $h = `tput lines` - 1;
my $h = `tput lines` - 1;
my $r = "\033[H";
my $r = "\033[H";
Line 11,155: Line 11,155:
print map((map($_ ? "#" : " ", @$_), "\n"), @universe);
print map((map($_ ? "#" : " ", @$_), "\n"), @universe);
iterate;
iterate;
}</lang>
}</syntaxhighlight>
===Next Generation in a Single Substitution Operator===
===Next Generation in a Single Substitution Operator===
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl


print $_ = <<'' =~ tr/./ /r; # test case, dots only for layout
print $_ = <<'' =~ tr/./ /r; # test case, dots only for layout
Line 11,173: Line 11,173:
s/$neighborhood/ substr " $&# ", "$1$2$3$4" =~ tr|#||, 1 /ge;
s/$neighborhood/ substr " $&# ", "$1$2$3$4" =~ tr|#||, 1 /ge;
print;
print;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
Line 11,200: Line 11,200:
{{libheader|Phix/online}}
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/conways_game_of_life.htm here].
You can run this online [http://phix.x10.mx/p2js/conways_game_of_life.htm here].
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Conways_Game_of_Life.exw
-- demo\rosetta\Conways_Game_of_Life.exw
Line 11,358: Line 11,358:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Picat}}==
=={{header|Picat}}==
===Blinker===
===Blinker===
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
Rows = 3,
Rows = 3,
Cols = 3,
Cols = 3,
Line 11,425: Line 11,425:
[1,1,1],
[1,1,1],
[0,0,0]],
[0,0,0]],
I=1,J=1.</lang>
I=1,J=1.</syntaxhighlight>


{{out}}
{{out}}
Line 11,446: Line 11,446:


===Testing some more forms===
===Testing some more forms===
<lang Picat>go2 =>
<syntaxhighlight lang="picat">go2 =>
Rows = 20,
Rows = 20,
Cols = 20,
Cols = 20,
Line 11,493: Line 11,493:
[0,0,0,1,1,1],
[0,0,0,1,1,1],
[0,0,0,1,1,1]],
[0,0,0,1,1,1]],
I=10,J=10.</lang>
I=10,J=10.</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Line 11,499: Line 11,499:
an array of multiply linked objects, and are also used in the chess program and
an array of multiply linked objects, and are also used in the chess program and
other games in the distribution.
other games in the distribution.
<lang PicoLisp>(load "@lib/simul.l")
<syntaxhighlight lang="picolisp">(load "@lib/simul.l")


(de life (DX DY . Init)
(de life (DX DY . Init)
Line 11,528: Line 11,528:
(=: life (: next)) ) ) ) ) )
(=: life (: next)) ) ) ) ) )


(life 5 5 b3 c3 d3)</lang>
(life 5 5 b3 c3 d3)</syntaxhighlight>
Output:
Output:
<pre> 5
<pre> 5
Line 11,550: Line 11,550:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>(subscriptrange):
<syntaxhighlight lang="pl/i">(subscriptrange):
Conway: procedure options (main); /* 20 November 2013 */
Conway: procedure options (main); /* 20 November 2013 */
/* A grid of (1:100, 1:100) is desired; the array GRID is defined as (0:101, 0:101), */
/* A grid of (1:100, 1:100) is desired; the array GRID is defined as (0:101, 0:101), */
Line 11,609: Line 11,609:
end;
end;
end;
end;
end Conway;</lang>
end Conway;</syntaxhighlight>
Results:
Results:
<pre>
<pre>
Line 11,653: Line 11,653:


=={{header|Pointless}}==
=={{header|Pointless}}==
<lang pointless>-----------------------------------------------------------
<syntaxhighlight lang="pointless">-----------------------------------------------------------
-- Print 100 simulated states of conway's game of life
-- Print 100 simulated states of conway's game of life
-- for a glider starting pattern on a wrapping grid
-- for a glider starting pattern on a wrapping grid
Line 11,740: Line 11,740:


showCell(cell) =
showCell(cell) =
if cell == 1 then "*" else " "</lang>
if cell == 1 then "*" else " "</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
<lang PostScript>%!PS-Adobe-3.0
<syntaxhighlight lang="postscript">%!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400
%%BoundingBox: 0 0 400 400


Line 11,791: Line 11,791:


1000 { drawboard showpage iter } repeat
1000 { drawboard showpage iter } repeat
%%EOF</lang>
%%EOF</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">
<lang Prolog>
%----------------------------------------------------------------------%
%----------------------------------------------------------------------%
% GAME OF LIFE %
% GAME OF LIFE %
Line 11,974: Line 11,974:
write_line(S,T).
write_line(S,T).
write_line(_,[]) :- !.
write_line(_,[]) :- !.
</syntaxhighlight>
</lang>


'''Sample output:'''<br>
'''Sample output:'''<br>
Line 11,983: Line 11,983:
Inspired by Daniel Shiffman's book The Nature of Code (http://natureofcode.com)
Inspired by Daniel Shiffman's book The Nature of Code (http://natureofcode.com)


<lang java>boolean play = true;
<syntaxhighlight lang="java">boolean play = true;
int cellSize = 10;
int cellSize = 10;
int cols, rows;
int cols, rows;
Line 12,122: Line 12,122:
grid[x][y] = states[grid[x][y]]; // invert
grid[x][y] = states[grid[x][y]]; // invert
}
}
}</lang>
}</syntaxhighlight>


==={{header|Processing Python mode}}===
==={{header|Processing Python mode}}===
<lang python>cell_size = 10
<syntaxhighlight lang="python">cell_size = 10
sample = 10
sample = 10
play = False # simulation is running
play = False # simulation is running
Line 12,235: Line 12,235:
if p != last_cell:
if p != last_cell:
last_cell = p
last_cell = p
grid[i][j] = (1, 0)[grid[i][j]]</lang>
grid[i][j] = (1, 0)[grid[i][j]]</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 12,250: Line 12,250:
of <u>universe</u> returns zero.
of <u>universe</u> returns zero.


<lang python>import random
<syntaxhighlight lang="python">import random
from collections import defaultdict
from collections import defaultdict


Line 12,304: Line 12,304:
for c in range(col-1, col+2) )
for c in range(col-1, col+2) )
) ]
) ]
universe = nextgeneration</lang>
universe = nextgeneration</syntaxhighlight>
{{out}} (sample)
{{out}} (sample)
<pre style="height:30ex;overflow:scroll">
<pre style="height:30ex;overflow:scroll">
Line 12,327: Line 12,327:
A world is represented as a set of (x, y) coordinates of all the alive cells.
A world is represented as a set of (x, y) coordinates of all the alive cells.


<lang python>from collections import Counter
<syntaxhighlight lang="python">from collections import Counter


def life(world, N):
def life(world, N):
Line 12,363: Line 12,363:




life(world, 5)</lang>
life(world, 5)</syntaxhighlight>


{{out}}
{{out}}
Line 12,430: Line 12,430:


===Using an array to define the world===
===Using an array to define the world===
<lang python>import numpy as np
<syntaxhighlight lang="python">import numpy as np
from pandas import DataFrame
from pandas import DataFrame
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
Line 12,491: Line 12,491:


conway_life()</lang>
conway_life()</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
<lang r># Generates a new board - either a random one, sample blinker or gliders, or user specified.
<syntaxhighlight lang="r"># Generates a new board - either a random one, sample blinker or gliders, or user specified.
gen.board <- function(type="random", nrow=3, ncol=3, seeds=NULL)
gen.board <- function(type="random", nrow=3, ncol=3, seeds=NULL)
{
{
Line 12,575: Line 12,575:
game.of.life(gen.board("blinker"))
game.of.life(gen.board("blinker"))
game.of.life(gen.board("glider", 18, 20))
game.of.life(gen.board("glider", 18, 20))
game.of.life(gen.board(, 50, 50))</lang>
game.of.life(gen.board(, 50, 50))</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require 2htdp/image 2htdp/universe)
(require 2htdp/image 2htdp/universe)
Line 12,709: Line 12,709:
;;; (game-of-life (thunder) 2)
;;; (game-of-life (thunder) 2)
;;; (game-of-life (cross) 2)
;;; (game-of-life (cross) 2)
</syntaxhighlight>
</lang>


Output for an 80x80 cross:
Output for an 80x80 cross:
Line 12,717: Line 12,717:
(formerly Perl 6)
(formerly Perl 6)


<lang perl6>class Automaton {
<syntaxhighlight lang="raku" line>class Automaton {
subset World of Str where {
subset World of Str where {
.lines>>.chars.unique == 1 and m/^^<[.#\n]>+$$/
.lines>>.chars.unique == 1 and m/^^<[.#\n]>+$$/
Line 12,774: Line 12,774:
say $glider++;
say $glider++;
say '--';
say '--';
}</lang>
}</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang Rebol>Red [
<syntaxhighlight lang="rebol">Red [
Purpose: "Conway's Game of Life"
Purpose: "Conway's Game of Life"
Author: "Joe Smith"
Author: "Joe Smith"
Line 12,833: Line 12,833:
conway *8-8
conway *8-8
]
]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 13,066: Line 13,066:


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>:w/l [ $. eq? [ #0 ] [ #1 ] choose , ] s:for-each ;
<syntaxhighlight lang="retro">:w/l [ $. eq? [ #0 ] [ #1 ] choose , ] s:for-each ;


'World d:create
'World d:create
Line 13,135: Line 13,135:
}}
}}
#12 gens</lang>
#12 gens</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 13,141: Line 13,141:
This version has been trimmed down from the original REXX program, otherwise the size of the program (with all its options and optional formatting)
This version has been trimmed down from the original REXX program, otherwise the size of the program (with all its options and optional formatting)
<br>would probably be on the large side for general viewing, &nbsp; and maybe a wee bit complex to demonstrate how to program for this task.
<br>would probably be on the large side for general viewing, &nbsp; and maybe a wee bit complex to demonstrate how to program for this task.
<lang rexx>/*REXX program runs and displays the Conway's game of life, it stops after N repeats. */
<syntaxhighlight lang="rexx">/*REXX program runs and displays the Conway's game of life, it stops after N repeats. */
signal on halt /*handle a cell growth interruptus. */
signal on halt /*handle a cell growth interruptus. */
parse arg peeps '(' rows cols empty life! clearScreen repeats generations .
parse arg peeps '(' rows cols empty life! clearScreen repeats generations .
Line 13,185: Line 13,185:
p: return word(arg(1), 1)
p: return word(arg(1), 1)
pickChar: _=p(arg(1)); arg u .; if u=='BLANK' then _=" "; L=length(_); if L==3 then _=d2c(_); if L==2 then _=x2c(_); return _
pickChar: _=p(arg(1)); arg u .; if u=='BLANK' then _=" "; L=length(_); if L==3 then _=d2c(_); if L==2 then _=x2c(_); return _
showRows: _=; do r=rows by -1 for rows; z=; do c=1 for cols; z=z||$.r.c; end; z=strip(z,'T',emp); say z; _=_||z; end; return</lang>
showRows: _=; do r=rows by -1 for rows; z=; do c=1 for cols; z=z||$.r.c; end; z=strip(z,'T',emp); say z; _=_||z; end; return</syntaxhighlight>
This REXX program makes use of &nbsp; '''linesize''' &nbsp; REXX program (or BIF) &nbsp; which is used to determine the screen width (or linesize) of the terminal (console); &nbsp; not all REXXes have this BIF.
This REXX program makes use of &nbsp; '''linesize''' &nbsp; REXX program (or BIF) &nbsp; which is used to determine the screen width (or linesize) of the terminal (console); &nbsp; not all REXXes have this BIF.


Line 13,216: Line 13,216:


===version 2===
===version 2===
<lang rexx>/* REXX ---------------------------------------------------------------
<syntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 02.08.2014 Walter Pachl
* 02.08.2014 Walter Pachl
* Input is a file containing the initial pattern
* Input is a file containing the initial pattern
Line 13,400: Line 13,400:
Return lineout(dbg,arg(1))
Return lineout(dbg,arg(1))
Else
Else
Return</lang>
Return</syntaxhighlight>
{{out}}
{{out}}
<pre> blinker
<pre> blinker
Line 13,421: Line 13,421:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def game_of_life(name, size, generations, initial_life=nil)
<syntaxhighlight lang="ruby">def game_of_life(name, size, generations, initial_life=nil)
board = new_board size
board = new_board size
seed board, size, initial_life
seed board, size, initial_life
Line 13,484: Line 13,484:
game_of_life "blinker", 3, 2, [[1,0],[1,1],[1,2]]
game_of_life "blinker", 3, 2, [[1,0],[1,1],[1,2]]
game_of_life "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]]
game_of_life "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]]
game_of_life "random", 5, 10</lang>
game_of_life "random", 5, 10</syntaxhighlight>


{{out}}
{{out}}
Line 13,602: Line 13,602:
The above implementation uses only methods. Below is one that is object-oriented and feels perhaps a bit more Ruby-ish.
The above implementation uses only methods. Below is one that is object-oriented and feels perhaps a bit more Ruby-ish.


<lang ruby>class Game
<syntaxhighlight lang="ruby">class Game
def initialize(name, size, generations, initial_life=nil)
def initialize(name, size, generations, initial_life=nil)
@size = size
@size = size
Line 13,706: Line 13,706:
Game.new "blinker", 3, 2, [[1,0],[1,1],[1,2]]
Game.new "blinker", 3, 2, [[1,0],[1,1],[1,2]]
Game.new "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]]
Game.new "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]]
Game.new "random", 5, 10</lang>
Game.new "random", 5, 10</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang="rust">
use std::collections::HashMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::HashSet;
Line 13,783: Line 13,783:
life(glider, 20, 8, 8);
life(glider, 20, 8, 8);
}
}
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
Line 13,791: Line 13,791:
{{works with|Scheme|implementing R6RS (tested with PLT Scheme, Petite Chez Scheme)}}
{{works with|Scheme|implementing R6RS (tested with PLT Scheme, Petite Chez Scheme)}}


<syntaxhighlight lang="scheme">
<lang Scheme>
;;An R6RS Scheme implementation of Conway's Game of Life --- assumes
;;An R6RS Scheme implementation of Conway's Game of Life --- assumes
;;all cells outside the defined grid are dead
;;all cells outside the defined grid are dead
Line 13,880: Line 13,880:
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)) 30)</lang>
(0 0 0 0 0 0 0 0)) 30)</syntaxhighlight>


{{out}}
{{out}}
Line 14,178: Line 14,178:
The game's initial state can be input manually by setting the values of <code>Init_state</code>, or using a bitmap image (or other supported formats). The output can be either printed on Scilab's console, or on a graphic window. For both image input and graphic output, either SIVP or IPCV modules are required, and <code>console_output</code> should be set to false.
The game's initial state can be input manually by setting the values of <code>Init_state</code>, or using a bitmap image (or other supported formats). The output can be either printed on Scilab's console, or on a graphic window. For both image input and graphic output, either SIVP or IPCV modules are required, and <code>console_output</code> should be set to false.


<lang>Init_state=[0 0 0;...
<syntaxhighlight lang="text">Init_state=[0 0 0;...
1 1 1;...
1 1 1;...
0 0 0];
0 0 0];
Line 14,280: Line 14,280:
Curr_state=Next_state;
Curr_state=Next_state;
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 14,320: Line 14,320:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>set starting_condition to ((0, 0), (1, 0), (2, 0), (-1, -1), (0, -1), (1, -1))
<syntaxhighlight lang="sensetalk">set starting_condition to ((0, 0), (1, 0), (2, 0), (-1, -1), (0, -1), (1, -1))


RunGameOfLife starting_condition
RunGameOfLife starting_condition
Line 14,392: Line 14,392:
wait 1 second
wait 1 second
end repeat
end repeat
end RunGameOfLife</lang>
end RunGameOfLife</syntaxhighlight>


=={{header|SequenceL}}==
=={{header|SequenceL}}==
Line 14,398: Line 14,398:


'''SequenceL Code:'''
'''SequenceL Code:'''
<lang sequencel>life(Cells(2))[I, J] :=
<syntaxhighlight lang="sequencel">life(Cells(2))[I, J] :=
let
let
numNeighbors := Cells[I-1,J-1] + Cells[I-1,J] + Cells[I-1,J+1] +
numNeighbors := Cells[I-1,J-1] + Cells[I-1,J] + Cells[I-1,J+1] +
Line 14,418: Line 14,418:
1
1
foreach y within 1 ... n,
foreach y within 1 ... n,
x within 1 ... n;</lang>
x within 1 ... n;</syntaxhighlight>


'''C++ Driver Code:'''
'''C++ Driver Code:'''
<lang c>#include <iostream>
<syntaxhighlight lang="c">#include <iostream>
#include <string>
#include <string>
#include <vector>
#include <vector>
Line 14,600: Line 14,600:
}
}
throw(errno);
throw(errno);
}</lang>
}</syntaxhighlight>


'''Usage:'''
'''Usage:'''
Line 14,633: Line 14,633:
This version uses a live cell set representation (set of coordinate pairs.)
This version uses a live cell set representation (set of coordinate pairs.)
This example first appeared [http://www.setl-lang.org/wiki/index.php/Conway%27s_Game_of_Life here].
This example first appeared [http://www.setl-lang.org/wiki/index.php/Conway%27s_Game_of_Life here].
<lang setl>program life;
<syntaxhighlight lang="setl">program life;


const
const
Line 14,667: Line 14,667:
end proc;
end proc;


end program;</lang>
end program;</syntaxhighlight>


=={{header|Shen}}==
=={{header|Shen}}==
Somewhat verbose but functional and type-checked implementation (tested with chibi-scheme and Shen/SBCL). Running this shows ten iterations of a toad.
Somewhat verbose but functional and type-checked implementation (tested with chibi-scheme and Shen/SBCL). Running this shows ten iterations of a toad.
<lang Shen>(tc +)
<syntaxhighlight lang="shen">(tc +)


(datatype subtype
(datatype subtype
Line 14,803: Line 14,803:
[0 1 1 1 0 0]
[0 1 1 1 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]])</lang>
[0 0 0 0 0 0]])</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>var w = Num(`tput cols`)
<syntaxhighlight lang="ruby">var w = Num(`tput cols`)
var h = Num(`tput lines`)
var h = Num(`tput lines`)
var r = "\033[H"
var r = "\033[H"
Line 14,838: Line 14,838:
say universe.map{|row| row.map{|cell| cell ? '#' : ' '}.join }.join("\n")
say universe.map{|row| row.map{|cell| cell ? '#' : ' '}.join }.join("\n")
iterate()
iterate()
}</lang>
}</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
{{trans|Scheme}}
{{trans|Scheme}}
<lang simula>COMMENT A PORT OF AN R6RS SCHEME IMPLEMENTATION OF CONWAY'S GAME OF LIFE TO SIMULA --- ASSUMES ;
<syntaxhighlight lang="simula">COMMENT A PORT OF AN R6RS SCHEME IMPLEMENTATION OF CONWAY'S GAME OF LIFE TO SIMULA --- ASSUMES ;
COMMENT ALL CELLS OUTSIDE THE DEFINED GRID ARE DEAD ;
COMMENT ALL CELLS OUTSIDE THE DEFINED GRID ARE DEAD ;


Line 15,007: Line 15,007:


END.
END.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style="height:30ex;overflow:scroll">
<pre style="height:30ex;overflow:scroll">
Line 15,308: Line 15,308:
This implementation has been developed using '''Cuis Smalltalk''' [https://github.com/Cuis-Smalltalk/Cuis-Smalltalk-Dev].
This implementation has been developed using '''Cuis Smalltalk''' [https://github.com/Cuis-Smalltalk/Cuis-Smalltalk-Dev].
Here are different configurations:
Here are different configurations:
<lang smalltalk>
<syntaxhighlight lang="smalltalk">
"Blinker"
"Blinker"
GameOfLife withAliveCells: { 4@2. 4@3. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10.
GameOfLife withAliveCells: { 4@2. 4@3. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10.
Line 15,314: Line 15,314:
"Toad"
"Toad"
GameOfLife withAliveCells: { 2@4. 3@4. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10
GameOfLife withAliveCells: { 2@4. 3@4. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10
</syntaxhighlight>
</lang>
This is the implementation:
This is the implementation:
<syntaxhighlight lang="smalltalk">
<lang Smalltalk>
Object subclass: #GameOfLife
Object subclass: #GameOfLife
instanceVariableNames: 'aliveCells boardSize'
instanceVariableNames: 'aliveCells boardSize'
Line 15,366: Line 15,366:
numberOfAliveNeighborsOf: aCell
numberOfAliveNeighborsOf: aCell
^aCell eightNeighbors count: [ :aNeighbor | self isAlive: aNeighbor ]
^aCell eightNeighbors count: [ :aNeighbor | self isAlive: aNeighbor ]
</lang>
</syntaxhighlight>
The implementation was developed using TDD. This are the tests used to implement it.
The implementation was developed using TDD. This are the tests used to implement it.
<syntaxhighlight lang="smalltalk">
<lang Smalltalk>
TestCase subclass: #GameOfLifeTest
TestCase subclass: #GameOfLifeTest
instanceVariableNames: ''
instanceVariableNames: ''
Line 15,429: Line 15,429:
raise: Error - MessageNotUnderstood
raise: Error - MessageNotUnderstood
withMessageText: 'Cell 1@4 out of range'
withMessageText: 'Cell 1@4 out of range'
</syntaxhighlight>
</lang>
If you want to have a visual representation, here is a view for it:
If you want to have a visual representation, here is a view for it:
<lang smalltalk>
<syntaxhighlight lang="smalltalk">
ImageMorph subclass: #GameOfLifeView
ImageMorph subclass: #GameOfLifeView
instanceVariableNames: 'game'
instanceVariableNames: 'game'
Line 15,475: Line 15,475:
self showBoard.
self showBoard.
self redrawNeeded.
self redrawNeeded.
</syntaxhighlight>
</lang>


=={{header|SQL}}==
=={{header|SQL}}==
Line 15,481: Line 15,481:


{{works with|Oracle}}
{{works with|Oracle}}
<lang sql>
<syntaxhighlight lang="sql">
-- save these lines in a file called
-- save these lines in a file called
-- setupworld.sql
-- setupworld.sql
Line 15,598: Line 15,598:
from output
from output
order by y desc;
order by y desc;
</syntaxhighlight>
</lang>


<pre>
<pre>
Line 15,630: Line 15,630:
{{trans|Rust}}
{{trans|Rust}}


<lang swift>struct Cell: Hashable {
<syntaxhighlight lang="swift">struct Cell: Hashable {
var x: Int
var x: Int
var y: Int
var y: Int
Line 15,724: Line 15,724:


print("Glider: ")
print("Glider: ")
col.run(iterations: 20)</lang>
col.run(iterations: 20)</syntaxhighlight>


{{out}}
{{out}}
Line 15,962: Line 15,962:
=={{header|SystemVerilog}}==
=={{header|SystemVerilog}}==
Note using non-blocking assignments, so that the code behaves as if every cell is updated in parallel on each clock edge. (I didn't need to use a clock here, but doing so looks more like standard verilog coding that is familiar to hardware designers).
Note using non-blocking assignments, so that the code behaves as if every cell is updated in parallel on each clock edge. (I didn't need to use a clock here, but doing so looks more like standard verilog coding that is familiar to hardware designers).
<lang SystemVerilog>module gol;
<syntaxhighlight lang="systemverilog">module gol;


parameter NUM_ROWS = 20;
parameter NUM_ROWS = 20;
Line 15,990: Line 15,990:
end
end


endmodule</lang>
endmodule</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5


proc main {} {
proc main {} {
Line 16,072: Line 16,072:
}
}


main</lang>
main</syntaxhighlight>
<pre style='height:30ex; overflow:scroll'>blinker generation 1:
<pre style='height:30ex; overflow:scroll'>blinker generation 1:
. # .
. # .
Line 16,116: Line 16,116:
{{works with|Korn Shell}}
{{works with|Korn Shell}}
{{works with|Z Shell}}
{{works with|Z Shell}}
<lang bash># Shells only have 1-dimensional arrays, so each row is one string
<syntaxhighlight lang="bash"># Shells only have 1-dimensional arrays, so each row is one string
function main {
function main {
typeset blinker=(000 111 000)
typeset blinker=(000 111 000)
Line 16,234: Line 16,234:
}
}


main "$@"</lang>
main "$@"</syntaxhighlight>


{{Out}}
{{Out}}
Line 16,264: Line 16,264:
sequence of n boards evolving from it.
sequence of n boards evolving from it.


<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


Line 16,271: Line 16,271:
neighborhoods = ~&thth3hthhttPCPthPTPTX**K7S+ swin3**+ swin3@hNSPiCihNCT+ --<0>*+ 0-*
neighborhoods = ~&thth3hthhttPCPthPTPTX**K7S+ swin3**+ swin3@hNSPiCihNCT+ --<0>*+ 0-*


evolve "n" = next"n" rule**+ neighborhoods</lang>
evolve "n" = next"n" rule**+ neighborhoods</syntaxhighlight>
test program:
test program:
<lang Ursala>blinker =
<syntaxhighlight lang="ursala">blinker =


(==`O)**t -[
(==`O)**t -[
Line 16,291: Line 16,291:
#show+
#show+


examples = mat0 ~&?(`O!,`+!)*** evolve3(blinker)-- evolve5(glider)</lang>
examples = mat0 ~&?(`O!,`+!)*** evolve3(blinker)-- evolve5(glider)</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:30ex;overflow:scroll">+++
<pre style="height:30ex;overflow:scroll">+++
Line 16,347: Line 16,347:
Two <tt>Replace</tt> commands are then used to change characters into '.' or 'O' to represent dead and living cells in the new generation.
Two <tt>Replace</tt> commands are then used to change characters into '.' or 'O' to represent dead and living cells in the new generation.


<lang vedit>IT("Generation 0 ") IN
<syntaxhighlight lang="vedit">IT("Generation 0 ") IN
IT(".O.") IN
IT(".O.") IN
IT(".O.") IN
IT(".O.") IN
Line 16,404: Line 16,404:
Ins_Char(Cur_Char+1,OVERWRITE)
Ins_Char(Cur_Char+1,OVERWRITE)
}
}
Return</lang>
Return</syntaxhighlight>


{{out}}
{{out}}
Line 16,424: Line 16,424:
=={{header|Wortel}}==
=={{header|Wortel}}==
Mapping over a matrix.
Mapping over a matrix.
<lang wortel>@let {
<syntaxhighlight lang="wortel">@let {
life &m ~!* m &[a y] ~!* a &[v x] @let {
life &m ~!* m &[a y] ~!* a &[v x] @let {
neigh @sum [
neigh @sum [
Line 16,447: Line 16,447:
!^life 2 blinker
!^life 2 blinker
]]
]]
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[
<pre>[
Line 16,468: Line 16,468:


Different solution by using functions that operate on matrices.
Different solution by using functions that operate on matrices.
<lang wortel>@let {
<syntaxhighlight lang="wortel">@let {
; Translation of the APL game of life (http://catpad.net/michael/apl/).
; Translation of the APL game of life (http://catpad.net/michael/apl/).
life &m @let {
life &m @let {
Line 16,520: Line 16,520:
!^life 2 blinker
!^life 2 blinker
]]
]]
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[
<pre>[
Line 16,542: Line 16,542:
=={{header|VBScript}}==
=={{header|VBScript}}==
I have used ANSI escape codes, so the program will not whork from W2000 to W8.1, where Microsoft did see fit to remove support to these codes. The game wraps around at borders, so the gliders are always alive. Must be invoked from cscript.
I have used ANSI escape codes, so the program will not whork from W2000 to W8.1, where Microsoft did see fit to remove support to these codes. The game wraps around at borders, so the gliders are always alive. Must be invoked from cscript.
<syntaxhighlight lang="vb">
<lang vb>
option explicit
option explicit
const tlcr=3, tlcc=3
const tlcr=3, tlcc=3
Line 16,628: Line 16,628:
next
next
end function
end function
</syntaxhighlight>
</lang>
<pre>
<pre>
Conway's Game of Life
Conway's Game of Life
Line 16,652: Line 16,652:
</pre>
</pre>
A fast version using a thechnique from Abrash's Black Book. Set your console to 34 rows minimum, as it uses a 32x32 cells world
A fast version using a thechnique from Abrash's Black Book. Set your console to 34 rows minimum, as it uses a 32x32 cells world
<syntaxhighlight lang="vb">
<lang vb>
option explicit
option explicit
const pix="##"
const pix="##"
Line 16,758: Line 16,758:
nextgen=nextgen+1
nextgen=nextgen+1
end sub
end sub
</syntaxhighlight>
</lang>


=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Go}}
{{trans|Go}}
<lang vlang>import rand
<syntaxhighlight lang="vlang">import rand
import strings
import strings
import time
import time
Line 16,859: Line 16,859:
time.sleep(time.second / 30)
time.sleep(time.second / 30)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 16,880: Line 16,880:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ecmascript>import "random" for Random
<syntaxhighlight lang="ecmascript">import "random" for Random
import "timer" for Timer
import "timer" for Timer


Line 16,984: Line 16,984:
}
}
System.print()
System.print()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 17,083: Line 17,083:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>def M=3; \array size
<syntaxhighlight lang="xpl0">def M=3; \array size
char NowGen(M+2, M+2), \size with surrounding borders
char NowGen(M+2, M+2), \size with surrounding borders
NewGen(M+2, M+2);
NewGen(M+2, M+2);
Line 17,114: Line 17,114:
I:= NowGen; NowGen:= NewGen; NewGen:= I; \swap arrays
I:= NowGen; NowGen:= NewGen; NewGen:= I; \swap arrays
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 17,133: Line 17,133:
=={{header|XSLT}}==
=={{header|XSLT}}==
So when the following templates
So when the following templates
<lang xml><xsl:template match="/table">
<syntaxhighlight lang="xml"><xsl:template match="/table">
<table>
<table>
<xsl:apply-templates />
<xsl:apply-templates />
Line 17,181: Line 17,181:
<xsl:template name="live">
<xsl:template name="live">
<td>X</td>
<td>X</td>
</xsl:template></lang>
</xsl:template></syntaxhighlight>
are applied against the document
are applied against the document
<lang html><table>
<syntaxhighlight lang="html"><table>
<tr><td>_</td><td>X</td><td>_</td></tr>
<tr><td>_</td><td>X</td><td>_</td></tr>
<tr><td>_</td><td>X</td><td>_</td></tr>
<tr><td>_</td><td>X</td><td>_</td></tr>
<tr><td>_</td><td>X</td><td>_</td></tr>
<tr><td>_</td><td>X</td><td>_</td></tr>
</table></lang>
</table></syntaxhighlight>
then the transformed XML document contains the new universe evolved by one tick:
then the transformed XML document contains the new universe evolved by one tick:
<lang html><table>
<syntaxhighlight lang="html"><table>
<tr><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td></tr>
<tr><td>X</td><td>X</td><td>X</td></tr>
<tr><td>X</td><td>X</td><td>X</td></tr>
<tr><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td></tr>
</table></lang>
</table></syntaxhighlight>


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
Line 17,203: Line 17,203:
if INITLINES is set to 0 the code will show the blinker
if INITLINES is set to 0 the code will show the blinker


<lang z80>;MSX Bios calls
<syntaxhighlight lang="z80">;MSX Bios calls
CHPUT equ 000A2H ;print character A
CHPUT equ 000A2H ;print character A
CHGET equ 0009FH ;wait for keyboard input
CHGET equ 0009FH ;wait for keyboard input
Line 17,359: Line 17,359:
;force 16k ROM size binary output
;force 16k ROM size binary output
EndOfCode dc 0x8000 - EndOfCode, 0xFF
EndOfCode dc 0x8000 - EndOfCode, 0xFF
end</lang>
end</syntaxhighlight>


=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{output?|Yabasic}}
{{output?|Yabasic}}
{{trans|BASIC256}}
{{trans|BASIC256}}
<lang Yabasic>// Conway's_Game_of_Life
<syntaxhighlight lang="yabasic">// Conway's_Game_of_Life
X = 59 : Y = 35 : H = 4
X = 59 : Y = 35 : H = 4
Line 17,433: Line 17,433:
else
else
print "Stabilized in ", s-2, " iterations"
print "Stabilized in ", s-2, " iterations"
end if</lang>
end if</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>class Life{
<syntaxhighlight lang="zkl">class Life{
fcn init(n, r1,c1, r2,c2, etc){
fcn init(n, r1,c1, r2,c2, etc){
var N=n, cells=Data(n*n), tmp=Data(n*n),
var N=n, cells=Data(n*n), tmp=Data(n*n),
Line 17,470: Line 17,470:
}
}
fcn dance(n=300){ do(n){ toAnsi().print(); Atomic.sleep(0.2); cycle(); } }
fcn dance(n=300){ do(n){ toAnsi().print(); Atomic.sleep(0.2); cycle(); } }
}</lang>
}</syntaxhighlight>
The data structure is a Data, which is a linear block of bytes.
The data structure is a Data, which is a linear block of bytes.
<lang zkl>cells:=Life(4, 0,1, 1,1, 2,1); // blinker
<syntaxhighlight lang="zkl">cells:=Life(4, 0,1, 1,1, 2,1); // blinker
do(3){ cells.println("="*4); cells.cycle(); }
do(3){ cells.println("="*4); cells.cycle(); }


cells:=Life(30, 0,1, 1,2, 2,0, 2,1, 2,2); // glider
cells:=Life(30, 0,1, 1,2, 2,0, 2,1, 2,2); // glider
cells.dance(100);</lang>
cells.dance(100);</syntaxhighlight>
{{out}}
{{out}}
Just the glider (reformatted), if you have an ANSI terminal (eg xterm), you'll see the glider moving down the screen.
Just the glider (reformatted), if you have an ANSI terminal (eg xterm), you'll see the glider moving down the screen.
Line 17,488: Line 17,488:


=={{header|ZPL}}==
=={{header|ZPL}}==
<lang ZPL>program Life;
<syntaxhighlight lang="zpl">program Life;


config var
config var
Line 17,515: Line 17,515:
TW := (TW & NN = 2) | ( NN = 3);
TW := (TW & NN = 2) | ( NN = 3);
until !(|<< TW);
until !(|<< TW);
end;</lang>
end;</syntaxhighlight>


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
Line 17,521: Line 17,521:


The ZX Spectrum was shipped with a demo tape called ''Horizons'', which included an implementation of Life; however, it relied on machine code.
The ZX Spectrum was shipped with a demo tape called ''Horizons'', which included an implementation of Life; however, it relied on machine code.
<lang zxbasic>10 REM Initialize
<syntaxhighlight lang="zxbasic">10 REM Initialize
20 LET w=32*22
20 LET w=32*22
30 DIM w$(w): DIM n$(w)
30 DIM w$(w): DIM n$(w)
Line 17,541: Line 17,541:
190 PRINT AT 0,0;w$
190 PRINT AT 0,0;w$
200 LET w$=n$
200 LET w$=n$
210 GO TO 80</lang>
210 GO TO 80</syntaxhighlight>