Conway's Game of Life: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|APL}}: correct spelling of Dyalog)
m (syntax highlighting fixup automation)
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,221:
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:
0 0 0 0 0
 
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
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.
 
<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:
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:
 
-- 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:
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:
**"
-- Run for 500 generations in a 100 x 100 universe.
runGame(GosperGliderGun, {100, 100}, 500)</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
Line 1,544:
{{works with|TI-Nspire}}
 
<langsyntaxhighlight ARMlang="arm Assemblyassembly"> .string "PRG"
 
lcd_ptr .req r4
Line 1,640:
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:
 
GuiClose: ; exit when GUI is closed
ExitApp</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 1,692:
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:
}
}
</syntaxhighlight>
</lang>
 
{{out}} Finally:
Line 1,749:
 
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:
End
End
Return</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 1,802:
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:
 
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:
else
print "Stabilized in "+(s-2)+" iterations"
end if</langsyntaxhighlight>
{{out}}
<pre>
Line 1,882:
==={{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:
SWAP old&(), new&()
WAIT 30
UNTIL FALSE</langsyntaxhighlight>
{{out}}
<BR>
Line 1,923:
==={{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:
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:
Print " Press any key to exit "
Sleep
End</langsyntaxhighlight>
 
==={{header|GFA Basic}}===
 
<syntaxhighlight lang="text">
'
' Conway's Game of Life
Line 2,319:
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:
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:
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:
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:
Until Inkey() <> ""
PrintN("Press any key to exit"): Repeat: Until Inkey() <> ""</langsyntaxhighlight>
'''Sample output:'''<br>
[[File:Game-of-life-PureBasic.gif‎]]
Line 2,566:
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:
LOOP UNTIL y > 80
PCOPY 0, 1
LOOP WHILE INKEY$ = ""</langsyntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
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>.
<langsyntaxhighlight lang="basic">1000 LET M=LEN L$(1)
1010 DIM N$(M,M)
1020 FOR I=0 TO M+1
Line 2,705:
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:
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:
:[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:
:End
:End
</syntaxhighlight>
</lang>
 
==={{header|TI-89 BASIC}}===
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.
 
<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:
setGraph("Grid", save[2])
setGraph("Labels", save[3])
EndPrgm</langsyntaxhighlight>
 
=={{header|Batch File}}==
Line 2,848:
If no parameters are parsed, it defaults to 5 iterations of the blinking example.
 
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 2,957:
 
exit /b
</syntaxhighlight>
</lang>
{{out}}
Blinking example:
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.
 
<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:
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:
=={{header|Brat}}==
 
<langsyntaxhighlight lang="brat">width = 3
height = 3
rounds = 3
Line 3,157:
p
step
}</langsyntaxhighlight>
 
{{out}}
Line 3,175:
 
=={{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:
 
blinker←>⟨0‿0‿0,1‿1‿1,0‿0‿0⟩
(<".#") ⊏¨˜ Life⍟(↕3) blinker</langsyntaxhighlight>
{{out}}
<pre>┌─
Line 3,194:
=={{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:
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:
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:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Text;
Line 3,601:
}
 
</syntaxhighlight>
</lang>
 
Output:
<syntaxhighlight lang="text">
Frame 1: Frame 2: Frame 3:
██
██████ ██ ██████
██
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="c">#include <iostream>
#define HEIGHT 4
#define WIDTH 4
Line 3,817:
gol2.iterate(4);
}
</syntaxhighlight>
</lang>
{{out}} first a glider, then a blinker, over a few iterations
(reformatted for convenience).
Line 3,837:
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:
return system( "pause" );
}
</syntaxhighlight>
</lang>
{{out}}<pre>
+--------------------+ +--------------------+ +--------------------+ +--------------------+
Line 4,042:
Shows a glider over 20 generations
Board edges wrap around to simulate infinite board
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 4,127:
}
}
</syntaxhighlight>
</lang>
{{out}}<pre>
generation 0:
Line 4,180:
 
=={{header|Chapel}}==
<langsyntaxhighlight lang="chapel">
config const gridHeight: int = 3;
config const gridWidth: int = 3;
Line 4,247:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,273:
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:
(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 lang="cobol">identification division.
program-id. game-of-life-program.
data division.
Line 4,371:
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.</langsyntaxhighlight>
{{out}}
<pre>GENERATION 0:
Line 4,395:
 
=={{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:
(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:
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:
 
(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:
uni.writeln;
}
}</langsyntaxhighlight>
{{out|Output, first iteration}}
<pre>-------------------------------------------------------------
Line 4,594:
===Faster Version===
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.typetuple,
std.array, std.conv;
 
Line 4,664:
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:
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:
});
});
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,951:
{{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:
end;
readln;
end.</langsyntaxhighlight>
{{out}}
<pre> * *** * * *
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.)
 
<langsyntaxhighlight lang="e">def gridWidth := 3
def gridHeight := 3
def X := 0..!gridWidth
Line 5,165:
currentFrame := frame
println(currentFrame)
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
Line 5,171:
[https://easylang.online/apps/game-of-life.html Run it]
 
<syntaxhighlight lang="text">n = 70
n += 1
subr init
Line 5,231:
len p[] n * n + n + 1
call init
timer 0</langsyntaxhighlight>
 
=={{header|eC}}==
{{libheader|Ecere}}
 
<syntaxhighlight lang="ec">
<lang eC>
import "ecere"
 
Line 5,332:
 
GameOfLife life {};
</syntaxhighlight>
</lang>
 
=={{header|Egel}}==
 
<langsyntaxhighlight Egellang="egel">import "prelude.eg"
import "io.ego"
 
Line 5,390:
let _ = map [ G -> let _ = print "generation:\n" in printboard G ] {GEN0, GEN1, GEN2} in
nop
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 5.0, using cellular library
<langsyntaxhighlight lang="elena">import extensions;
import system'threading;
import cellular;
Line 5,509:
 
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:
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:
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight lang="lisp">#!/usr/bin/env emacs -script
;; -*- lexical-binding: t -*-
;; run: ./conways-life conways-life.config
Line 5,766:
(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:
;; This is a custom pattern.
(4 4 (".***"
"***."))))</langsyntaxhighlight>
 
{{out}}
Line 5,812:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
 
-module(life).
Line 6,021:
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:
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:
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:
 
!!'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:
'''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:
**
*
Generation 1 ok</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran"> PROGRAM LIFE_2D
IMPLICIT NONE
Line 6,459:
END SUBROUTINE NextgenV2
!###########################################################################
END PROGRAM LIFE_2D</langsyntaxhighlight>
{{out}}
<pre style="height:45ex;overflow:scroll">
Line 6,586:
=={{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:
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:
 
repeat 5
iteration()</langsyntaxhighlight>
 
{{out}}
Line 6,831:
 
=={{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:
{ „x” } { „y” } { „n” }
 
</syntaxhighlight>
</lang>
 
=={{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:
iteration board in
to_int_board board
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 7,083:
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:
=={{header|Groovy}}==
 
<syntaxhighlight lang="groovy">
<lang Groovy>
class GameOfLife {
 
Line 7,210:
game.board = game.createGliderBoard()
game.start()
</syntaxhighlight>
</lang>
 
The output of this program:
Line 7,388:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Array.Unboxed
 
type Grid = UArray (Int,Int) Bool
Line 7,409:
 
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:
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:
putStrLn "Blinker >> 3"
putStrLn "------------"
runLife 3 blinker</langsyntaxhighlight>
 
=={{header|HolyC}}==
Line 7,506:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">global limit
 
procedure main(args)
Line 7,584:
initial count := 0
return ((count +:= 1) > \limit) | (trim(!g) == " ")
end</langsyntaxhighlight>
 
A sample run:
Line 7,620:
=={{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:
 
'''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:
0 0 0
1 1 1
0 0 0</langsyntaxhighlight>
 
'''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:
=={{header|JAMES II/Rule-based Cellular Automata}}==
{{libheader|JAMES II}}
<langsyntaxhighlight lang="j2carules">@caversion 1;
 
dimensions 2;
Line 7,699:
ALIVE
*/
rule{DEAD}:ALIVE{3}->ALIVE;</langsyntaxhighlight>
Animated output for the blinker example:
 
Line 7,705:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class GameOfLife{
public static void main(String[] args){
String[] dish= {
Line 7,795:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Generation 0:
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.
Use the input file given below to create a cool screensaver on your terminal.
<langsyntaxhighlight lang="java">
//package conway;
 
Line 7,968:
}
}
</syntaxhighlight>
</lang>
 
Glider Gun design. Save it in GOLglidergun.txt and uncomment the setCustomConfig function.
Line 7,998:
 
===Java 10===
<langsyntaxhighlight lang="java">
import static java.util.List.of;
 
Line 8,091:
 
}
</syntaxhighlight>
</lang>
Outputs:
<pre>
Line 8,112:
{{works with|SpiderMonkey}}
{{works with|V8}}
<langsyntaxhighlight lang="javascript">function GameOfLife () {
 
this.init = function (turns,width,height) {
Line 8,210:
print("---\nRandom 5x10");
game.init(5,5,10);
game.start();</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">---
Line 8,335:
{{libheader|HTML5}}
Essentially the same as the above straight [[JavaScript]] but displayed in an [[HTML5]] Canvas.
<langsyntaxhighlight lang="javascript">
<html>
<head>
Line 8,486:
</canvas><br>
</body>
</html></langsyntaxhighlight>
{{out}} for 3x3 Blinker:
 
Line 8,493:
 
'''More functional style''':
<langsyntaxhighlight lang="javascript">
const _ = require('lodash');
 
Line 8,535:
displayWorld(world);
}, 1000);
</syntaxhighlight>
</lang>
 
'''ES6 + ''':
<langsyntaxhighlight lang="javascript">
const alive = 1;
const dead = 0;
Line 8,610:
run()
 
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
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))
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:
end )
| [., $lines, $w] ;
</syntaxhighlight>
</lang>
'''Animation''':
<langsyntaxhighlight lang="jq"># "clear screen":
def cls: "\u001b[2J";
 
Line 8,688:
# 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:
"| .. |\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:
+---+
 
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:
 
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 8,898:
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:
 
julia> gameOfLife(15, 30, 5)
30x15x5 Cellular Automaton</langsyntaxhighlight>
 
# ## # ###### ### ### ##
Line 8,996:
=== 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:
lifegame("lwss.gif", lwss)
lifegame("glidergun.gif", glidergun, 90, 200)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 9,050:
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:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 9,260:
=={{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:
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:
end
for i = 6,20 do life:evolve() end
life:render()</langsyntaxhighlight>
{{out}}
<pre>GLIDER:
Line 9,408:
□ □ □ □ □ □ □ □ □ □</pre>
=={{header|ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
# # Version AJM 93u+ 2012-08-01
Line 9,502:
_game ${h} ${w}
 
</syntaxhighlight>
</lang>
 
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Life {
Font "courier new"
Line 9,581:
}
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:
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:
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:
 
=={{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:
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:
[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>
 
=={{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,896:
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:
swap(univ,utmp)
 
sleep 200</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let get g x y =
try g.(x).(y)
with _ -> 0
Line 9,990:
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:
=== 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:
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.
 
Line 10,139:
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,213:
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,290:
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,736:
Else
Return
</syntaxhighlight>
</lang>
{{out}}
<pre>blinker.txt
Line 10,752:
 
=={{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,855:
{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,868:
};
M=[0,1,0;0,1,0;0,1,0];
for(i=1,3,print(M);M=step(M))</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 10,875:
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,054:
PrintGen;
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
Line 11,064:
would do 15 iterations over 5 rows and 10 columns.
<langsyntaxhighlight lang="perl">my ($width, $height, $generations) = @ARGV;
 
my $printed;
Line 11,122:
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,155:
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,173:
s/$neighborhood/ substr " $&# ", "$1$2$3$4" =~ tr|#||, 1 /ge;
print;
}</langsyntaxhighlight>
{{out}}
Line 11,200:
{{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,358:
<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,425:
[1,1,1],
[0,0,0]],
I=1,J=1.</langsyntaxhighlight>
 
{{out}}
Line 11,446:
 
===Testing some more forms===
<langsyntaxhighlight Picatlang="picat">go2 =>
Rows = 20,
Cols = 20,
Line 11,493:
[0,0,0,1,1,1],
[0,0,0,1,1,1]],
I=10,J=10.</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Line 11,499:
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,528:
(=: life (: next)) ) ) ) ) )
 
(life 5 5 b3 c3 d3)</langsyntaxhighlight>
Output:
<pre> 5
Line 11,550:
 
=={{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,609:
end;
end;
end Conway;</langsyntaxhighlight>
Results:
<pre>
Line 11,653:
 
=={{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,740:
 
showCell(cell) =
if cell == 1 then "*" else " "</langsyntaxhighlight>
 
=={{header|PostScript}}==
<langsyntaxhighlight PostScriptlang="postscript">%!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400
 
Line 11,791:
 
1000 { drawboard showpage iter } repeat
%%EOF</langsyntaxhighlight>
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">
<lang Prolog>
%----------------------------------------------------------------------%
% GAME OF LIFE %
Line 11,974:
write_line(S,T).
write_line(_,[]) :- !.
</syntaxhighlight>
</lang>
 
'''Sample output:'''<br>
Line 11,983:
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,122:
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,235:
if p != last_cell:
last_cell = p
grid[i][j] = (1, 0)[grid[i][j]]</langsyntaxhighlight>
 
=={{header|Python}}==
Line 12,250:
of <u>universe</u> returns zero.
 
<langsyntaxhighlight lang="python">import random
from collections import defaultdict
 
Line 12,304:
for c in range(col-1, col+2) )
) ]
universe = nextgeneration</langsyntaxhighlight>
{{out}} (sample)
<pre style="height:30ex;overflow:scroll">
Line 12,327:
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,363:
 
 
life(world, 5)</langsyntaxhighlight>
 
{{out}}
Line 12,430:
 
===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,491:
 
conway_life()</langsyntaxhighlight>
 
=={{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,575:
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,709:
;;; (game-of-life (thunder) 2)
;;; (game-of-life (cross) 2)
</syntaxhighlight>
</lang>
 
Output for an 80x80 cross:
Line 12,717:
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>class Automaton {
subset World of Str where {
.lines>>.chars.unique == 1 and m/^^<[.#\n]>+$$/
Line 12,774:
say $glider++;
say '--';
}</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Rebollang="rebol">Red [
Purpose: "Conway's Game of Life"
Author: "Joe Smith"
Line 12,833:
conway *8-8
]
</syntaxhighlight>
</lang>
 
{{out}}
Line 13,066:
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">:w/l [ $. eq? [ #0 ] [ #1 ] choose , ] s:for-each ;
 
'World d:create
Line 13,135:
}}
#12 gens</langsyntaxhighlight>
 
=={{header|REXX}}==
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)
<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,185:
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,216:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 02.08.2014 Walter Pachl
* Input is a file containing the initial pattern
Line 13,400:
Return lineout(dbg,arg(1))
Else
Return</langsyntaxhighlight>
{{out}}
<pre> blinker
Line 13,421:
 
=={{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,484:
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,602:
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,706:
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,783:
life(glider, 20, 8, 8);
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
Line 13,791:
{{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,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)) 30)</langsyntaxhighlight>
 
{{out}}
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.
 
<syntaxhighlight lang="text">Init_state=[0 0 0;...
1 1 1;...
0 0 0];
Line 14,280:
Curr_state=Next_state;
end</langsyntaxhighlight>
 
{{out}}
Line 14,320:
 
=={{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,392:
wait 1 second
end repeat
end RunGameOfLife</langsyntaxhighlight>
 
=={{header|SequenceL}}==
Line 14,398:
 
'''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,418:
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,600:
}
throw(errno);
}</langsyntaxhighlight>
 
'''Usage:'''
Line 14,633:
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,667:
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,803:
[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,838:
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,007:
 
END.
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 15,308:
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,314:
"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,366:
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,429:
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,475:
self showBoard.
self redrawNeeded.
</syntaxhighlight>
</lang>
 
=={{header|SQL}}==
Line 15,481:
 
{{works with|Oracle}}
<langsyntaxhighlight lang="sql">
-- save these lines in a file called
-- setupworld.sql
Line 15,598:
from output
order by y desc;
</syntaxhighlight>
</lang>
 
<pre>
Line 15,630:
{{trans|Rust}}
 
<langsyntaxhighlight lang="swift">struct Cell: Hashable {
var x: Int
var y: Int
Line 15,724:
 
print("Glider: ")
col.run(iterations: 20)</langsyntaxhighlight>
 
{{out}}
Line 15,962:
=={{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,990:
end
 
endmodule</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc main {} {
Line 16,072:
}
 
main</langsyntaxhighlight>
<pre style='height:30ex; overflow:scroll'>blinker generation 1:
. # .
Line 16,116:
{{works with|Korn Shell}}
{{works with|Z Shell}}
<langsyntaxhighlight lang="bash"># Shells only have 1-dimensional arrays, so each row is one string
function main {
typeset blinker=(000 111 000)
Line 16,234:
}
 
main "$@"</langsyntaxhighlight>
 
{{Out}}
Line 16,264:
sequence of n boards evolving from it.
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 16,271:
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,291:
#show+
 
examples = mat0 ~&?(`O!,`+!)*** evolve3(blinker)-- evolve5(glider)</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">+++
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.
 
<langsyntaxhighlight lang="vedit">IT("Generation 0 ") IN
IT(".O.") IN
IT(".O.") IN
Line 16,404:
Ins_Char(Cur_Char+1,OVERWRITE)
}
Return</langsyntaxhighlight>
 
{{out}}
Line 16,424:
=={{header|Wortel}}==
Mapping over a matrix.
<langsyntaxhighlight lang="wortel">@let {
life &m ~!* m &[a y] ~!* a &[v x] @let {
neigh @sum [
Line 16,447:
!^life 2 blinker
]]
}</langsyntaxhighlight>
{{out}}
<pre>[
Line 16,468:
 
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,520:
!^life 2 blinker
]]
}</langsyntaxhighlight>
{{out}}
<pre>[
Line 16,542:
=={{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.
<syntaxhighlight lang="vb">
<lang vb>
option explicit
const tlcr=3, tlcc=3
Line 16,628:
next
end function
</syntaxhighlight>
</lang>
<pre>
Conway's Game of Life
Line 16,652:
</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,758:
nextgen=nextgen+1
end sub
</syntaxhighlight>
</lang>
 
=={{header|Vlang}}==
{{trans|Go}}
<langsyntaxhighlight lang="vlang">import rand
import strings
import time
Line 16,859:
time.sleep(time.second / 30)
}
}</langsyntaxhighlight>
 
{{out}}
Line 16,880:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="ecmascript">import "random" for Random
import "timer" for Timer
 
Line 16,984:
}
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 17,083:
 
=={{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 17,114:
I:= NowGen; NowGen:= NewGen; NewGen:= I; \swap arrays
];
]</langsyntaxhighlight>
 
{{out}}
Line 17,133:
=={{header|XSLT}}==
So when the following templates
<langsyntaxhighlight lang="xml"><xsl:template match="/table">
<table>
<xsl:apply-templates />
Line 17,181:
<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,203:
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,359:
;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,433:
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,470:
}
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,488:
 
=={{header|ZPL}}==
<langsyntaxhighlight ZPLlang="zpl">program Life;
 
config var
Line 17,515:
TW := (TW & NN = 2) | ( NN = 3);
until !(|<< TW);
end;</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
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.
<langsyntaxhighlight lang="zxbasic">10 REM Initialize
20 LET w=32*22
30 DIM w$(w): DIM n$(w)
Line 17,541:
190 PRINT AT 0,0;w$
200 LET w$=n$
210 GO TO 80</langsyntaxhighlight>
10,327

edits