Conway's Game of Life: Difference between revisions

no edit summary
No edit summary
 
(40 intermediate revisions by 19 users not shown)
Line 36:
=={{header|11l}}==
{{trans|Python}}
<langsyntaxhighlight lang="11l">V cellcountx = 6
V cellcounty = 5
V celltable = [(1, 2) = 1,
Line 62:
col-1..col+1, (r, c) -> :universe[(r, c)]))
), 0)
universe = nextgeneration</langsyntaxhighlight>
 
===More optimal solution===
<langsyntaxhighlight lang="11l">V cellcountx = 6
V cellcounty = 5
V universe = [[0B] * cellcountx] * cellcounty
Line 104:
s += universe[row+1][col+1]
nextgeneration[row][col] = I universe[row][col] {s C 2..3} E s == 3
universe = nextgeneration</langsyntaxhighlight>
 
{{out}}
Line 140:
{{works with|http://www.6502asm.com/ 6502asm.com|1.2}}
 
<langsyntaxhighlight lang="6502asm">randfill: stx $01 ;$200 for indirect
ldx #$02 ;addressing
stx $02
Line 262:
lda $01
sta $03
rts</langsyntaxhighlight>
 
=={{header|68000 Assembly}}==
Line 278:
* popLong = <tt>MOVE.L (SP)+,___</tt>
 
<langsyntaxhighlight lang="68000devpac">include "\SrcALL\68000_Macros.asm"
;Ram Variables
Cursor_X equ $00FF0000 ;Ram for Cursor Xpos
Line 755:
DC.B $80 ;23 DMA source address high (C=CMD) CCHHHHHH
VDPSettingsEnd:
even</langsyntaxhighlight>
{{out}}
[https://ibb.co/VN4KbSL Screenshot of emulator]
Line 762:
{{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
<syntaxhighlight lang="abap">
<lang ABAP>
*&---------------------------------------------------------------------*
*& Report ZCONWAYS_GAME_OF_LIFE
Line 965:
leave list-processing.
endcase.
</syntaxhighlight>
</lang>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun print-row (row)
(if (endp row)
nil
Line 1,072:
nil
(progn$ (print-grid grid)
(conway (conway-step grid) (1- steps)))))</langsyntaxhighlight>
 
{{out}}
Line 1,092:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">
WITH Ada.Text_IO; USE Ada.Text_IO;
Line 1,148:
Put_And_Step_Generation (3, "Blinker", Blinker);
Put_And_Step_Generation (5, "Glider", Glider);
END Life;</langsyntaxhighlight>
The solution uses one cell thick border around square Petri dish
as uninhabited dire land. This simplifies computations of neighborhood.
Line 1,211:
=={{header|ALGOL 68}}==
See [[Conway's Game of Life/ALGOL 68]]
 
=={{header|Amazing Hopper}}==
<p>El programa genera el algoritmo en modo texto.</p>
<p>Adaptado del programa "Conway's Game of Life" de Vishal Nagda, en Hithub</p>
<p>https://github.com/vishalnagda1/CONWAYs-Game-of-Life-C/blob/master/game_of_life.c</p>
<syntaxhighlight lang="text">
#include <jambo.h>
 
#define SIZER 90
#define SIZEC 120
 
Main
Dim (SIZER, SIZEC) as zeros 'grid, neighbour_count'
Dim (SIZER, SIZEC) as fill '" ",disp grid'
c=0, Let( c := Utf8(Chr(254)))
moi=0, moj=0, poi=0, poj=0
 
m={}
Set ' 0,1,1 ' Apnd row 'm'
Set ' 1,1,0 ' Apnd row 'm'
Set ' 0,1,0 ' Apnd row 'm'
[44:46, 59:61] Set 'm', Put 'grid'
Clr all marks
i=0, j=0
Tok sep '""'
Locate (1,1)
Loop
i=1
Iterator ( ++i, Less equal(i,SIZER),\
j=1, Iterator ( ++j, Less equal(j,SIZEC), \
Set 'i,j', Gosub 'Count NBR', [i,j], Put 'neighbour_count' ) )
 
i=1
Loop if( Less equal(i,SIZER) )
j=1
Loop if( Less equal(j,SIZEC) )
[i,j]
If ( Get 'grid' )
Get 'neighbour_count'
When ( Out of range including '1,4' ) {
Set '0," "', Put 'disp grid', Put 'grid'
}
Else
Get 'neighbour_count'
When ( Is equal to '3' ) {
Set '1,c', Put 'disp grid', Put 'grid'
}
End If
++j
Back
++i
Back
Clr all marks
Print table 'disp grid'
Break if ( Key pressed )
 
Back
Pause
End
 
Subrutines
 
Define 'Count NBR, i, j'
n_count = 0
 
When ( Must be( Minus one 'i' ---Backup to 'moi'---, Minus one 'j' ---Backup to 'moj'--- ) ) {
 
When ( [moi,moj]Get 'grid' ) {
++n_count
}
}
 
Plus one 'j', Move to 'poj'
 
When ( moi ) {
When ( [ moi, j ] Get 'grid' ) {
++n_count
}
When ( Less equal( poj, SIZEC )) {
When ( [ moi, poj] Get 'grid' ) {
++n_count
}
}
}
 
When ( moj ) {
When( [i, moj] Get 'grid' ) {
++n_count
}
}
 
When ( Less equal ( poj, SIZEC ) ){
When( [i, poj] Get 'grid' ) {
++n_count
}
}
 
When ( Less equal (Plus one 'i' ---Backup to 'poi'---, SIZER ) ) {
 
When ( [ poi, j] Get 'grid' ) {
++n_count
}
When ( Less equal ( poj, SIZEC) ) {
When ( [poi, poj] Get 'grid' ) {
++n_count
}
}
When ( moj ){
When ([poi, moj] Get 'grid' ){
++n_count
}
}
}
Return 'n_count'
 
</syntaxhighlight>
{{out}}
<pre>
La llamada se realiza desde terminal, con el programa "rxvt" de Linux, para adaptar la terminal a los pixeles y dimensiones adecuados.
 
Llamada:
rxvt -g 270x100 -fn "xft:FantasqueSansMono-Regular:pixelsize=3" -e hopper jm/gamelife.jambo
</pre>
 
[[File:Captura_de_pantalla_de_2022-10-07_04-37-57.png]]
 
<p>Version 2</p>
<p>Me di cuenta de que la subrutina "Count NBR" era un poco lenta, y además, una función que cuente los vecinos en un radio dado, me es útil para hacer juegos, por lo que incluí esa función dentro de las funciones de HOPPER.</p>
<p>Además, reescribí el programa "a la Hopper", como debió ser desde un principio.</p>
<syntaxhighlight lang="text">
#include <jambo.h>
#define SIZER 90
#define SIZEC 120
 
Main
Cls
Hide cursor
 
Dim (SIZER, SIZEC), as zeros 'grid, neighbour_count'
Dim (SIZER, SIZEC), as fill '" ",disp grid'
c=0 , Let( c := Utf8(Chr(254)))
 
m={}
Set ' 0,1,1 ' Apend row to 'm'
Set ' 1,1,0 ' Apend row to 'm'
Set ' 0,1,0 ' Apend row to 'm'
[44:46, 59:61] Set 'm', Put 'grid'
Clr all marks
radio=1, r=0
 
Tok sep '""'
 
Locate (1,1)
Loop
i=1
Iterator ( ++i, Less equal(i,SIZER),\
j=1, Iterator ( ++j, Less equal(j,SIZEC), \
[i,j], Neighbour count (grid,radio), Put 'neighbour_count' ) )
Cartesian ( Greater equal(grid, 1)---Back up to 'r'--- Mul by 'neighbour_count';\
Out of range including '1,4' )
Get range, Set '0," "', Put 'disp grid', Put 'grid', Forget
 
Cartesian ( Not( r ); Mul by 'neighbour_count'; Is equal to '3' )
Get range, Set '1,c', Put 'disp grid', Put 'grid', Forget
Clr range
 
Clr all marks
Print table 'disp grid'
Break if ( Key pressed )
Back
Pause
Show cursor
End
 
</syntaxhighlight>
{{out}}
La salida es la misma, pero ahora va mucho más rápido... parecen estrellitas explotando :D
 
=={{header|APL}}==
[[GNU APL]] (from Wikipedia: https://aplwiki.com/wiki/John_Scholes%27_Conway%27s_Game_of_Life#Translations)<syntaxhighlight lang="apl">
[http://www.dyalog.com/dfnsdws/c_life.htm APL2 (Dialog) Example in one line]
Life←{↑↑1 ⍵∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵}
m ← 5 5⍴(0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0)
m
0 0 0 0 0
0 0 0 0 0
0 1 1 1 0
0 0 0 0 0
0 0 0 0 0
Life m
0 0 0 0 0
0 0 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
Life Life m
0 0 0 0 0
0 0 0 0 0
0 1 1 1 0
0 0 0 0 0
0 0 0 0 0
</syntaxhighlight>
 
 
[http://www.dyalog.com/dfnsdws/c_life.htm APL2 (Dyalog) Example in one line]
 
APL \ 1130 example (very old APL dialect via simulator)<br>
Line 1,221 ⟶ 1,436:
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>
<syntaxhighlight lang="text">
∇LIFE[⎕]∇
[0] NG←LIFE CG;W
Line 1,248 ⟶ 1,463:
0 0 0 0 0
 
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
Line 1,254 ⟶ 1,469:
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.
 
<langsyntaxhighlight 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 scripting additions
Line 1,431 ⟶ 1,646:
return universe
end newUniverse</langsyntaxhighlight>
 
In conjunction with the above, this fulfills the task as set:
 
<langsyntaxhighlight lang="applescript">on RCTask(seed, dimensions, maxGenerations)
-- Create a universe and start a list with its initial state.
set universe to newUniverse(seed, dimensions)
Line 1,456 ⟶ 1,671:
 
-- Return text containing the original and three generations of a "blinker" in a 3 x 3 grid.
return RCTask("***", {3, 3}, 3)</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">"
■■■
Line 1,481 ⟶ 1,696:
Generation 3
-----"</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="applescript">on runGame(seed, dimensions, maxGenerations)
-- Create an RTF file set up for Menlo-Regular 12pt, half spacing, and a reasonable window size.
set fontName to "Menlo-Regular"
Line 1,538 ⟶ 1,753:
**"
-- Run for 500 generations in a 100 x 100 universe.
runGame(GosperGliderGun, {100, 100}, 500)</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
Line 1,544 ⟶ 1,759:
{{works with|TI-Nspire}}
 
<langsyntaxhighlight ARMlang="arm Assemblyassembly"> .string "PRG"
 
lcd_ptr .req r4
Line 1,640 ⟶ 1,855:
offsets:
.hword -321, -320, -319, -1, 1, 319, 320, 321
</syntaxhighlight>
</lang>
http://i.imgur.com/kV9RirP.gif
 
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=143 discussion]
<langsyntaxhighlight lang="autohotkey">rows := cols := 10 ; set grid dimensions
i = -1,0,1, -1,1, -1,0,1 ; neighbors' x-offsets
j = -1,-1,-1, 0,0, 1,1,1 ; neighbors' y-offsets
Line 1,684 ⟶ 1,899:
 
GuiClose: ; exit when GUI is closed
ExitApp</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 1,692 ⟶ 1,907:
running for 220 generations,
using [http://en.wikipedia.org/wiki/ANSI_escape_code ANSI escape-codes] for output to terminal:
<syntaxhighlight lang="awk">
<lang AWK>
BEGIN {
c=220; d=619; i=10000;
Line 1,718 ⟶ 1,933:
}
}
</syntaxhighlight>
</lang>
 
{{out}} Finally:
Line 1,749 ⟶ 1,964:
 
This implementation uses the full screen buffer instead of a 3x3 grid. This naive, unoptimized version gets less than 1 FPS.
<langsyntaxhighlight lang="axe">Full
 
While getKey(0)
Line 1,792 ⟶ 2,007:
End
End
Return</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 1,802 ⟶ 2,017:
You can find it in the [[Galton box animation#BASIC256|Galton box animation]] example.
 
<langsyntaxhighlight lang="basic256"># Conway's_Game_of_Life
 
X = 59 : Y = 35 : H = 4
Line 1,810 ⟶ 2,025:
 
dim c(X,Y) : dim cn(X,Y) : dim cl(X,Y)
</langsyntaxhighlight><syntaxhighlight lang ="basic256">
# 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
Line 1,874 ⟶ 2,089:
else
print "Stabilized in "+(s-2)+" iterations"
end if</langsyntaxhighlight>
{{out}}
<pre>
Line 1,882 ⟶ 2,097:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> dx% = 64
dy% = 64
DIM old&(dx%+1,dy%+1), new&(dx%+1,dy%+1)
Line 1,916 ⟶ 2,131:
SWAP old&(), new&()
WAIT 30
UNTIL FALSE</langsyntaxhighlight>
{{out}}
<BR>
Line 1,923 ⟶ 2,138:
==={{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}}
<langsyntaxhighlight lang="casiobasic">Filename:JG VIDA
Cls
20→D
Line 1,998 ⟶ 2,213:
Next
Goto 1
</syntaxhighlight>
</lang>
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">' FreeBASIC Conway's Game of Life
' May 2015
' 07-10-2016 cleanup/little changes
Line 2,171 ⟶ 2,386:
Print " Press any key to exit "
Sleep
End</langsyntaxhighlight>
 
==={{header|GFA Basic}}===
 
<syntaxhighlight lang="text">
'
' Conway's Game of Life
Line 2,319 ⟶ 2,534:
CLOSEW 1
RETURN
</syntaxhighlight>
</lang>
 
==={{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.
 
<langsyntaxhighlight lang="gwbasic">10 REM Conway's Game of Life
20 REM 30x30 grid, padded with zeroes as the boundary
30 DIM WORLD(31, 31, 1)
Line 2,377 ⟶ 2,592:
520 NEXT YY
530 NEXT XX
540 RETURN</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
It will run slow for grids above say 25!
<syntaxhighlight lang="lb">
<lang lb>
nomainwin
 
Line 2,450 ⟶ 2,665:
close #w
end
</syntaxhighlight>
</lang>
 
==={{header|MSX Basic}}===
<langsyntaxhighlight lang="basic">
10 DEFINT A-Z
20 DIM L(16,16), N(16,16)
Line 2,498 ⟶ 2,713:
1350 G=G+1
1360 GOTO 1090
</syntaxhighlight>
</lang>
 
==={{header|PureBasic}}===
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
Define.i x, y ,Xmax ,Ymax ,N
Xmax = 13 : Ymax = 20
Line 2,556 ⟶ 2,771:
Until Inkey() <> ""
PrintN("Press any key to exit"): Repeat: Until Inkey() <> ""</langsyntaxhighlight>
'''Sample output:'''<br>
[[File:Game-of-life-PureBasic.gif‎]]
Line 2,566 ⟶ 2,781:
Yo solo lo transcrito y comento al español.<br>
I just transcribed it and comment it in Spanish.
<langsyntaxhighlight lang="qbasic">SCREEN 9, 0, 0, 1
 
RANDOMIZE TIMER
Line 2,663 ⟶ 2,878:
LOOP UNTIL y > 80
PCOPY 0, 1
LOOP WHILE INKEY$ = ""</langsyntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Line 2,669 ⟶ 2,884:
 
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>.
<langsyntaxhighlight lang="basic">1000 LET M=LEN L$(1)
1010 DIM N$(M,M)
1020 FOR I=0 TO M+1
Line 2,705 ⟶ 2,920:
1340 NEXT I
1350 LET G=G+1
1360 GOTO 1090</langsyntaxhighlight>
To run the blinker, add this code:
<langsyntaxhighlight lang="basic">10 DIM L$(3,3)
20 LET L$(1)="000"
30 LET L$(2)="111"
40 LET L$(3)="000"</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="basic">10 DIM L$(16,16)
20 FOR I=1 TO 16
30 FOR J=1 TO 16
Line 2,720 ⟶ 2,935:
50 IF RND>=.7 THEN LET L$(I,J)="1"
60 NEXT J
70 NEXT I</langsyntaxhighlight>
A screenshot is [http://www.edmundgriffiths.com/zx81liferandom.jpg here].
 
==={{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.
<langsyntaxhighlight lang="ti83b"> PROGRAM:CONWAY
:While 1
:For(X,2,9,1)
Line 2,746 ⟶ 2,961:
:[B]→[A]
: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).
<langsyntaxhighlight lang="ti83b">PROGRAM:PIC2LIFE
:For(I,0,17,1)
:For(J,0,9,1)
Line 2,754 ⟶ 2,969:
:End
:End
</syntaxhighlight>
</lang>
 
==={{header|TI-89 BASIC}}===
Line 2,761 ⟶ 2,976:
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.
 
<langsyntaxhighlight lang="ti89b">Define life(pattern) = Prgm
Local x,y,nt,count,save,xl,yl,xh,yh
Define nt(y,x) = when(pxlTest(y,x), 1, 0)
Line 2,836 ⟶ 3,051:
setGraph("Grid", save[2])
setGraph("Labels", save[3])
EndPrgm</langsyntaxhighlight>
 
=={{header|Batch File}}==
Line 2,848 ⟶ 3,063:
If no parameters are parsed, it defaults to 5 iterations of the blinking example.
 
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 2,957 ⟶ 3,172:
 
exit /b
</syntaxhighlight>
</lang>
{{out}}
Blinking example:
Line 3,053 ⟶ 3,268:
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.
 
<langsyntaxhighlight 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<
>6*`*#v_55+-#v_p10g1+10p>^pg08g07+gp08:+8/*8*65\p07:<^ >/10g-50g^87>+1+:01p/8/v
Line 3,060 ⟶ 3,275:
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
:p00%g04:-1<<$_^#!:pg01%"P"\*8%8gp<< ^3\%g04+g04-1+g00%3:%9+4:-1p06\<90p01/g04</langsyntaxhighlight>
 
{{in}}
Line 3,097 ⟶ 3,312:
=={{header|Brat}}==
 
<langsyntaxhighlight lang="brat">width = 3
height = 3
rounds = 3
Line 3,157 ⟶ 3,372:
p
step
}</langsyntaxhighlight>
 
{{out}}
Line 3,175 ⟶ 3,390:
 
=={{header|BQN}}==
<langsyntaxhighlight lang="bqn">Life←{
r←¯1(⌽⎉1)¯1⌽(2+≢𝕩)↑𝕩
s←∨´ (1∾<r) ∧ 3‿4 = <+´⥊ ¯1‿0‿1 (⌽⎉1)⌜ ¯1‿0‿1 ⌽⌜ <r
Line 3,182 ⟶ 3,397:
 
blinker←>⟨0‿0‿0,1‿1‿1,0‿0‿0⟩
(<".#") ⊏¨˜ Life⍟(↕3) blinker</langsyntaxhighlight>
{{out}}
<pre>┌─
Line 3,194 ⟶ 3,409:
=={{header|C}}==
Play game of life on your console: <code>gcc -std=c99 -Wall game.c; ./a.out [width] [height]</code>
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Line 3,249 ⟶ 3,464:
if (h <= 0) h = 30;
game(w, h);
}</langsyntaxhighlight>
Also see [[Conway's Game of Life/C]]
 
===C for Arduino===
Play game of life on your arduino (using FastLED) - based on the C example.
<syntaxhighlight lang="c">
<lang C>
#include <FastLED.h>
 
Line 3,329 ⟶ 3,544:
FastLED.delay(1000/FRAMERATE);
}
</syntaxhighlight>
</lang>
 
===C for Arduino===
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>
Line 3,421 ⟶ 3,636:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Text;
Line 3,601 ⟶ 3,816:
}
 
</syntaxhighlight>
</lang>
 
Output:
<syntaxhighlight lang="text">
Frame 1: Frame 2: Frame 3:
██
██████ ██ ██████
██
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
 
Because Nobody else included a version with Graphics, Here is a simple implementation using SFML for graphic rendering
<syntaxhighlight lang="c">
#include <iostream>
#include <vector>
#include <SFML/Graphics.hpp>
#include <thread>
#include <chrono>
using namespace std;
 
class Life {
private:
int ticks;
bool pass;
int height;
int width;
bool **board;
bool **buffer;
vector<pair<float,float>> liveCoords;
void init();
void lives(int x, int y);
void dies(int x, int y);
bool isAlive(bool **curr, int x, int y);
int checkNeighbors(bool **curr, int x, int y);
void evaluatePosition(bool** curr, int x, int y);
public:
Life(int w = 100, int h = 50, int seed = 1337);
Life(const Life& life);
~Life();
vector<pair<float,float>> doTick();
Life& operator=(const Life& life);
};
void Life::init() {
board = new bool*[height];
buffer = new bool*[height];
for (int y = 0; y < height; y++) {
board[y] = new bool[width];
buffer[y] = new bool[width];
for (int x = 0; x < width; x++) {
board[y][x] = false;
buffer[y][x] = false;
}
}
}
 
Life::Life(int w, int h, int seed) {
width = w;
height = h;
init();
for (int i = 0; i < seed; i++) {
board[rand() % height][rand() % width] = true;
}
pass = true;
}
 
Life::Life(const Life& life) {
width = life.width;
height = life.height;
init();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
board[y][x] = life.board[y][x];
buffer[y][x] = life.buffer[y][x];
}
}
}
 
Life& Life::operator=(const Life& life) {
width = life.width;
height = life.height;
init();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
board[y][x] = life.board[y][x];
buffer[y][x] = life.buffer[y][x];
}
}
return *this;
}
 
Life::~Life() {
for (int i = 0; i < height; i++) {
delete [] board[i];
delete [] buffer[i];
}
delete [] board;
delete [] buffer;
}
 
vector<pair<float,float>> Life::doTick() {
liveCoords.clear();
bool **currentGeneration = pass ? board:buffer;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
evaluatePosition(currentGeneration, x, y);
}
}
pass = !pass;
ticks++;
return liveCoords;
}
 
 
bool Life::isAlive(bool **curr, int x, int y) {
return curr[y][x];
}
int Life::checkNeighbors(bool **curr, int x, int y) {
int lc = 0;
int dx[8] = {-1, 0, 1,1,1,-1, 0,-1};
int dy[8] = {-1,-1,-1,0,1, 1, 1, 0};
for (int i = 0; i < 8; i++) {
int nx = ((dx[i]+x)+width) % width;
int ny = ((dy[i]+y)+height) % height;
lc += isAlive(curr, nx, ny);
}
return lc;
}
void Life::lives(int x, int y) {
if (!pass) {
board[y][x] = true;
} else {
buffer[y][x] = true;
}
liveCoords.push_back(make_pair((float)x,(float)y));
}
void Life::dies(int x, int y) {
if (!pass) {
board[y][x] = false;
} else {
buffer[y][x] = false;
}
}
void Life::evaluatePosition(bool** generation, int x, int y) {
int lc = checkNeighbors(generation, x, y);
if (isAlive(generation, x, y)) {
if (lc == 2 || lc == 3) {
lives(x, y);
} else {
dies(x, y);
}
} else {
if (lc == 3) {
lives(x, y);
} else {
dies(x, y);
}
}
}
 
class App {
private:
void sleep();
void drawLiveCells();
void render();
void handleEvent(sf::Event& event);
void saveDisplay();
int width;
int height;
Life life;
bool isRecording;
int tick;
sf::RenderWindow* window;
sf::RenderTexture* texture;
public:
App(int w = 100, int h = 50);
void start();
};
 
App::App(int w, int h) {
height = h;
width = w;
life = Life(width, height);
isRecording = false;
tick = 0;
}
 
void App::start() {
sf::Event event;
window = new sf::RenderWindow(sf::VideoMode(width*10, height*10), "The Game of Life");
texture = new sf::RenderTexture();
texture->create(width*10, height*10);
window->setFramerateLimit(60);
while (window->isOpen()) {
while (window->pollEvent(event)) {
handleEvent(event);
}
render();
tick++;
}
delete window;
delete texture;
}
 
void App::handleEvent(sf::Event& event) {
if (event.type == sf::Event::Closed) {
window->close();
}
if (event.type == sf::Event::KeyPressed) {
switch (event.key.code) {
case sf::Keyboard::R:
life = Life(width, height);
break;
case sf::Keyboard::S:
isRecording = !isRecording;
break;
case sf::Keyboard::Q:
case sf::Keyboard::Escape:
window->close();
break;
default:
break;
}
}
}
 
void App::sleep() {
std::this_thread::sleep_for(350ms);
}
 
void App::drawLiveCells() {
float XSCALE = 10.0, YSCALE = 10.0;
sf::RectangleShape rect;
rect.setSize(sf::Vector2f(XSCALE, YSCALE));
rect.setFillColor(sf::Color::Green);
auto coords = life.doTick();
texture->clear(sf::Color::Black);
for (auto m : coords) {
rect.setPosition(m.first*XSCALE, m.second*YSCALE);
texture->draw(rect);
}
texture->display();
}
 
void App::render() {
drawLiveCells();
window->clear();
sf::Sprite sprite(texture->getTexture());
window->draw(sprite);
window->display();
if (isRecording) saveDisplay();
sleep();
}
 
void App::saveDisplay() {
string name = "tick" + to_string(tick) + ".png";
sf::Image image = texture->getTexture().copyToImage();
image.saveToFile(name);
}
 
int main(int argc, char* argv[]) {
srand(time(0));
App app;
app.start();
return 0;
}
</syntaxhighlight>
 
And the output of the above program:
[[File:Game of Life.gif|thumb|Life]]
 
 
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.
<langsyntaxhighlight lang="c">#include <iostream>
#define HEIGHT 4
#define WIDTH 4
Line 3,817 ⟶ 4,294:
gol2.iterate(4);
}
</syntaxhighlight>
</lang>
{{out}} first a glider, then a blinker, over a few iterations
(reformatted for convenience).
Line 3,837 ⟶ 4,314:
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.
<langsyntaxhighlight lang="cpp">
#include <algorithm>
#include <vector>
Line 4,024 ⟶ 4,501:
return system( "pause" );
}
</syntaxhighlight>
</lang>
{{out}}<pre>
+--------------------+ +--------------------+ +--------------------+ +--------------------+
Line 4,042 ⟶ 4,519:
Shows a glider over 20 generations
Board edges wrap around to simulate infinite board
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 4,127 ⟶ 4,604:
}
}
</syntaxhighlight>
</lang>
{{out}}<pre>
generation 0:
Line 4,180 ⟶ 4,657:
 
=={{header|Chapel}}==
<lang chapel>
config const gridHeight: int = 3;
config const gridWidth: int = 3;
 
Compile and run with <code>chpl gol.chpl; ./gol --gridWidth [x] --gridHeight [y]</code>.
enum State { dead = 0, alive = 1 };
<syntaxhighlight lang="chapel">
config const gridHeight : int = 3;
config const gridWidth : int = 3;
 
enum state { dead = 0, alive = 1 };
 
class ConwaysGameofLife
{
var gridDomain : domain(2, int);
var computeDomain : subdomain(gridDomain);
var grid : [gridDomain] state;
 
proc init(height : int, width : int)
{
this.gridDomain = {0..#height+2, 0..#width+2};
this.computeDomain = this.gridDomain.expand(-1);
}
 
 
proc step() : void
{
var tempGrid: [this.computeDomain] state;
 
forall (i,j) in this.computeDomain
{
var isAlive = this.grid[i,j] == state.alive;
var numAlive = (+ reduce this.grid[i-1..i+1, j-1..j+1]:int) - if isAlive then 1 else 0;
tempGrid[i,j] = if ( (2 == numAlive && isAlive) || numAlive == 3 ) then state.alive else state.dead ;
}
 
this.grid[this.computeDomain] = tempGrid;
}
 
proc this(i : int, j : int) ref : state
{
return this.grid[i,j];
}
 
 
proc prettyPrint() : string
{
var str : string;
for i in this.gridDomain.dim(0)
{
if i == 0 || i == gridDomain.dim(0).last
{
for j in this.gridDomain.dim(1)
{
str += "-";
}
}
else
{
for j in this.gridDomain.dim(1)
{
if j == 0 || j == this.gridDomain.dim(1).last
{
str += "|";
}
else
{
str += if this.grid[i,j] == state.alive then "#" else " ";
}
}
}
str += "\n";
}
 
return str;
}
 
class ConwaysGameofLife {
var gridDomain: domain(2);
var computeDomain: subdomain( gridDomain );
var grid: [gridDomain] int;
proc ConwaysGameofLife( height: int, width: int ) {
this.gridDomain = {0..#height+2, 0..#width+2};
this.computeDomain = this.gridDomain.expand( -1 );
}
proc step(){
var tempGrid: [this.computeDomain] State;
forall (i,j) in this.computeDomain {
var isAlive = this.grid[i,j] == State.alive;
var numAlive = (+ reduce this.grid[ i-1..i+1, j-1..j+1 ]) - if isAlive then 1 else 0;
tempGrid[i,j] = if ( (2 == numAlive && isAlive) || numAlive == 3 ) then State.alive else State.dead ;
}
this.grid[this.computeDomain] = tempGrid;
}
proc this( i: int, j: int ) ref : State {
return this.grid[i,j];
}
proc prettyPrint(): string {
var str: string;
for i in this.gridDomain.dim(1) {
if i == 0 || i == gridDomain.dim(1).last {
for j in this.gridDomain.dim(2) {
str += "-";
}
} else {
for j in this.gridDomain.dim(2) {
if j == 0 || j == this.gridDomain.dim(2).last {
str += "|";
} else {
str += if this.grid[i,j] == State.alive then "#" else " ";
}
}
}
str += "\n";
}
return str;
}
 
}
 
 
proc main{
proc main()
var game = new ConwaysGameofLife( gridHeight, gridWidth );
{
game[gridHeight/2 + 1, gridWidth/2 ] = State.alive;
var game[gridHeight/2 += 1new ConwaysGameofLife(gridHeight, gridWidth/2 + 1 ] = State.alive);
 
game[gridHeight/2 + 1, gridWidth/2 + 2 ] = State.alive;
game[gridHeight/2 + 1, gridWidth/2 ] = state.alive;
for i in 1..3 {
game[gridHeight/2 + 1, gridWidth/2 + 1 ] = state.alive;
writeln( game.prettyPrint() );
game[gridHeight/2 + 1, gridWidth/2 + 2 ] = state.alive;
game.step();
 
}
for i in 1..3
{
writeln(game.prettyPrint());
game.step();
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,273 ⟶ 4,776:
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.
<langsyntaxhighlight lang="lisp">(defn moore-neighborhood [[x y]]
(for [dx [-1 0 1]
dy [-1 0 1]
Line 4,300 ⟶ 4,803:
(def *blinker* #{[1 2] [2 2] [3 2]})
(def *glider* #{[1 0] [2 1] [0 2] [1 2] [2 2]})
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
<langsyntaxhighlight cobollang="cobolfree">identification division.
program-id. game-of-life-program.
 
data division.
working-storage section.
Line 4,323 ⟶ 4,827:
05 check-row pic s9.
05 check-cell pic s9.
 
procedure division.
control-paragraph.
Line 4,371 ⟶ 4,876:
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,
then add 1 to living-neighbours.</lang>
 
end program game-of-life-program.</syntaxhighlight>
{{out}}
<pre>GENERATION 0:
Line 4,395 ⟶ 4,902:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun next-life (array &optional results)
(let* ((dimensions (array-dimensions array))
(results (or results (make-array dimensions :element-type 'bit))))
Line 4,436 ⟶ 4,943:
(terpri out) (print-grid world out)
(psetq world (next-life world result)
result world))))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">(run-life (make-array '(3 3)
:element-type 'bit
:initial-contents '((0 0 0)
(1 1 1)
(0 0 0)))
3)</langsyntaxhighlight>
 
produces
Line 4,461 ⟶ 4,968:
A version using a sparse list of living cells rather than an explicit board.
 
<langsyntaxhighlight lang="lisp">(defun moore-neighborhood (cell)
(let ((r '(-1 0 1)))
(mapcan
Line 4,502 ⟶ 5,009:
 
(defparameter *blinker* '((1 . 2) (2 . 2) (3 . 2)))
(defparameter *glider* '((1 . 0) (2 . 1) (0 . 2) (1 . 2) (2 . 2)))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.array, std.conv;
 
struct GameOfLife {
Line 4,568 ⟶ 5,075:
uni.writeln;
}
}</langsyntaxhighlight>
{{out|Output, first iteration}}
<pre>-------------------------------------------------------------
Line 4,594 ⟶ 5,101:
===Faster Version===
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.typetuple,
std.array, std.conv;
 
Line 4,664 ⟶ 5,171:
uni.writeln;
}
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">/**
* States of a cell. A cell is either [ALIVE] or [DEAD].
* The state contains its [symbol] for printing.
Line 4,823 ⟶ 5,330:
loadBlinker(grid) => blinkerPoints().forEach((point) => grid.set(point, State.ALIVE));
 
blinkerPoints() => [new Point(0, 1), new Point(1, 1), new Point(2, 1)];</langsyntaxhighlight>
 
Test cases driving the design of this code:
<langsyntaxhighlight lang="dart">#import('<path to sdk>/lib/unittest/unittest.dart');
 
main() {
Line 4,923 ⟶ 5,430:
});
});
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,951 ⟶ 5,458:
{{Trans|Go}}
Thanks Rudy Velthuis for the [https://github.com/rvelthuis/Consoles Velthuis.Console] library.
<syntaxhighlight lang="delphi">
<lang Delphi>
program game_of_life;
 
Line 5,084 ⟶ 5,591:
end;
readln;
end.</langsyntaxhighlight>
{{out}}
<pre> * *** * * *
Line 5,105 ⟶ 5,612:
Just does three generations of a blinker in a dead-boundary grid, as specified. ([[User:Kevin Reid]] has graphical and wrapping versions.)
 
<langsyntaxhighlight lang="e">def gridWidth := 3
def gridHeight := 3
def X := 0..!gridWidth
Line 5,165 ⟶ 5,672:
currentFrame := frame
println(currentFrame)
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
[https://easylang.onlinedev/apps/game-of-life.html Run it]
 
<syntaxhighlight lang="text">
<lang>n = 70
n += 170
time = 0.1
#
nx = n + 1
subr init
for r = 1 to n - 1
for c = 1 to n - 1
i = r * nnx + c
if randomf < 0.3
f[i] = 1
.
.
.
.
.
f = 100 / (n - 1)
subr show
clear
for r = 1 to n - 1
for c = 1 to n - 1
if f[r * nnx + c] = 1
move (c -* 1)f *- f (r -* 1)f *- f
rect f * 0.9 f * 0.9
.
.
.
.
.
subr update
swap f[] p[]
for r = 1 to n - 1
sm = 0
i = r * nnx + 1
sr = p[i - n + 1nx] + p[i + 1] + p[i + n + 1nx]
for c = 1 to n - 1
i + sl = 1sm
sl = sm = sr
sm in = sri + 1
sr = p[iin - n + 1nx] + p[i + 1in] + p[i + nin + 1nx]
s = sl + sm + sr
if s = 3 or s = 4 and p[i] = 1
f[i] = 1
else
f[i] = 0
.
i = in
.
.
.
.
on timer
call update
call show
timer 0.2time
.
on mouse_down
c = mouse_x div f + 1
r = mouse_y div f + 1
i = r * nnx + c + n + 1
f[i] = 1 - f[i]
call show
timer 3
.
len f[] nnx * nnx + n + 1nx
len p[] nnx * nnx + n + 1nx
call init
timer 0</lang>
</syntaxhighlight>
 
=={{header|eC}}==
{{libheader|Ecere}}
 
<syntaxhighlight lang="ec">
<lang eC>
import "ecere"
 
Line 5,332 ⟶ 5,844:
 
GameOfLife life {};
</syntaxhighlight>
</lang>
 
=={{header|Egel}}==
 
<langsyntaxhighlight Egellang="egel">import "prelude.eg"
import "io.ego"
 
Line 5,390 ⟶ 5,902:
let _ = map [ G -> let _ = print "generation:\n" in printboard G ] {GEN0, GEN1, GEN2} in
nop
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 56.0x, using cellular library
<langsyntaxhighlight lang="elena">import extensions;
import system'threading;
import system'text;
import cellular;
 
Line 5,405 ⟶ 5,918:
sealed class Model
{
Space theSpace_space;
RuleSet theRuleSet_ruleSet;
bool started_started;
 
event Func<Space, object> OnUpdate : event;
constructor newRandomset(RuleSet transformSet)
{
theSpace_space := new IntMatrixSpace.allocate(maxY, maxX, randomSet);
 
theRuleSet_ruleSet := transformSet;
started_started := false
}
private onUpdate()
constructor newLoaded(RuleSet initSet, RuleSet transformSet)
{
OnUpdate.?(_space)
theSpace := IntMatrixSpace.allocate(maxY, maxX, initSet);
}
theRuleSet := transformSet;
started := false
}
private onUpdaterun()
{
if OnUpdate.?(theSpace_started)
} {
_space.update(_ruleSet)
run() }
{ else
if (started){
{ _started := true
};
theSpace.update(theRuleSet)
}
else
{
started := true
};
self.onUpdate()
}
}
 
singleton gameOfLifeRuleSet : RuleSet
{
int proceed(Space s, int x, int y, ref int retVal)
{
int cell := s.at(x, y);
int number := s.LiveCell(x, y, 1); // NOTE : number of living cells around the self includes the cell itself
if (cell == 0 && number == 3)
{
retVal :=^ 1
}
else if (cell == 1 && (number == 4 || number == 3))
{
retVal :=^ 1
}
else
{
retVal :=^ 0
}
}
}
 
public extension presenterOp : Space
{
print()
{
console.setCursorPosition(0, 0);
int columns := self.Columns;
int rows := self.Rows;
auto for(int iline := 0,new i < rows, i += 1TextBuilder();
for(int i {:= 0; i < rows; i += 1)
{
for(int j := 0, j < columns, j += 1)
{line.clear();
for(int j := 0; j < columns; intj cell :+= self.at(i, j1);
{
int console.write((cell =:= 0)self.iifat("i, ","o")j);
};
line.write((cell == 0).iif(" ","o"));
console.writeLine()};
}
console.writeLine(line.Value)
}
}
}
}
 
Line 5,505 ⟶ 6,011:
model.run();
threadControl.sleep:(DELAY)
};
 
console.readChar()
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Conway do
def game_of_life(name, size, generations, initial_life\\nil) do
board = seed(size, initial_life)
Line 5,582 ⟶ 6,088:
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("random", 5, 10)</langsyntaxhighlight>
 
{{out}}
Line 5,673 ⟶ 6,179:
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight lang="lisp">#!/usr/bin/env emacs -script
;; -*- lexical-binding: t -*-
;; run: ./conways-life conways-life.config
Line 5,766 ⟶ 6,272:
(swap a b))))
 
(simulate-life (elt command-line-args-left 0))</langsyntaxhighlight>
 
Configuration file, which defines the size starting patterns and
how long the simulation will run.
<langsyntaxhighlight lang="lisp">((rows . 8)
(cols . 10)
(generations . 3)
Line 5,778 ⟶ 6,284:
;; This is a custom pattern.
(4 4 (".***"
"***."))))</langsyntaxhighlight>
 
{{out}}
Line 5,812 ⟶ 6,318:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
 
-module(life).
Line 6,021 ⟶ 6,527:
list_to_integer(atom_to_list(Atom)).
 
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
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
 
Line 6,099 ⟶ 6,605:
END PROGRAM
 
</syntaxhighlight>
</lang>
 
=={{header|F Sharp|F#}}==
The following F# implementation uses {{libheader|Windows Presentation Foundation}} for visualization and is easily compiled into a standalone executable:
<langsyntaxhighlight lang="fsharp">let count (a: _ [,]) x y =
let m, n = a.GetLength 0, a.GetLength 1
let mutable c = 0
Line 6,137 ⟶ 6,643:
Media.CompositionTarget.Rendering.Add update
Window(Content=image, Title="Game of Life")
|> (Application()).Run |> ignore</langsyntaxhighlight>
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">;{Conway's Game of Life in Fermat}
;{square grid with wrap-around boundaries}
 
Line 6,220 ⟶ 6,726:
 
!!'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)
<pre>
Line 6,278 ⟶ 6,784:
'''gencell''' uses an optimization for the core Game of Life rules: new state = (old state | neighbors == 3).
 
<langsyntaxhighlight lang="forth"> \ The fast wrapping requires dimensions that are powers of 2.
1 6 lshift constant w \ 64
1 4 lshift constant h \ 16
Line 6,356 ⟶ 6,862:
**
*
Generation 1 ok</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran"> PROGRAM LIFE_2D
IMPLICIT NONE
Line 6,459 ⟶ 6,965:
END SUBROUTINE NextgenV2
!###########################################################################
END PROGRAM LIFE_2D</langsyntaxhighlight>
{{out}}
<pre style="height:45ex;overflow:scroll">
Line 6,586 ⟶ 7,092:
=={{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.
<langsyntaxhighlight lang="frink">
start = now[]
// Generate a random 10x10 grid with "1" being on and "0" being off
Line 6,692 ⟶ 7,198:
end = now[]
println["Program run time: " + ((end - start)*1.0 -> "seconds")]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import lists.zipWithIndex
import util.Regex
 
Line 6,783 ⟶ 7,289:
 
repeat 5
iteration()</langsyntaxhighlight>
 
{{out}}
Line 6,831 ⟶ 7,337:
 
=={{header|Furor}}==
<syntaxhighlight lang="furor">
<lang Furor>
// Life simulator (game). Console (CLI) version.
// It is a 'cellular automaton', and was invented by Cambridge mathematician John Conway.
Line 6,934 ⟶ 7,440:
{ „x” } { „y” } { „n” }
 
</syntaxhighlight>
</lang>
 
=={{header|Peri}}==
<syntaxhighlight lang="peri">
###sysinclude standard.uh
###sysinclude args.uh
###sysinclude str.uh
###sysinclude system.uh
// Life simulator (game).
// It is a 'cellular automaton', and was invented by Cambridge mathematician John Conway.
 
// The Rules
 
// For a space that is 'populated':
// Each cell with one or no neighbors dies, as if by solitude.
// Each cell with four or more neighbors dies, as if by overpopulation.
// Each cell with two or three neighbors survives.
// For a space that is 'empty' or 'unpopulated'
// Each cell with three neighbors becomes populated.
// --------------------------------------------------------------------------------------------
#g
// Get the terminal-resolution:
terminallines -- sto tlin
terminalcolumns sto tcol
// .............................
// Verify the commandline parameters:
argc 3 < { #s ."Usage: " 0 argv print SPACE 1 argv print ." lifeshape-file.txt\n" end }
2 argv 'f inv istrue { #s ."The given file ( " 2 argv print ." ) doesn't exist!\n" end }
2 argv filetolist sto startingshape // read the file into the list
[[startingshape]]~~~ sto maxlinlen
@tlin @tcol [[mem]] sto neighbour // Generate the stringarray for the neighbour-calculations
@tlin @tcol [[mem]] sto livingspace // Generate the stringarray for the actual generations
@tlin @tcol [[mem]]! sto cellscreen // Generate the stringarray for the visible livingspace
// Calculate offset for the shape ( it must be put to the centre):
@tlin startingshape~ - 2 / sto originlin
@tcol @maxlinlen - 2 / sto origincol
 
startingshape~ shaperead: {{ {{}} [[startingshape]]~ {{ {{}}§shaperead {{}} [[startingshape]][]
32 > { 1 }{ 0 } sto emblem
@originlin {{}}§shaperead + @origincol {{}} + @emblem inv [[livingspace]][]
}}
}}
cursoroff
// ==================================================================
{.. // infinite loop starts
sbr §renderingsbr
topleft @cellscreen ![[print]]
."Generation: " {..} print fflush // print the number of the generations.
0 [[neighbour]][^] // fill up the neighbour list with zero value
// Calculate neighbourhoods
@tlin linloop: {{ // loop for every lines
@tcol {{ // loop for every columns
{{}}§linloop {{}} sbr §neighbors
{{}}§linloop {{}} @nn inv [[neighbour]][] // store the neighbournumber
}} }}
// Now, kill everybody if the neighbors are less than 2 or more than 3:
@tlin linloop2: {{ // loop for every lines
@tcol {{ // loop for every columns
{{}}§linloop2 {{}} [[neighbour]][] 2 < then §kill
{{}}§linloop2 {{}} [[neighbour]][] 3 > then §kill
{{<}} // Continue the inner loop
kill: {{}}§linloop2 {{}} 0 inv [[livingspace]][]
}} }}
@tlin linloop3: {{ // loop for every lines
@tcol {{ // loop for every columns
// Generate the newborn cells:
{{}}§linloop3 {{}} [[neighbour]][] 3 == { {{}}§linloop3 {{}} 1 inv [[livingspace]][] }
}} }}
50000 inv sleep
..} // infinite loop ends
// ==================================================================
end
// ==========================================================
neighbors: // This subroutine calculates the quantity of neighborhood
sto xx sto yy zero nn
@yy ? @tlin -- @xx ? @tcol -- [[livingspace]][] sum nn // upleft corner
@yy @xx ? @tcol -- [[livingspace]][] sum nn // upmid corner
@yy ++? tlin @xx ? @tcol -- [[livingspace]][] sum nn // upright corner
@yy ? @tlin -- @xx [[livingspace]][] sum nn // midleft corner
@yy ++? tlin @xx [[livingspace]][] sum nn // midright corner
@yy ? @tlin -- @xx ++? tcol [[livingspace]][] sum nn // downleft corner
@yy @xx ++? tcol [[livingspace]][] sum nn // downmid corner
@yy ++? tlin @xx ++? tcol [[livingspace]][] sum nn // downright corner
rts
// ==========================================================
renderingsbr:
@tlin livingspaceloop: {{ @tcol {{
{{}}§livingspaceloop {{}}
{{}}§livingspaceloop {{}} [[livingspace]][] { '* }{ 32 } inv [[cellscreen]][]
}}
}}
rts
 
{ „tlin” }
{ „tcol” }
{ „startingshape” }
{ „maxlinlen” }
{ „livingspace” }
{ „neighbour” }
{ „originlin” }
{ „origincol” }
{ „emblem” }
{ „cellscreen” }
{ „xx” } { „yy” } { „nn” }
 
</syntaxhighlight>
 
=={{header|Futhark}}==
{{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 intb(x: int): bool = if x == 0 then False else True
Line 6,983 ⟶ 7,594:
iteration board in
to_int_board board
</syntaxhighlight>
</lang>
 
 
 
=={{header|FutureBasic}}==
This is just the basic central routine.
<syntaxhighlight lang="futurebasic">
 
Short a(4, 4), c(4, 4) // Initialize arrays of cells and a working copy
 
void local fn seed
Short x, y
// Blinker
a(1, 2) = 1 : a(2, 2) = 1 : a(3, 2) = 1
for y = 1 to 3 : for x = 1 to 3
print a(x, y); // Draw array
next : print : next : print
end fn
 
void local fn nextGen
Short x, y, dx, dy, n
// Calculate next generation on temporary board
for y = 1 to 3 : for x = 1 to 3
c(x, y) = 0 // Initialize
n = -a(x, y) // Don't count center cell
for dy = -1 to 1 : for dx = -1 to 1
n += a(x + dx, y + dy) // Count the neighbours
next : next
c(x, y) = ( n == 3 ) or ( n == 2 and a(x, y) ) // Conway’s rule
next : next
// Copy temp array to actual array and draw
for y = 1 to 3 : for x = 1 to 3
a(x, y) = c(x, y) // Copy
print a(x, y); // Draw
next : print : next : print
end fn
 
fn seed
fn nextGen
fn nextGen
 
handleevents // Go into Mac event loop
 
 
</syntaxhighlight>
Just three generations, as requested:
<pre>
000
111
000
 
010
010
010
 
000
111
000
 
 
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 7,083 ⟶ 7,754:
time.Sleep(time.Second / 30)
}
}</langsyntaxhighlight>
Running this program will compute and draw the first 300 "frames". The final frame looks like this:
<pre>
Line 7,105 ⟶ 7,776:
=={{header|Groovy}}==
 
<syntaxhighlight lang="groovy">
<lang Groovy>
class GameOfLife {
 
Line 7,210 ⟶ 7,881:
game.board = game.createGliderBoard()
game.start()
</syntaxhighlight>
</lang>
 
The output of this program:
Line 7,388 ⟶ 8,059:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Array.Unboxed
 
type Grid = UArray (Int,Int) Bool
Line 7,409 ⟶ 8,080:
 
count :: [Bool] -> Int
count = length . filter id</langsyntaxhighlight>
 
Example of use:
 
<langsyntaxhighlight lang="haskell">import Data.List (unfoldr)
 
grid :: [String] -> (Int, Int, Grid)
Line 7,452 ⟶ 8,123:
printGrid w g
 
main = printLife 10 glider</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="haskell">module Main where
import Data.List
 
Line 7,498 ⟶ 8,169:
putStrLn "Blinker >> 3"
putStrLn "------------"
runLife 3 blinker</langsyntaxhighlight>
 
=={{header|HolyC}}==
Line 7,506 ⟶ 8,177:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">global limit
 
procedure main(args)
Line 7,584 ⟶ 8,255:
initial count := 0
return ((count +:= 1) > \limit) | (trim(!g) == " ")
end</langsyntaxhighlight>
 
A sample run:
Line 7,620 ⟶ 8,291:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">pad=: 0,0,~0,.0,.~]
life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@pad
NB. the above could also be a one-line solution:
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:
Line 7,634 ⟶ 8,305:
 
'''Example''' (showing generations 0, 1 and 2 of a blinker):
<langsyntaxhighlight lang="j"> life^:0 1 2 #:0 7 0
0 0 0
1 1 1
Line 7,645 ⟶ 8,316:
0 0 0
1 1 1
0 0 0</lang>
 
</syntaxhighlight>
 
'''Example''' (showing start and six following generations of a glider)
 
<langsyntaxhighlight lang="j"> blocks=: (2 2$2) ((7 u:' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█') {~ #.@,);._3 >.&.-:@$ {. ]</langsyntaxhighlight>
 
<pre style="line-height: 1"> blocks"2 life^:(i.7) 4 5{.#:1 5 3
Line 7,675 ⟶ 8,348:
=={{header|JAMES II/Rule-based Cellular Automata}}==
{{libheader|JAMES II}}
<langsyntaxhighlight lang="j2carules">@caversion 1;
 
dimensions 2;
Line 7,699 ⟶ 8,372:
ALIVE
*/
rule{DEAD}:ALIVE{3}->ALIVE;</langsyntaxhighlight>
Animated output for the blinker example:
 
Line 7,705 ⟶ 8,378:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class GameOfLife{
public static void main(String[] args){
String[] dish= {
Line 7,795 ⟶ 8,468:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Generation 0:
Line 7,813 ⟶ 8,486:
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.
<langsyntaxhighlight lang="java">
//package conway;
 
Line 7,968 ⟶ 8,641:
}
}
</syntaxhighlight>
</lang>
 
Glider Gun design. Save it in GOLglidergun.txt and uncomment the setCustomConfig function.
Line 7,998 ⟶ 8,671:
 
===Java 10===
<langsyntaxhighlight lang="java">
import static java.util.List.of;
 
Line 8,091 ⟶ 8,764:
 
}
</syntaxhighlight>
</lang>
Outputs:
<pre>
Line 8,112 ⟶ 8,785:
{{works with|SpiderMonkey}}
{{works with|V8}}
<langsyntaxhighlight lang="javascript">function GameOfLife () {
 
this.init = function (turns,width,height) {
Line 8,210 ⟶ 8,883:
print("---\nRandom 5x10");
game.init(5,5,10);
game.start();</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">---
Line 8,335 ⟶ 9,008:
{{libheader|HTML5}}
Essentially the same as the above straight [[JavaScript]] but displayed in an [[HTML5]] Canvas.
<langsyntaxhighlight lang="javascript">
<html>
<head>
Line 8,486 ⟶ 9,159:
</canvas><br>
</body>
</html></langsyntaxhighlight>
{{out}} for 3x3 Blinker:
 
Line 8,493 ⟶ 9,166:
 
'''More functional style''':
<langsyntaxhighlight lang="javascript">
const _ = require('lodash');
 
Line 8,535 ⟶ 9,208:
displayWorld(world);
}, 1000);
</syntaxhighlight>
</lang>
 
'''ES6 + ''':
<langsyntaxhighlight lang="javascript">
const alive = 1;
const dead = 0;
Line 8,610 ⟶ 9,283:
run()
 
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 8,616 ⟶ 9,289:
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.
<langsyntaxhighlight lang="jq"># Notes on the implementation:
 
# 1. For efficiency, the implementation requires that the world
Line 8,660 ⟶ 9,333:
end )
| [., $lines, $w] ;
</syntaxhighlight>
</lang>
'''Animation''':
<langsyntaxhighlight lang="jq"># "clear screen":
def cls: "\u001b[2J";
 
Line 8,688 ⟶ 9,361:
# Input: a string representing the initial state
def frames(n): animation(n; -1);
</syntaxhighlight>
</lang>
'''Examples''':
<langsyntaxhighlight lang="jq">def world3:
"+---+\n" +
"| |\n" +
Line 8,704 ⟶ 9,377:
"| .. |\n" +
"| |\n" +
"+-----------+\n" ;</langsyntaxhighlight>
 
'''Task''':
<syntaxhighlight lang ="jq">world3 | frames(3)</langsyntaxhighlight>
{{Out}}
<div style="overflow:scroll; height:200px;">
<langsyntaxhighlight lang="sh">$ jq -n -r -f Game_of_life.jq
 
+---+
Line 8,740 ⟶ 9,413:
+---+
 
1</langsyntaxhighlight></div>
'''Animation example'''
<langsyntaxhighlight lang="jq"># Animation of 100 frames with approximately 1 second between each update:
world11 | animation(100; 1000)</langsyntaxhighlight>
 
=={{header|Jsish}}==
From Javascript, SpiderMonkey entry.
 
<langsyntaxhighlight lang="javascript">/* Conway's game of life, in Jsish */
function GameOfLife () {
this.title = "Conway's Game of Life";
Line 8,887 ⟶ 9,560:
 
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 8,898 ⟶ 9,571:
Using the '''CellularAutomata''' package: https://github.com/natj/CellularAutomata.jl
 
<langsyntaxhighlight lang="cpp">julia> Pkg.add("CellularAutomata")
INFO: Installing CellularAutomata v0.1.2
INFO: Package database updated
Line 8,908 ⟶ 9,581:
 
julia> gameOfLife(15, 30, 5)
30x15x5 Cellular Automaton</langsyntaxhighlight>
 
# ## # ###### ### ### ##
Line 8,996 ⟶ 9,669:
=== GPU calculation based version ===
Requires a CUDA compatible graphics card and uses the ArrayFire library.
<langsyntaxhighlight lang="julia">using ArrayFire
using Images
using LinearAlgebra
Line 9,039 ⟶ 9,712:
lifegame("lwss.gif", lwss)
lifegame("glidergun.gif", glidergun, 90, 200)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 9,050 ⟶ 9,723:
The particular random pattern used now needs only 99 generations to reach stability.
 
<langsyntaxhighlight lang="scala">// version 1.2.0
 
import java.util.Random
Line 9,160 ⟶ 9,833:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 9,257 ⟶ 9,930:
..........##....................................................................
</pre>
 
=={{header|Lambdatalk}}==
Lambdatalk works in any web browsers coming with javascript and canvas.
<syntaxhighlight lang="scheme">
{center
{input {@ type="button" value="start random"
onclick="LIFE.startstop(this,'random')"}}
{input {@ type="button" value="start cross"
onclick="LIFE.startstop(this,'cross')"}}
{canvas {@ id="life" width="330" height="330"
style="box-shadow:0 0 8px #000"}}
}
 
calling the following javascript code
 
{script
var LIFE = (function() {
var board = [],
xmax = 8, ymax = 8,
interval = null,
delay = 1000;
var isdefined = function(x,y) {
return typeof board[x] !== 'undefined'
&& typeof board[x][y] !== 'undefined'
&& board[x][y];
};
 
var alive = function(c,n) {
if (n < 2 || n > 3) c = 0;
if (n === 3) c = 1;
return c
};
 
var neighbours = function(x,y) {
var n = 0;
if (isdefined(x-1,y-1)) n++;
if (isdefined(x ,y-1)) n++;
if (isdefined(x+1,y-1)) n++;
if (isdefined(x-1,y )) n++;
if (isdefined(x+1,y )) n++;
if (isdefined(x-1,y+1)) n++;
if (isdefined(x ,y+1)) n++;
if (isdefined(x+1,y+1)) n++;
return n
};
 
var nextGen = function() {
var next = [];
for (var x = 0; x < xmax; x++) {
next[x] = [];
for (var y = 0; y < ymax; y++)
next[x][y] = alive( board[x][y], neighbours(x,y) );
}
board = next
};
 
var print = function(ctx,dw,dh) {
for (var x = 0; x < xmax; x++) {
for (var y = 0; y < ymax; y++) {
ctx.fillStyle = (board[x][y])? "#fff" : "#888";
ctx.fillRect(y*dh+1,x*dw+1,dh-1,dw-1)
}
}
};
 
var init = function (type,w,h) {
xmax = w;
ymax = h;
delay = (type === "random")? 100 : 1000;
for (var x = 0; x < xmax; x++) {
board[x] = [];
for (var y = 0; y < ymax; y++) {
if (type === "random") {
board[x][y] = Math.round(Math.random());
} else {
board[x][y] = 0;
if (x === Math.floor(w/2)) board[x][y] = 1;
if (y === Math.floor(h/2)) board[x][y] = 1;
}
}
}
};
 
var run = function(ctx,dw,dh) {
print(ctx,dw,dh);
nextGen()
};
 
var startstop = function(id,type) {
var can = document.getElementById('life').getContext('2d');
if (interval === null) {
id.value = "stop";
init(type,33,33);
interval = window.setInterval( run, delay, can, 10, 10 );
} else {
id.value = (type === "random")? "start_random" : "start_cross";
window.clearInterval( interval );
interval = null;
}
};
 
return { startstop }
}) (); // end LIFE
}
</syntaxhighlight>
Results can be seen in http://lambdaway.free.fr/lambdaspeech/?view=life
and in http://lambdaway.free.fr/lambdawalks/?view=conway
 
=={{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)''
<langsyntaxhighlight 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 = {
Line 9,296 ⟶ 10,078:
end
end
}</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="lua">print("GLIDER:")
local life = Life:new(5,5)
life:set({ 2,1, 3,2, 1,3, 2,3, 3,3 })
Line 9,318 ⟶ 10,100:
end
for i = 6,20 do life:evolve() end
life:render()</langsyntaxhighlight>
{{out}}
<pre>GLIDER:
Line 9,408 ⟶ 10,190:
□ □ □ □ □ □ □ □ □ □</pre>
=={{header|ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
# # Version AJM 93u+ 2012-08-01
Line 9,502 ⟶ 10,284:
_game ${h} ${w}
 
</syntaxhighlight>
</lang>
 
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Life {
Font "courier new"
Line 9,581 ⟶ 10,363:
}
Life
</syntaxhighlight>
</lang>
 
=={{header|MANOOL}}==
Straightforward implementation useful for benchmarking:
<syntaxhighlight lang="manool">
<lang MANOOL>
{ {extern "manool.org.18/std/0.3/all"} in
: let { N = 40; M = 80 } in
Line 9,638 ⟶ 10,420:
Out.WriteLine["After " G " generations:"]; Display[B]
}
</syntaxhighlight>
</lang>
Using comprehension notation:
<syntaxhighlight lang="manool">
<lang MANOOL>
{ {extern "manool.org.18/std/0.3/all"} in
: let { N = 40; M = 80 } in
Line 9,691 ⟶ 10,473:
Out.WriteLine["After " G " generations:"]; Display[B]
}
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica has cellular automaton functionality built in, so implementing Conway's Game of Life is a one-liner:
<langsyntaxhighlight Mathematicalang="mathematica">CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}}, startconfiguration, steps];</langsyntaxhighlight>
Example of a glyder progressing 8 steps and showing the 9 frames afterwards as grids of hashes and dots:
<langsyntaxhighlight Mathematicalang="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]}]</langsyntaxhighlight>
gives back:
<pre style="height:30ex;overflow:scroll">
Line 9,766 ⟶ 10,548:
 
=={{header|MATLAB}}==
MATLAB has a builtin Game of Life GUI. Type <syntaxhighlight lang ="matlab">life</langsyntaxhighlight> to run it. To view the code, type
 
<langsyntaxhighlight lang="matlab">open(fullfile(matlabroot, 'toolbox', 'matlab', 'demos', 'life.m'))</langsyntaxhighlight>
 
Here is an example code, more simple (runs the game of life for N generations in a square of side S) :
 
<langsyntaxhighlight lang="matlab">function GoL(S, N) %
colormap copper; whitebg('black');
G= round(rand(S));
Line 9,781 ⟶ 10,563:
surf(G); view([0 90]); pause(0.001)
end
end</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">life(A) := block(
[p, q, B: zerofor(A), s],
[p, q]: matrix_size(A),
Line 9,836 ⟶ 10,618:
[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])</langsyntaxhighlight>
Blinker over three generations
<syntaxhighlight lang="maxima">
three_all_alive: matrix([0,1,0],[0,1,0],[0,1,0])$
with_slider_draw(n,makelist(j,j,0,2),image(gen(three_all_alive,n),0,0,30,30));
</syntaxhighlight>
[[File:BlinkerMaxima.gif|thumb|center]]
 
=={{header|MiniScript}}==
This GUI implementation is for use with [http://miniscript.org/MiniMicro Mini Micro].
<langsyntaxhighlight MiniScriptlang="miniscript">// Conway's Game of Life
clear
rows = 64; rowRange = range(0, rows-1)
Line 9,850 ⟶ 10,638:
display(dispIdx).mode = displayMode.tile
td = display(dispIdx)
td.cellSize = 109 // size of cells on screen
td.extent = [cols, rows]
td.overlap = -1 // adds a small gap between cells
Line 9,896 ⟶ 10,684:
display(curIdx).mode = displayMode.off
curIdx = newIdx
end while</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">import os, strutils, random
 
randomize()
Line 9,941 ⟶ 10,729:
swap(univ,utmp)
 
sleep 200</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let get g x y =
try g.(x).(y)
with _ -> 0
Line 9,989 ⟶ 10,777:
else print_char 'o'
done;
print_newline ()
done</langsyntaxhighlight>
 
put the code above in a file named "life.ml", and then use it in the ocaml toplevel like this:
Line 10,053 ⟶ 10,841:
=== A graphical version ===
This implementation has 6 starting patterns (most get quite large) and a random option, and you can set the grid size.
<langsyntaxhighlight OCamllang="ocaml">let alive = 0
let dead = 0xFFFFFF
 
Line 10,133 ⟶ 10,921:
disp bd2;
iteration bd2 bd1 width height
done</langsyntaxhighlight>
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.
 
=={{header|Octave}}==
 
=={{header|OCTAVE}}==
1st order two variable recurrence relation m-file, will also run under MATLAB.
 
<langsyntaxhighlight lang="matlab">
clear all
x=55; % Size of the Lattice (same as LAWE)
Line 10,214 ⟶ 11,001:
pause % each press advances the algorithm one step
endfor
</syntaxhighlight>
</lang>
 
 
=={{header|Ol}}==
{{libheader|OpenGL}}
<langsyntaxhighlight lang="scheme">
#!/usr/bin/ol
(import (otus random!))
Line 10,291 ⟶ 11,077:
neighbors)))
#empty generation)))))
</syntaxhighlight>
</lang>
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang="oorexx">/* REXX ---------------------------------------------------------------
* 07.08.2014 Walter Pachl Conway's Game of life graphical
* Input is a file containing the initial pattern.
Line 10,737 ⟶ 11,523:
Else
Return
</syntaxhighlight>
</lang>
{{out}}
<pre>blinker.txt
Line 10,753 ⟶ 11,539:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
Rules = [rule(c:1 n:[0 1] new:0) %% Lonely
rule(c:1 n:[4 5 6 7 8] new:0) %% Overcrowded
Line 10,856 ⟶ 11,642:
{System.showInfo "\nGen. "#I}
{ForAll {ShowG Gi} System.showInfo}
end</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="parigp">step(M)={
my(N=M,W=matsize(M)[1],L=#M,t);
for(l=1,W,for(w=1,L,
Line 10,869 ⟶ 11,655:
};
M=[0,1,0;0,1,0;0,1,0];
for(i=1,3,print(M);M=step(M))</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 10,876 ⟶ 11,662:
Optimized for speed on a Haswell CPU
(without PrintGen ~ 8.5 Cpu-cyles/coordinate )
<langsyntaxhighlight lang="pascal">program Gol;
// Game of life
{$IFDEF FPC}
Line 11,055 ⟶ 11,841:
PrintGen;
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
Line 11,065 ⟶ 11,851:
would do 15 iterations over 5 rows and 10 columns.
<langsyntaxhighlight lang="perl">my ($width, $height, $generations) = @ARGV;
 
my $printed;
Line 11,123 ⟶ 11,909:
printlife @life;
}
print "\n";</langsyntaxhighlight>
 
Another version, takes up the whole area of your terminal. Using warping edges.<langsyntaxhighlight Perllang="perl">my $w = `tput cols` - 1;
my $h = `tput lines` - 1;
my $r = "\033[H";
Line 11,156 ⟶ 11,942:
print map((map($_ ? "#" : " ", @$_), "\n"), @universe);
iterate;
}</langsyntaxhighlight>
===Next Generation in a Single Substitution Operator===
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
print $_ = <<'' =~ tr/./ /r; # test case, dots only for layout
Line 11,174 ⟶ 11,960:
s/$neighborhood/ substr " $&# ", "$1$2$3$4" =~ tr|#||, 1 /ge;
print;
}</langsyntaxhighlight>
{{out}}
Line 11,201 ⟶ 11,987:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/conways_game_of_life.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Conways_Game_of_Life.exw
Line 11,359 ⟶ 12,145:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{header|Picat}}==
===Blinker===
<langsyntaxhighlight Picatlang="picat">go =>
Rows = 3,
Cols = 3,
Line 11,426 ⟶ 12,212:
[1,1,1],
[0,0,0]],
I=1,J=1.</langsyntaxhighlight>
 
{{out}}
Line 11,447 ⟶ 12,233:
 
===Testing some more forms===
<langsyntaxhighlight Picatlang="picat">go2 =>
Rows = 20,
Cols = 20,
Line 11,494 ⟶ 12,280:
[0,0,0,1,1,1],
[0,0,0,1,1,1]],
I=10,J=10.</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Line 11,500 ⟶ 12,286:
an array of multiply linked objects, and are also used in the chess program and
other games in the distribution.
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
 
(de life (DX DY . Init)
Line 11,529 ⟶ 12,315:
(=: life (: next)) ) ) ) ) )
 
(life 5 5 b3 c3 d3)</langsyntaxhighlight>
Output:
<pre> 5
Line 11,551 ⟶ 12,337:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">(subscriptrange):
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), */
Line 11,610 ⟶ 12,396:
end;
end;
end Conway;</langsyntaxhighlight>
Results:
<pre>
Line 11,654 ⟶ 12,440:
 
=={{header|Pointless}}==
<langsyntaxhighlight lang="pointless">-----------------------------------------------------------
-- Print 100 simulated states of conway's game of life
-- for a glider starting pattern on a wrapping grid
Line 11,741 ⟶ 12,527:
 
showCell(cell) =
if cell == 1 then "*" else " "</langsyntaxhighlight>
 
=={{header|PostScript}}==
<langsyntaxhighlight PostScriptlang="postscript">%!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400
 
Line 11,792 ⟶ 12,578:
 
1000 { drawboard showpage iter } repeat
%%EOF</langsyntaxhighlight>
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">
<lang Prolog>
%----------------------------------------------------------------------%
% GAME OF LIFE %
Line 11,975 ⟶ 12,761:
write_line(S,T).
write_line(_,[]) :- !.
</syntaxhighlight>
</lang>
 
'''Sample output:'''<br>
Line 11,984 ⟶ 12,770:
Inspired by Daniel Shiffman's book The Nature of Code (http://natureofcode.com)
 
<langsyntaxhighlight lang="java">boolean play = true;
int cellSize = 10;
int cols, rows;
Line 12,123 ⟶ 12,909:
grid[x][y] = states[grid[x][y]]; // invert
}
}</langsyntaxhighlight>
 
==={{header|Processing Python mode}}===
<langsyntaxhighlight lang="python">cell_size = 10
sample = 10
play = False # simulation is running
Line 12,236 ⟶ 13,022:
if p != last_cell:
last_cell = p
grid[i][j] = (1, 0)[grid[i][j]]</langsyntaxhighlight>
 
=={{header|Python}}==
Line 12,251 ⟶ 13,037:
of <u>universe</u> returns zero.
 
<langsyntaxhighlight lang="python">import random
from collections import defaultdict
 
Line 12,305 ⟶ 13,091:
for c in range(col-1, col+2) )
) ]
universe = nextgeneration</langsyntaxhighlight>
{{out}} (sample)
<pre style="height:30ex;overflow:scroll">
Line 12,328 ⟶ 13,114:
A world is represented as a set of (x, y) coordinates of all the alive cells.
 
<langsyntaxhighlight lang="python">from collections import Counter
 
def life(world, N):
Line 12,364 ⟶ 13,150:
 
 
life(world, 5)</langsyntaxhighlight>
 
{{out}}
Line 12,431 ⟶ 13,217:
 
===Using an array to define the world===
<langsyntaxhighlight lang="python">import numpy as np
from pandas import DataFrame
import matplotlib.pyplot as plt
Line 12,492 ⟶ 13,278:
 
conway_life()</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
Uses a Tortoise and Hare algorithm to detect when Life becomes static or repetitive. The tortoise version is displayed, along with five victory laps of the cyclic part once a cycle is detected.
 
<syntaxhighlight lang="Quackery">
[ $ "turtleduck.qky" loadfile ] now!
 
[ $ \
import time
now = time.time()
sleepy_time = 5/7-(now%(5/7))
time.sleep(sleepy_time)
\ python ] is wait ( --> )
 
[ dup 1
[ 2dup > while + 1 >> 2dup / again ]
drop nip ] is sqrt ( n --> n )
 
[ stack ] is width ( --> s )
 
[ tuck witheach
[ over i^ peek + rot i^ poke swap ]
drop ] is add ( [ [ --> [ )
 
[ 1 split swap join ] is left ( [ --> [ )
 
[ -1 split swap join ] is right ( [ --> [ )
 
[ width share split swap join ] is up ( [ --> [ )
 
[ width share negate split swap join ] is down ( [ --> [ )
 
[ left dup up tuck add
swap right tuck add
swap right tuck add
swap down tuck add
swap down tuck add
swap left tuck add
swap left add ] is neighbours ( [ --> [ )
 
[ [] swap
width share times
[ width share split
dip [ 0 swap 0 join join join ] ]
drop
2 width tally
0 width share of tuck join join ] is makeborder ( [ --> [ )
 
[ dup size times
[ 0 swap i^ poke
0 swap i^ width share + 1 - poke
width share step ]
width share times
[ 0 swap i^ poke
0 swap i^ 1 + negate poke ] ] is clearborder ( [ --> [ )
 
[ dup neighbours
witheach
[ over i^ peek iff
[ 1 | 3 != if
[ 0 swap i^ poke ] ]
done
3 = if [ 1 swap i^ poke ] ]
clearborder ] is nextgen ( [ --> [ )
 
[ 6 random
[ table
[ 200 200 255 ] [ 200 255 200 ]
[ 255 200 200 ] [ 200 255 255 ]
[ 255 200 255 ] [ 255 255 200 ] ]
fill
[ 4 times
[ 20 1 walk -1 4 turn ] ] ] is block ( --> )
 
 
[ clear
width share 10 *
dup negate
4 - 1 fly
-1 4 turn
16 - 1 fly
1 4 turn
20 1 fly
' [ 200 200 200 ] colour
4 times
[ width share 2 - 20 * 1 walk
1 4 turn ]
-20 1 fly
' [ 63 63 63 ] colour
width share times
[ width share split
swap witheach
[ if block
20 1 fly ]
width share -20 * 1 fly
1 4 turn
20 1 fly
-1 4 turn ]
drop wait frame ] is draw ( [ --> )
 
[ turtle 0 frames 2 wide
dup size sqrt width put
makeborder
dup
[ dup draw nextgen
dip [ nextgen nextgen ]
2dup = until ]
5 times
[ dup draw nextgen 2dup = until ]
2drop width release ] is life ( [ --> )
 
' [ 0 0 0
1 1 1
0 0 0 ] life ( task requirement )
 
' [ 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 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 1 1 1 1 1 0 1 1 1 1 1 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 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 ] life ( more interesting )
 
randomise
[ []
1089 times
[ 2 random join ]
life
again ] ( ... runs forever )</syntaxhighlight>
 
{{out}}
 
<code>( task requirement )</code>
 
[[File:Quackery Life Task.png|thumb|center]]
 
<code>( more interesting )</code>
 
[[File:Quackery Life.gif|thumb|center]]
 
<code>( ... runs forever )</code>
 
https://youtu.be/U5owgEpxzwg
 
(The code runs forever, not the video. The accompanying music is also generative, and comes from the Kolakoski Sequence.)
 
=={{header|R}}==
<langsyntaxhighlight 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)
{
Line 12,576 ⟶ 13,516:
game.of.life(gen.board("blinker"))
game.of.life(gen.board("glider", 18, 20))
game.of.life(gen.board(, 50, 50))</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
(require 2htdp/image 2htdp/universe)
Line 12,710 ⟶ 13,650:
;;; (game-of-life (thunder) 2)
;;; (game-of-life (cross) 2)
</syntaxhighlight>
</lang>
 
Output for an 80x80 cross:
Line 12,718 ⟶ 13,658:
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>class Automaton {
subset World of Str where {
.lines>>.chars.unique == 1 and m/^^<[.#\n]>+$$/
Line 12,775 ⟶ 13,715:
say $glider++;
say '--';
}</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Rebollang="red">Red [
Purpose: "Conway's Game of Life"
Author: "Joe Smith"
Line 12,834 ⟶ 13,774:
conway *8-8
]
</syntaxhighlight>
</lang>
 
{{out}}
Line 13,067 ⟶ 14,007:
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">:w/l [ $. eq? [ #0 ] [ #1 ] choose , ] s:for-each ;
 
'World d:create
Line 13,136 ⟶ 14,076:
}}
#12 gens</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 13,142 ⟶ 14,082:
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.
<langsyntaxhighlight 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. */
parse arg peeps '(' rows cols empty life! clearScreen repeats generations .
Line 13,186 ⟶ 14,126:
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 _
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</langsyntaxhighlight>
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,217 ⟶ 14,157:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 02.08.2014 Walter Pachl
* Input is a file containing the initial pattern
Line 13,401 ⟶ 14,341:
Return lineout(dbg,arg(1))
Else
Return</langsyntaxhighlight>
{{out}}
<pre> blinker
Line 13,422 ⟶ 14,362:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def game_of_life(name, size, generations, initial_life=nil)
board = new_board size
seed board, size, initial_life
Line 13,485 ⟶ 14,425:
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 "random", 5, 10</langsyntaxhighlight>
 
{{out}}
Line 13,603 ⟶ 14,543:
The above implementation uses only methods. Below is one that is object-oriented and feels perhaps a bit more Ruby-ish.
 
<langsyntaxhighlight lang="ruby">class Game
def initialize(name, size, generations, initial_life=nil)
@size = size
Line 13,707 ⟶ 14,647:
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 "random", 5, 10</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
use std::collections::HashMap;
use std::collections::HashSet;
Line 13,784 ⟶ 14,724:
life(glider, 20, 8, 8);
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
Line 13,792 ⟶ 14,732:
{{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
;;all cells outside the defined grid are dead
Line 13,881 ⟶ 14,821:
(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)</langsyntaxhighlight>
 
{{out}}
Line 14,179 ⟶ 15,119:
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.
 
<syntaxhighlight lang="text">Init_state=[0 0 0;...
1 1 1;...
0 0 0];
Line 14,281 ⟶ 15,221:
Curr_state=Next_state;
end</langsyntaxhighlight>
 
{{out}}
Line 14,321 ⟶ 15,261:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">set starting_condition to ((0, 0), (1, 0), (2, 0), (-1, -1), (0, -1), (1, -1))
 
RunGameOfLife starting_condition
Line 14,393 ⟶ 15,333:
wait 1 second
end repeat
end RunGameOfLife</langsyntaxhighlight>
 
=={{header|SequenceL}}==
Line 14,399 ⟶ 15,339:
 
'''SequenceL Code:'''
<langsyntaxhighlight lang="sequencel">life(Cells(2))[I, J] :=
let
numNeighbors := Cells[I-1,J-1] + Cells[I-1,J] + Cells[I-1,J+1] +
Line 14,419 ⟶ 15,359:
1
foreach y within 1 ... n,
x within 1 ... n;</langsyntaxhighlight>
 
'''C++ Driver Code:'''
<langsyntaxhighlight lang="c">#include <iostream>
#include <string>
#include <vector>
Line 14,601 ⟶ 15,541:
}
throw(errno);
}</langsyntaxhighlight>
 
'''Usage:'''
Line 14,634 ⟶ 15,574:
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].
<langsyntaxhighlight lang="setl">program life;
 
const
Line 14,668 ⟶ 15,608:
end proc;
 
end program;</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight Shenlang="shen">(tc +)
 
(datatype subtype
Line 14,804 ⟶ 15,744:
[0 1 1 1 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]])</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var w = Num(`tput cols`)
var h = Num(`tput lines`)
var r = "\033[H"
Line 14,839 ⟶ 15,779:
say universe.map{|row| row.map{|cell| cell ? '#' : ' '}.join }.join("\n")
iterate()
}</langsyntaxhighlight>
 
=={{header|Simula}}==
{{trans|Scheme}}
<langsyntaxhighlight 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 ;
 
Line 15,008 ⟶ 15,948:
 
END.
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 15,309 ⟶ 16,249:
This implementation has been developed using '''Cuis Smalltalk''' [https://github.com/Cuis-Smalltalk/Cuis-Smalltalk-Dev].
Here are different configurations:
<langsyntaxhighlight lang="smalltalk">
"Blinker"
GameOfLife withAliveCells: { 4@2. 4@3. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10.
Line 15,315 ⟶ 16,255:
"Toad"
GameOfLife withAliveCells: { 2@4. 3@4. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10
</syntaxhighlight>
</lang>
This is the implementation:
<syntaxhighlight lang="smalltalk">
<lang Smalltalk>
Object subclass: #GameOfLife
instanceVariableNames: 'aliveCells boardSize'
Line 15,367 ⟶ 16,307:
numberOfAliveNeighborsOf: aCell
^aCell eightNeighbors count: [ :aNeighbor | self isAlive: aNeighbor ]
</langsyntaxhighlight>
The implementation was developed using TDD. This are the tests used to implement it.
<syntaxhighlight lang="smalltalk">
<lang Smalltalk>
TestCase subclass: #GameOfLifeTest
instanceVariableNames: ''
Line 15,430 ⟶ 16,370:
raise: Error - MessageNotUnderstood
withMessageText: 'Cell 1@4 out of range'
</syntaxhighlight>
</lang>
If you want to have a visual representation, here is a view for it:
<langsyntaxhighlight lang="smalltalk">
ImageMorph subclass: #GameOfLifeView
instanceVariableNames: 'game'
Line 15,476 ⟶ 16,416:
self showBoard.
self redrawNeeded.
</syntaxhighlight>
</lang>
 
=={{header|SQL}}==
Line 15,482 ⟶ 16,422:
 
{{works with|Oracle}}
<langsyntaxhighlight lang="sql">
-- save these lines in a file called
-- setupworld.sql
Line 15,599 ⟶ 16,539:
from output
order by y desc;
</syntaxhighlight>
</lang>
 
<pre>
Line 15,631 ⟶ 16,571:
{{trans|Rust}}
 
<langsyntaxhighlight lang="swift">struct Cell: Hashable {
var x: Int
var y: Int
Line 15,725 ⟶ 16,665:
 
print("Glider: ")
col.run(iterations: 20)</langsyntaxhighlight>
 
{{out}}
Line 15,963 ⟶ 16,903:
=={{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).
<langsyntaxhighlight SystemVeriloglang="systemverilog">module gol;
 
parameter NUM_ROWS = 20;
Line 15,991 ⟶ 16,931:
end
 
endmodule</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc main {} {
Line 16,073 ⟶ 17,013:
}
 
main</langsyntaxhighlight>
<pre style='height:30ex; overflow:scroll'>blinker generation 1:
. # .
Line 16,112 ⟶ 17,052:
. . . #
. # # #</pre>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Z Shell}}
<syntaxhighlight lang="bash"># Shells only have 1-dimensional arrays, so each row is one string
function main {
typeset blinker=(000 111 000)
run list 4 "${blinker[@]}"
}
 
function run {
typeset mode=$1 # screen or list
shift
typeset -i limit=0
if (( $1 > 1 )); then
limit=$1
shift
fi
if [[ mode == screen ]]; then
clear
fi
typeset universe=("$@")
typeset -i generation=0
while (( !limit || generation < limit )); do
if [[ mode == screen ]]; then
printf '\e[H'
else
printf '\n'
fi
printf 'Generation %d\n' "$generation"
disp "${universe[@]}" | tr '01' '.@'
universe=($(next_generation "${universe[@]}"))
(( generation += 1 ))
sleep 0.125
done
}
 
# display a matrix
function disp {
# remove sed for more compact display
printf '%s\n' "$@" | sed 's/./ &/g'
}
 
# center a matrix within a given size by padding with 0s
function center {
typeset height=$1 width=$2
shift 2
typeset -i offset_i offset_j i j
if (( $# > height || ${#1} > width )); then
printf >&2 'Source larger than target.\n'
return 1
fi
(( offset_i = (height - $#) / 2 ))
(( offset_j = (width - ${#1}) / 2 ))
typeset prefix zeroes suffix
for (( j=0; j<width; ++j )); do
zeroes+=0
if (( j < offset_j )); then
prefix+=0
elif (( j >= offset_j+${#1} )); then
suffix+=0
fi
done
for (( i=0; i<offset_i; ++i )); do
printf '%s\n' "$zeroes"
done
while (( $# )); do
printf '%s%s%s\n' "$prefix" "$1" "$suffix"
shift
(( i++ ))
done
while (( i++ < height )); do
printf '%s\n' "$zeroes"
done
}
 
# compute the next generation
# the grid is finite; pass -t to treat as torus (wraparound), otherwise it's
# bounded by always-dead cells
next_generation() {
typeset -i torus=0
if [[ $1 == -t ]]; then
torus=1
shift
fi
# cache cells in an associative array
# (for fast lookup when counting neighbors)
typeset -A cells
typeset -i i=0 j=0 height=$# width=${#1}
while (( $# )); do
row=$1
shift
for (( j=0; j<${#row}; ++j )); do
cells[$i,$j]=${row:$j:1}
done
(( i+=1 ))
done
typeset -i di dj ni nj n cell
for (( i=0; i<height; ++i )); do
for (( j=0; j<width; ++j )); do
n=0
for (( di=-1; di<2; ++di )); do
(( ni = i + di ))
if (( torus )); then
(( ni = (ni + height) % height ))
fi
for (( dj=-1; dj<2; ++dj )); do
(( nj = j + dj ))
if (( torus )); then
(( nj = (nj + width) % width ))
fi
if (( (di || dj) && ni >= 0 && nj >= 0 && ni < height && nj < width )); then
(( n += ${cells[$ni,$nj]} ))
fi
done
done
printf '%d' "$(( ( n == 3 ) || ( ${cells[$i,$j]} && n==2 ) ))"
done
printf '\n'
done
}
 
main "$@"</syntaxhighlight>
 
{{Out}}
<pre>Generation 0
. . .
@ @ @
. . .
 
Generation 1
. @ .
. @ .
. @ .
 
Generation 2
. . .
@ @ @
. . .
 
Generation 3
. @ .
. @ .
. @ .</pre>
 
=={{header|Ursala}}==
Line 16,120 ⟶ 17,205:
sequence of n boards evolving from it.
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 16,127 ⟶ 17,212:
neighborhoods = ~&thth3hthhttPCPthPTPTX**K7S+ swin3**+ swin3@hNSPiCihNCT+ --<0>*+ 0-*
 
evolve "n" = next"n" rule**+ neighborhoods</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">blinker =
 
(==`O)**t -[
Line 16,147 ⟶ 17,232:
#show+
 
examples = mat0 ~&?(`O!,`+!)*** evolve3(blinker)-- evolve5(glider)</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">+++
Line 16,203 ⟶ 17,288:
Two <tt>Replace</tt> commands are then used to change characters into '.' or 'O' to represent dead and living cells in the new generation.
 
<langsyntaxhighlight lang="vedit">IT("Generation 0 ") IN
IT(".O.") IN
IT(".O.") IN
Line 16,260 ⟶ 17,345:
Ins_Char(Cur_Char+1,OVERWRITE)
}
Return</langsyntaxhighlight>
 
{{out}}
Line 16,280 ⟶ 17,365:
=={{header|Wortel}}==
Mapping over a matrix.
<langsyntaxhighlight lang="wortel">@let {
life &m ~!* m &[a y] ~!* a &[v x] @let {
neigh @sum [
Line 16,303 ⟶ 17,388:
!^life 2 blinker
]]
}</langsyntaxhighlight>
{{out}}
<pre>[
Line 16,324 ⟶ 17,409:
 
Different solution by using functions that operate on matrices.
<langsyntaxhighlight lang="wortel">@let {
; Translation of the APL game of life (http://catpad.net/michael/apl/).
life &m @let {
Line 16,376 ⟶ 17,461:
!^life 2 blinker
]]
}</langsyntaxhighlight>
{{out}}
<pre>[
Line 16,397 ⟶ 17,482:
 
=={{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 glidergliders isare always alive. Must be invoked from cscript.
<syntaxhighlight lang="vb">
<lang vb>
option explicit
const tlcr=3, tlcc=3
Line 16,484 ⟶ 17,569:
next
end function
</syntaxhighlight>
</lang>
<pre>
Conway's Game of Life
Line 16,508 ⟶ 17,593:
</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
<syntaxhighlight lang="vb">
<lang vb>
option explicit
const pix="##"
Line 16,614 ⟶ 17,699:
nextgen=nextgen+1
end sub
</syntaxhighlight>
</lang>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import rand
import strings
import time
Line 16,715 ⟶ 17,800:
time.sleep(time.second / 30)
}
}</langsyntaxhighlight>
 
{{out}}
Line 16,736 ⟶ 17,821:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "timer" for Timer
 
Line 16,840 ⟶ 17,925:
}
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 16,939 ⟶ 18,024:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">def M=3; \array size
char NowGen(M+2, M+2), \size with surrounding borders
NewGen(M+2, M+2);
Line 16,970 ⟶ 18,055:
I:= NowGen; NowGen:= NewGen; NewGen:= I; \swap arrays
];
]</langsyntaxhighlight>
 
{{out}}
Line 16,989 ⟶ 18,074:
=={{header|XSLT}}==
So when the following templates
<langsyntaxhighlight lang="xml"><xsl:template match="/table">
<table>
<xsl:apply-templates />
Line 17,037 ⟶ 18,122:
<xsl:template name="live">
<td>X</td>
</xsl:template></langsyntaxhighlight>
are applied against the document
<langsyntaxhighlight 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>
</table></langsyntaxhighlight>
then the transformed XML document contains the new universe evolved by one tick:
<langsyntaxhighlight lang="html"><table>
<tr><td>_</td><td>_</td><td>_</td></tr>
<tr><td>X</td><td>X</td><td>X</td></tr>
<tr><td>_</td><td>_</td><td>_</td></tr>
</table></langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
Line 17,059 ⟶ 18,144:
if INITLINES is set to 0 the code will show the blinker
 
<langsyntaxhighlight lang="z80">;MSX Bios calls
CHPUT equ 000A2H ;print character A
CHGET equ 0009FH ;wait for keyboard input
Line 17,215 ⟶ 18,300:
;force 16k ROM size binary output
EndOfCode dc 0x8000 - EndOfCode, 0xFF
end</langsyntaxhighlight>
 
=={{header|Yabasic}}==
{{output?|Yabasic}}
{{trans|BASIC256}}
<langsyntaxhighlight Yabasiclang="yabasic">// Conway's_Game_of_Life
X = 59 : Y = 35 : H = 4
Line 17,289 ⟶ 18,374:
else
print "Stabilized in ", s-2, " iterations"
end if</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">class Life{
fcn init(n, r1,c1, r2,c2, etc){
var N=n, cells=Data(n*n), tmp=Data(n*n),
Line 17,326 ⟶ 18,411:
}
fcn dance(n=300){ do(n){ toAnsi().print(); Atomic.sleep(0.2); cycle(); } }
}</langsyntaxhighlight>
The data structure is a Data, which is a linear block of bytes.
<langsyntaxhighlight lang="zkl">cells:=Life(4, 0,1, 1,1, 2,1); // blinker
do(3){ cells.println("="*4); cells.cycle(); }
 
cells:=Life(30, 0,1, 1,2, 2,0, 2,1, 2,2); // glider
cells.dance(100);</langsyntaxhighlight>
{{out}}
Just the glider (reformatted), if you have an ANSI terminal (eg xterm), you'll see the glider moving down the screen.
Line 17,344 ⟶ 18,429:
 
=={{header|ZPL}}==
<langsyntaxhighlight ZPLlang="zpl">program Life;
 
config var
Line 17,371 ⟶ 18,456:
TW := (TW & NN = 2) | ( NN = 3);
until !(|<< TW);
end;</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
Line 17,377 ⟶ 18,462:
 
The ZX Spectrum was shipped with a demo tape called ''Horizons'', which included an implementation of Life; however, it relied on machine code.
<langsyntaxhighlight lang="zxbasic">10 REM Initialize
20 LET w=32*22
30 DIM w$(w): DIM n$(w)
Line 17,397 ⟶ 18,482:
190 PRINT AT 0,0;w$
200 LET w$=n$
210 GO TO 80</langsyntaxhighlight>
6

edits