Conway's Game of Life: Difference between revisions

no edit summary
No edit summary
 
(97 intermediate revisions by 43 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}}==
I went a little further and created a 40x30 grid, but this implementation is accurate and does have a blinker in it. As always, thanks to Keith of Chibiakumas for the cartridge header and hardware routines. This is the source code for a Sega Genesis game that you can compile with VASM. (It was tested in the Fusion emulator but it should work anywhere.)
 
Explanation of the implementation:
* I'm using the Genesis's foreground tilemap to create the graphics.
* Grid boundaries are handled by using the classic trick of padding all sides with a value that's not used in the "real" grid, and always counts as a dead cell.
* Every iteration of the main loop does the same thing: check neighbors of each cell in the grid, write the next generation to a buffer, copy that buffer over the original, and display the output. This way, updates don't impact the outcome of the rest of the cells down the line (which would go against the rules of the game, as all cell births/deaths happen simultaneously.)
 
Explanation of macros:
* pushRegs = <tt>MOVEM.L ___,-(SP)</tt>
* popRegs = <tt>MOVEM.L (SP)+,___</tt>
* pushLong = <tt>MOVE.L ___,-(SP)</tt>
* popLong = <tt>MOVE.L (SP)+,___</tt>
 
<syntaxhighlight lang="68000devpac">include "\SrcALL\68000_Macros.asm"
;Ram Variables
Cursor_X equ $00FF0000 ;Ram for Cursor Xpos
Cursor_Y equ $00FF0000+1 ;Ram for Cursor Ypos
 
conwayTilemapRam equ $00FF1000
conwayBackupTilemapRam equ $00FF2000
;Video Ports
VDP_data EQU $C00000 ; VDP data, R/W word or longword access only
VDP_ctrl EQU $C00004 ; VDP control, word or longword writes only
 
;constants
ROWLENGTH equ 40
 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Traps
DC.L $FFFFFE00 ;SP register value
DC.L ProgramStart ;Start of Program Code
DS.L 7,IntReturn ; bus err,addr err,illegal inst,divzero,CHK,TRAPV,priv viol
DC.L IntReturn ; TRACE
DC.L IntReturn ; Line A (1010) emulator
DC.L IntReturn ; Line F (1111) emulator
DS.L 4,IntReturn ; Reserverd /Coprocessor/Format err/ Uninit Interrupt
DS.L 8,IntReturn ; Reserved
DC.L IntReturn ; spurious interrupt
DC.L IntReturn ; IRQ level 1
DC.L IntReturn ; IRQ level 2 EXT
DC.L IntReturn ; IRQ level 3
DC.L IntReturn ; IRQ level 4 Hsync
DC.L IntReturn ; IRQ level 5
DC.L IntReturn ; IRQ level 6 Vsync
DC.L IntReturn ; IRQ level 7
DS.L 16,IntReturn ; TRAPs
DS.L 16,IntReturn ; Misc (FP/MMU)
 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Header
DC.B "SEGA GENESIS " ;System Name
DC.B "(C)CHBI " ;Copyright
DC.B "2019.JAN" ;Date
DC.B "ChibiAkumas.com " ; Cart Name
DC.B "ChibiAkumas.com " ; Cart Name (Alt)
DC.B "GM CHIBI001-00" ;TT NNNNNNNN-RR T=Type (GM=Game) N=game Num R=Revision
DC.W $0000 ;16-bit Checksum (Address $000200+)
DC.B "J " ;Control Data (J=3button K=Keyboard 6=6button C=cdrom)
DC.L $00000000 ;ROM Start
DC.L $003FFFFF ;ROM Length
DC.L $00FF0000,$00FFFFFF ;RAM start/end (fixed)
DC.B " " ;External RAM Data
DC.B " " ;Modem Data
DC.B " " ;MEMO
DC.B "JUE " ;Regions Allowed
 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Generic Interrupt Handler
IntReturn:
rte
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Program Start
ProgramStart:
;initialize TMSS (TradeMark Security System)
move.b ($A10001),D0 ;A10001 test the hardware version
and.b #$0F,D0
beq NoTmss ;branch if no TMSS chip
move.l #'SEGA',($A14000);A14000 disable TMSS
NoTmss:
 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Set Up Graphics
 
lea VDPSettings,A5 ;Initialize Screen Registers
move.l #VDPSettingsEnd-VDPSettings,D1 ;length of Settings
move.w (VDP_ctrl),D0 ;C00004 read VDP status (interrupt acknowledge?)
move.l #$00008000,d5 ;VDP Reg command (%8rvv)
NextInitByte:
move.b (A5)+,D5 ;get next video control byte
move.w D5,(VDP_ctrl) ;C00004 send write register command to VDP
; 8RVV - R=Reg V=Value
add.w #$0100,D5 ;point to next VDP register
dbra D1,NextInitByte ;loop for rest of block
 
 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Set up palette and graphics
move.l #$C0000000,d0 ;Color 0
move.l d0,VDP_Ctrl
MOVE.W #$0A00,VDP_Data ;BLUE
move.l #$C01E0000,d0 ;Color 0
move.l d0,VDP_Ctrl
MOVE.W #$00EE,VDP_Data ;YELLOW
lea Graphics,a0 ;background tiles
move.w #(GraphicsEnd-Graphics)-1,d1 ;data size
CLR.L D2 ;start loading at tile 0 of VRAM
jsr DefineTiles
clr.b Cursor_X ;Clear Cursor XY
clr.b Cursor_Y
;Turn on screen
move.w #$8144,(VDP_Ctrl);C00004 reg 1 = 0x44 unblank display
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; TESTING AREA
 
;load the tilemaps
LEA Conway_Tilemap,a3
LEA ConwayTilemapRam,A2
move.l #(Conway_Backup_Tilemap-Conway_Tilemap),d1
JSR LDIR
LEA Conway_Backup_Tilemap,a3
LEA conwayBackupTilemapRam,A2
move.l #(Conway_Backup_Tilemap-Conway_Tilemap),d1
JSR LDIR
CLR.B Cursor_X
CLR.B Cursor_Y
;print the tilemap once
LEA ConwayTilemapRam,A3
JSR Conway_Print
main:
;do the behavior
jsr Conway_CheckTilemap
;copy the tilemap
lea conwayBackupTilemapRam,A3
LEA ConwayTilemapRam,A2
move.l #(Conway_Backup_Tilemap-Conway_Tilemap),d1
jsr LDIR
CLR.B Cursor_X
CLR.B Cursor_Y
;print the tilemap
LEA ConwayTilemapRam,A3
JSR Conway_Print
;repeat
JMP main
 
Conway_CheckTilemap:
;since we don't want the partial results of the checks to mess with later ones, we'll copy the changes to a buffer, and then
;have that buffer clobber the original. That way, all changes to the ecosystem are effectively atomic.
LEA ConwayTilemapRam,A0
LEA conwayBackupTilemapRam,A6
LEA (ROWLENGTH+3,A0),A0 ;actual data starts here
LEA (ROWLENGTH+3,A6),A6 ;actual data starts here
.loop:
MOVE.B (A0),D2
CMP.B #255,D2
BEQ .done
CMP.B #2,D2
BEQ .overhead
JSR Conway_CheckNeighbors
 
pushLong D0
JSR popcnt_8
MOVE.B D0,D3
popLong D0
;now implement the table here.
;neighbor bits in D0
;current state in D2
;popcnt in D3
;pointer to where we are in A0
;the only time the current state is relevant to the output, is when popcnt = 2. Otherwise, it's entirely determined by popcnt.
CMP.B #4,D3
BCC .DeadCell
CMP.B #1,D3
BLS .DeadCell
CMP.B #3,D3
BEQ .LiveCell
;else, must be 2.
MOVE.B D2,(A6) ;store current value into backup table.
bra .overhead
.LiveCell:
MOVE.B #1,(A6)
BRA .overhead
.DeadCell:
MOVE.B #0,(A6) ;store in backup table.
.overhead:
ADDA.L #1,A0
ADDA.L #1,A6
JMP .loop
.done:
RTS
 
popcnt_8:
pushRegs D2-D5
MOVEQ #8-1,D5
MOVEQ #0,D3
.loop:
ROR.B #1,D0
BCC .overhead
ADDQ.B #1,D3
.overhead:
dbra d5,.loop
MOVE.B D3,D0
popRegs D2-D5
RTS
 
Conway_CheckNeighbors:
;A0 = pointer to where we are in the tilemap.
;returns: D0.B = uUrRdDlL
;u = top left
;U = top
;r = top Right
;R = Right
;d = bottom right
;D = bottom
;l = bottom Left
;L = Left
pushRegs D2-D5/A0
MOVEQ #0,D0
MOVE.L A0,A1
MOVE.L A1,A2
SUBA.L #ROWLENGTH+2,A1 ;POINTS ABOVE
ADDA.L #ROWLENGTH+2,A2 ;POINTS BELOW
MOVE.B (A1),D1
MOVE.B (A2),D2
CMP.B #1,D1
BNE .noUpper
BSET #6,D0
bra .next
.noUpper:
BCLR #6,D0
.next:
CheckLower:
CMP.B #1,D2
BNE .noLower
BSET #2,D0
bra .next
.noLower:
BCLR #2,D0
.next:
 
SUBA.L #1,A0 ;left
SUBA.L #1,A1 ;upper-left
SUBA.L #1,A2 ;lower-left
MOVE.B (A1),D1
MOVE.B (A2),D2
MOVE.B (A0),D3
CheckUpperLeft:
CMP.B #1,D1
BNE .noUpperLeft
BSET #7,D0
bra .next
.noUpperLeft:
BCLR #7,D0
.next:
 
CheckLowerLeft:
CMP.B #1,D2
BNE .noLowerLeft
BSET #1,D0
bra .next
.noLowerLeft:
BCLR #1,D0
.next:
 
CheckLeft:
CMP.B #1,D3
BNE .noLeft
BSET #0,D0
bra .next
.noLeft:
BCLR #0,D0
.next:
 
 
addA.L #2,A0
addA.L #2,A1
addA.L #2,A2
MOVE.B (A1),D1
MOVE.B (A2),D2
MOVE.B (A0),D3
CheckUpperRight:
CMP.B #1,D1
BNE .noUpperRight
BSET #5,D0
bra .next
.noUpperRight:
BCLR #5,D0
.next:
 
CheckLowerRight:
CMP.B #1,D2
BNE .noLowerRight
BSET #3,D0
bra .next
.noLowerRight:
BCLR #3,D0
.next:
 
CheckRight:
CMP.B #1,D3
BNE .noRight
BSET #4,D0
bra .next
.noRight:
BCLR #4,D0
.next:
popRegs D2-D5/A0
rts
Conway_Print:
;input: A3 = base address of tilemap
MOVE.B (A3)+,D0
CMP.B #255,D0
BEQ .done
CMP.B #2,D0
BEQ .skip
;else, print
JSR Conway_PrintChar
.skip
BRA Conway_Print
.done
rts
Conway_PrintChar: ;Show D0 to screen
moveM.l d0-d7/a0-a7,-(sp)
and.l #$FF,d0 ;Keep only 1 byte
Move.L #$40000003,d5 ;top 4=write, bottom $3=Cxxx range
MOVEQ #0,D4 ;Tilemap at $C000+
 
Move.B (Cursor_Y),D4
rol.L #8,D4 ;move $-FFF to $-FFF----
rol.L #8,D4
rol.L #7,D4 ;2 bytes per tile * 64 tiles per line
add.L D4,D5 ;add $4------3
Move.B (Cursor_X),D4
rol.L #8,D4 ;move $-FFF to $-FFF----
rol.L #8,D4
rol.L #1,D4 ;2 bytes per tile
add.L D4,D5 ;add $4------3
MOVE.L D5,(VDP_ctrl) ; C00004 write next character to VDP
MOVE.W D0,(VDP_data) ; C00000 store next word of name data
 
addq.b #1,(Cursor_X) ;INC Xpos
move.b (Cursor_X),d0
cmp.b #39,d0
bls .nextpixel_Xok
jsr NewLine ;If we're at end of line, start newline
.nextpixel_Xok:
moveM.l (sp)+,d0-d7/a0-a7
rts
;don't forget, these are in ROM so we can't write to them directly.
;instead, they will be copied to ram and worked with from there.
Conway_Tilemap: ;(screenwidth + 2) by (screenheight+2)
DC.B $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$01,$01,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$01,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$01,$01,$00,$00,$00,$00,$00,$00,$01,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$01,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02
DC.B 255
EVEN
Conway_Backup_Tilemap: ;(screenwidth + 2) by (screenheight+2)
DC.B $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02
rept 30
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
endr
DC.B $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02
DC.B 255
EVEN
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
NewLine:
addq.b #1,(Cursor_Y) ;INC Y
clr.b (Cursor_X) ;Zero X
rts
 
LDIR: ;COPY D1 BYTES FROM A3 TO A2
move.b (a3)+,(a2)+
DBRA D1,LDIR
rts
DefineTiles: ;Copy D1 bytes of data from A0 to VDP memory D2
jsr prepareVram ;Calculate the memory location we want to write
.again: ; the tile pattern definitions to
move.l (a0)+,(VDP_data)
dbra d1,.again
rts
prepareVram: ;To select a memory location D2 we need to calculate
;the command byte... depending on the memory location
pushall ;$7FFF0003 = Vram $FFFF.... $40000000=Vram $0000
move.l d2,d0
and.w #%1100000000000000,d0 ;Shift the top two bits to the far right
rol.w #2,d0
and.l #%0011111111111111,d2 ; shift all the other bits left two bytes
rol.l #8,d2
rol.l #8,d2
or.l d0,d2
or.l #$40000000,d2 ;Set the second bit from the top to 1
;#%01000000 00000000 00000000 00000000
move.l d2,(VDP_ctrl)
popallRTS:
popall
rts
Graphics:
DC.L $0000000F,$0000000F,$0000000F,$0000000F,$0000000F,$0000000F,$0000000F,$FFFFFFFF
DC.L $FFFFFFFF,$FFFFFFFF,$FFFFFFFF,$FFFFFFFF,$FFFFFFFF,$FFFFFFFF,$FFFFFFFF,$FFFFFFFF
GraphicsEnd:
 
VDPSettings:
DC.B $04 ; 0 mode register 1 ---H-1M-
DC.B $04 ; 1 mode register 2 -DVdP---
DC.B $30 ; 2 name table base for scroll A (A=top 3 bits) --AAA--- = $C000
DC.B $3C ; 3 name table base for window (A=top 4 bits / 5 in H40 Mode) --AAAAA- = $F000
DC.B $07 ; 4 name table base for scroll B (A=top 3 bits) -----AAA = $E000
DC.B $6C ; 5 sprite attribute table base (A=top 7 bits / 6 in H40) -AAAAAAA = $D800
DC.B $00 ; 6 unused register --------
DC.B $00 ; 7 background color (P=Palette C=Color) --PPCCCC
DC.B $00 ; 8 unused register --------
DC.B $00 ; 9 unused register --------
DC.B $FF ;10 H interrupt register (L=Number of lines) LLLLLLLL
DC.B $00 ;11 mode register 3 ----IVHL
DC.B $81 ;12 mode register 4 (C bits both1 = H40 Cell) C---SIIC
DC.B $37 ;13 H scroll table base (A=Top 6 bits) --AAAAAA = $FC00
DC.B $00 ;14 unused register --------
DC.B $02 ;15 auto increment (After each Read/Write) NNNNNNNN
DC.B $01 ;16 scroll size (Horiz & Vert size of ScrollA & B) --VV--HH = 64x32 tiles
DC.B $00 ;17 window H position (D=Direction C=Cells) D--CCCCC
DC.B $00 ;18 window V position (D=Direction C=Cells) D--CCCCC
DC.B $FF ;19 DMA length count low LLLLLLLL
DC.B $FF ;20 DMA length count high HHHHHHHH
DC.B $00 ;21 DMA source address low LLLLLLLL
DC.B $00 ;22 DMA source address mid MMMMMMMM
DC.B $80 ;23 DMA source address high (C=CMD) CCHHHHHH
VDPSettingsEnd:
even</syntaxhighlight>
{{out}}
[https://ibb.co/VN4KbSL Screenshot of emulator]
 
=={{header|ABAP}}==
{{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">
*&---------------------------------------------------------------------*
*& Report ZCONWAYS_GAME_OF_LIFE
*&---------------------------------------------------------------------*
*& by Marcelo Bovo
*&---------------------------------------------------------------------*
report zconways_game_of_life line-size 174 no standard page heading
line-count 40.
 
parameters: p_char type c default '#',
p_pos type string.
 
class lcl_game_of_life definition.
 
public section.
 
data: x_max type i value 174,
y_max type i value 40,
character type c value abap_true,
x type i,
y type i,
pos type string,
offlimits type i value 9998,
grid(9999) type c. " every X_MAX characters on grid equals one line on screen
 
data: o_random_y type ref to cl_abap_random_int,
o_random_x type ref to cl_abap_random_int.
 
methods: constructor,
play,
initial_position,
initial_grid,
write,
change_grid.
 
endclass.
 
class lcl_game_of_life implementation.
method constructor.
o_random_y = cl_abap_random_int=>create( seed = cl_abap_random=>create( conv i( sy-uzeit ) )->intinrange( low = 1 high = 999999 )
min = 1
max = y_max ).
 
o_random_x = cl_abap_random_int=>create( seed = cl_abap_random=>create( conv i( |{ sy-datum(4) }{ sy-uzeit }| ) )->intinrange( low = 1 high = 999999 )
min = 1
max = x_max ).
 
endmethod.
 
method play.
 
"fill initial data ramdonly if user hasnt typed any coordenates
if pos is initial.
initial_position( ).
endif.
 
initial_grid( ).
 
write( ).
 
endmethod.
 
method initial_position.
do cl_abap_random_int=>create( "seed = conv i( sy-uzeit )
min = 50
max = 800 )->get_next( ) times.
data(lv_index) = sy-index.
 
x = o_random_x->get_next( ).
y = o_random_y->get_next( ).
 
p_pos = |{ p_pos }{ switch char1( lv_index when '1' then space else ';' ) }{ y },{ x }|.
enddo.
endmethod.
 
method initial_grid.
 
"Split coordenates
split p_pos at ';' into table data(lt_pos_inicial) .
 
"Sort By Line(Easy to read)
sort lt_pos_inicial.
 
loop at lt_pos_inicial assigning field-symbol(<pos_inicial>).
 
split <pos_inicial> at ',' into data(y_char) data(x_char).
 
x = x_char.
y = y_char.
 
"Ensure maximum coordenates are not surpassed
x = cond #( when x <= x_max then x
else o_random_x->get_next( ) ).
 
y = cond #( when y <= y_max then y
else o_random_y->get_next( ) ).
 
"Write on string grid
"Every x_max lines represent one line(Y) on the grid
data(grid_xy) = ( x_max * y ) + x - x_max - 1.
grid+grid_xy(1) = character.
 
endloop.
 
endmethod.
 
method write.
 
skip to line 1.
 
"Write every line on screen
do y_max times.
data(lv_index) = sy-index - 1.
 
"Write whole line(current line plus number of maximum X characters)
data(grid_xy) = ( lv_index * x_max ).
 
write / grid+grid_xy(x_max) no-gap.
 
if grid+grid_xy(x_max) is initial.
skip.
endif.
 
enddo.
 
change_grid( ).
 
endmethod.
 
method change_grid.
 
data(grid_aux) = grid.
clear grid_aux.
data(grid_size) = strlen( grid ).
 
"Validate neighbours based on previous written grid
"ABC
"D.F
"GHI
do grid_size + x_max times.
 
"Doens't write anything beyond borders
check sy-index <= x_max * y_max.
 
data(grid_xy) = sy-index - 1.
 
data(neighbours) = 0.
 
"Current Line neighbours
data(d) = grid_xy - 1.
data(f) = grid_xy + 1.
 
"Line above neighbours
data(b) = grid_xy - x_max.
data(a) = b - 1.
data(c) = b + 1.
 
"Line Bellow neighbours
data(h) = grid_xy + x_max.
data(g) = h - 1.
data(i) = h + 1.
 
"Previous Neighbours
neighbours += cond #( when a < 0 then 0 else cond #( when grid+a(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when b < 0 then 0 else cond #( when grid+b(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when c < 0 then 0 else cond #( when grid+c(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when d < 0 then 0 else cond #( when grid+d(1) is not initial then 1 else 0 ) ).
 
"Next Neighbours
neighbours += cond #( when f > grid_size then 0 else cond #( when grid+f(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when g > grid_size then 0 else cond #( when grid+g(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when h > grid_size then 0 else cond #( when grid+h(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when i > grid_size then 0 else cond #( when grid+i(1) is not initial then 1 else 0 ) ).
 
grid_aux+grid_xy(1) = cond #( when neighbours = 3 or ( neighbours = 2 and grid+grid_xy(1) = character )
then character
else space ).
 
enddo.
 
grid = grid_aux.
 
endmethod.
endclass.
 
start-of-selection.
 
set pf-status 'STANDARD_FULLSCREEN'. "Use &REFRESH button with F8 Shortcut to go to next generation
 
data(lo_prog) = new lcl_game_of_life( ).
lo_prog->character = p_char.
lo_prog->pos = p_pos.
lo_prog->play( ).
 
at user-command.
 
case sy-ucomm.
when 'REFR' or '&REFRESH'.
sy-lsind = 1. "Prevents LIST_TOO_MANY_LEVELS DUMP
lo_prog->write( ).
when others.
leave list-processing.
endcase.
</syntaxhighlight>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun print-row (row)
(if (endp row)
nil
Line 369 ⟶ 1,072:
nil
(progn$ (print-grid grid)
(conway (conway-step grid) (1- steps)))))</langsyntaxhighlight>
 
{{out}}
Line 389 ⟶ 1,092:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">
WITH Ada.Text_IO; USE Ada.Text_IO;
Line 445 ⟶ 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 508 ⟶ 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 518 ⟶ 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 545 ⟶ 1,463:
0 0 0 0 0
 
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
 
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.
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation" -- For the regex at the top of newUniverse()
use scripting additions
 
-- The characters to represent the live and dead cells.
property live : "■" -- character id 9632 (U+25A0).
property dead : space
-- Infinite universes are expensive to maintain, so only a local region of universe is represented here.
-- Its invisible border is a wall of "dead" cells one cell deep, lined with a two-cell buffer layer into which
-- objects nominally leaving the region can disappear without being seen to hit the wall or bouncing back.
property borderThickness : 3
 
on newUniverse(seed, {w, h})
-- Replace every visible character in the seed text with "■" and every horizontal space with a space.
set seed to current application's class "NSMutableString"'s stringWithString:(seed)
set regex to current application's NSRegularExpressionSearch
tell seed to replaceOccurrencesOfString:("\\S") withString:(live) options:(regex) range:({0, its |length|()})
tell seed to replaceOccurrencesOfString:("\\h") withString:(dead) options:(regex) range:({0, its |length|()})
-- Ensure the universe dimensions are at least equal to the number of lines and the length of the longest.
set seedLines to paragraphs of (seed as text)
set lineCount to (count seedLines)
if (lineCount > h) then set h to lineCount
set seedWidth to 0
repeat with thisLine in seedLines
set lineLength to (count thisLine)
if (lineLength > seedWidth) then set seedWidth to lineLength
end repeat
if (seedWidth > w) then set w to seedWidth
-- Get a new universe.
script universe
-- State lists. These will contain or be lists of 0s and 1s and will include the border cells.
property newState : {}
property previousState : {}
property currentRow : {}
property rowAbove : {}
property rowBelow : {}
property replacementRow : {}
-- Equivalent text lists. These will only cover what's in the bounded region.
property lineList : {}
property characterGrid : {}
property currentLineCharacters : {}
-- Precalculated border cell indices.
property rightInnerBuffer : borderThickness + w + 1
property rightOuterBuffer : rightInnerBuffer + borderThickness - 2
property bottomInnerBuffer : borderThickness + h + 1
property bottomOuterBuffer : bottomInnerBuffer + borderThickness - 2
-- Generation counter.
property counter : 0
-- Temporary lists used in the set-up.
property rowTemplate : {}
property lineCharacterTemplate : {}
-- Built-in handlers. Both return text representing a universe state and
-- a boolean indicating whether or not the state's the same as the previous one.
on nextState()
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
copy newState to previousState
set currentRow to beginning of my previousState
set rowBelow to item 2 of my previousState
-- Check each occupiable cell in each occupiable row of the 'previousState' grid, including the buffer cells.
-- If warranted by the number of live neighbours, edit the equivalent cell in 'newState' and,
-- if within the region's bounds, change the corresponding text character too.
repeat with r from 2 to bottomOuterBuffer
set rowAbove to currentRow
set currentRow to rowBelow
set rowBelow to item (r + 1) of my previousState
set replacementRow to item r of my newState
set rowCrossesRegion to ((r comes after borderThickness) and (r comes before bottomInnerBuffer))
if (rowCrossesRegion) then set currentLineCharacters to item (r - borderThickness) of my characterGrid
set lineChanged to false
repeat with c from 2 to rightOuterBuffer
set liveNeighbours to ¬
(item (c - 1) of my rowAbove) + (item c of my rowAbove) + (item (c + 1) of my rowAbove) + ¬
(item (c - 1) of my currentRow) + (item (c + 1) of my currentRow) + ¬
(item (c - 1) of my rowBelow) + (item c of my rowBelow) + (item (c + 1) of my rowBelow)
if (item c of my currentRow is 1) then
if ((liveNeighbours < 2) or (liveNeighbours > 3)) then
set item c of my replacementRow to 0
if ((c comes after borderThickness) and (c comes before rightInnerBuffer) and (rowCrossesRegion)) then
set item (c - borderThickness) of my currentLineCharacters to dead
set lineChanged to true
else if ((c is 3) or (c is rightOuterBuffer) or (r is 3) or (r is bottomOuterBuffer)) then
-- This is a fudge to dissolve "bombers" entering the buffer zone.
set item (c - 1) of my replacementRow to -1
set item c of item (r - 1) of my newState to -1
end if
end if
else if (liveNeighbours is 3) then
set item c of my replacementRow to 1
if ((c comes after borderThickness) and (c comes before rightInnerBuffer) and (rowCrossesRegion)) then
set item (c - borderThickness) of my currentLineCharacters to live
set lineChanged to true
end if
end if
end repeat
if (lineChanged) then set item (r - borderThickness) of my lineList to currentLineCharacters as text
end repeat
set AppleScript's text item delimiters to astid
set counter to counter + 1
set last item of my lineList to "Generation " & counter
return currentState()
end nextState
on currentState()
set noChanges to (newState = previousState)
if (noChanges) then ¬
set last item of my lineList to (last item of my lineList) & " (all dead, still lifes, or left the universe)"
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to return
set stateText to lineList as text
set AppleScript's text item delimiters to astid
return {stateText, noChanges}
end currentState
end script
-- Set the universe's start conditions.
-- Build a row template list containing w + 2 * borderThickness zeros
-- and a line character template list containing w 'dead' characters.
repeat (borderThickness * 2) times
set end of universe's rowTemplate to 0
end repeat
repeat w times
set end of universe's rowTemplate to 0
set end of universe's lineCharacterTemplate to dead
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
set blankLine to universe's lineCharacterTemplate as text
-- Use the templates to populate lists representing the universe's conditions.
-- Firstly the top border rows ('newState' list only).
repeat borderThickness times
copy universe's rowTemplate to end of universe's newState
end repeat
-- Then enough rows and text lines to centre the input roughly halfway down the grid.
set headroom to (h - lineCount) div 2
repeat headroom times
copy universe's rowTemplate to end of universe's newState
copy universe's lineCharacterTemplate to end of universe's characterGrid
set end of universe's lineList to blankLine
end repeat
-- Then the rows and lines representing the input itself, centring it roughly halfway across the grid.
set textInset to (w - seedWidth) div 2
set stateInset to textInset + borderThickness
repeat with thisLine in seedLines
copy universe's rowTemplate to universe's currentRow
copy universe's lineCharacterTemplate to universe's currentLineCharacters
repeat with c from 1 to (count thisLine)
set thisCharacter to character c of thisLine
set item (textInset + c) of universe's currentLineCharacters to thisCharacter
set item (stateInset + c) of universe's currentRow to (thisCharacter is live) as integer
end repeat
set end of universe's newState to universe's currentRow
set end of universe's characterGrid to universe's currentLineCharacters
set end of universe's lineList to universe's currentLineCharacters as text
end repeat
set AppleScript's text item delimiters to astid
-- Then the rows and lines beneath and the bottom border.
repeat (h - (headroom + lineCount)) times
copy universe's rowTemplate to end of universe's newState
copy universe's lineCharacterTemplate to end of universe's characterGrid
set end of universe's lineList to blankLine
end repeat
repeat borderThickness times
copy universe's rowTemplate to end of universe's newState
end repeat
-- Add a generation counter display line to the end of the line list.
set end of universe's lineList to "Generation 0"
-- Lose the no-longer-needed template lists.
set universe's rowTemplate to missing value
set universe's lineCharacterTemplate to universe's rowTemplate
return universe
end newUniverse</syntaxhighlight>
 
In conjunction with the above, this fulfills the task as set:
 
<syntaxhighlight lang="applescript">on RCTask(seed, dimensions, maxGenerations)
-- Create a universe and start a list with its initial state.
set universe to newUniverse(seed, dimensions)
set {stateText} to universe's currentState()
set output to {stateText}
-- Add successive states to the list.
repeat maxGenerations times
set {stateText, noChanges} to universe's nextState()
set end of output to stateText
if (noChanges) then exit repeat
end repeat
-- Coerce the states to a single text, each followed by a short line of dashes.
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed & "-----" & linefeed & linefeed
set output to (output as text) & linefeed & "-----"
set AppleScript's text item delimiters to astid
return output
end RCTask
 
-- Return text containing the original and three generations of a "blinker" in a 3 x 3 grid.
return RCTask("***", {3, 3}, 3)</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"
■■■
Generation 0
-----
 
Generation 1
-----
 
■■■
Generation 2
-----
 
Generation 3
-----"</syntaxhighlight>
 
This alternative to the task code runs an animation of a "Gosper glider gun" in TextEdit, the AppleScriptable text editor included with macOS. The animation's achieved by replacing the entire text of a document with successive universe states. It's faster than it sounds, but the universe size specified shouldn't be much greater than 150 x 150 with current machines.
 
<syntaxhighlight lang="applescript">on runGame(seed, dimensions, maxGenerations)
-- Create an RTF file set up for Menlo-Regular 12pt, half spacing, and a reasonable window size.
set fontName to "Menlo-Regular"
set fontSize to 12
set viewScale to fontSize * 12.4 -- Seems to work well.
set {w, h} to dimensions
set RTFHeaders to "{\\rtf1\\ansi\\ansicpg1252\\cocoartf1671\\cocoasubrtf600
{\\fonttbl\\f0\\fnil\\fcharset0 " & fontName & ";}
{\\colortbl;\\red255\\green255\\blue255;}
{\\*\\expandedcolortbl;;}
\\margl1440\\margr1440\\vieww" & (w * viewScale as integer) & "\\viewh" & ((h + 1) * viewScale as integer) & "\\viewkind0
\\pard\\sl120\\slmult1\\pardirnatural\\partightenfactor0
\\f0\\fs" & (fontSize * 2) & " \\cf0 }" -- Contains a space as body text for TextEdit to see as an 'attribute run'.
set RTFFile to ((path to temporary items as text) & "Conway's Game of Life.rtf") as «class furl»
set fRef to (open for access RTFFile with write permission)
try
set eof fRef to 0
write RTFHeaders as «class utf8» to fRef
close access fRef
on error errMsg number errNum
close access fRef
error errMsg number errNum
end try
-- Open the file as a document in TextEdit.
tell application "TextEdit"
activate
tell document "Conway's Game of Life.rtf" to if (it exists) then close saving no
set CGoLDoc to (open RTFFile)
end tell
-- Create a universe and display its initial state in the document window.
set universe to newUniverse(seed, dimensions)
set {stateText} to universe's currentState()
tell application "TextEdit" to set CGoLDoc's first attribute run to stateText
-- Get and display successive states.
repeat maxGenerations times
set {stateText, noChanges} to universe's nextState()
tell application "TextEdit" to set CGoLDoc's first attribute run to stateText
if (noChanges) then exit repeat
end repeat
end runGame
 
set GosperGliderGun to " *
* *
** ** **
* * ** **
** * * **
** * * ** * *
* * *
* *
**"
-- Run for 500 generations in a 100 x 100 universe.
runGame(GosperGliderGun, {100, 100}, 500)</syntaxhighlight>
 
=={{header|ARM Assembly}}==
Line 551 ⟶ 1,759:
{{works with|TI-Nspire}}
 
<langsyntaxhighlight ARMlang="arm Assemblyassembly"> .string "PRG"
 
lcd_ptr .req r4
Line 647 ⟶ 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 691 ⟶ 1,899:
 
GuiClose: ; exit when GUI is closed
ExitApp</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 699 ⟶ 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 725 ⟶ 1,933:
}
}
</syntaxhighlight>
</lang>
 
{{out}} Finally:
Line 756 ⟶ 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 799 ⟶ 2,007:
End
End
Return</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 809 ⟶ 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 817 ⟶ 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 881 ⟶ 2,089:
else
print "Stabilized in "+(s-2)+" iterations"
end if</langsyntaxhighlight>
{{out}}
<pre>
Line 889 ⟶ 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 923 ⟶ 2,131:
SWAP old&(), new&()
WAIT 30
UNTIL FALSE</langsyntaxhighlight>
{{out}}
<BR>
[[File:Lifebbc.gif]]
 
==={{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}}
<syntaxhighlight lang="casiobasic">Filename:JG VIDA
Cls
20→D
D+2→F
1→E
{F,F}→Dim Mat A
{F,F}→Dim Mat B
{F,F}→Dim Mat C
Fill(0,Mat A)
Fill(0,Mat B)
Fill(0,Mat C)
"PONDERACION 1"?→G
"PONDERACION 2"?→H
For 1→I To D
For 1→J To D
RanInt#(1,G)→R
If R≦H:Then
0→Mat A[I+1,J+1]
Else
1→Mat A[I+1,J+1]
IfEnd
Next
Next
Goto 2
Lbl 1
Mat A→Mat C
Mat B→Mat A
Lbl 2
For 1→I To D
For 1→J To D
I+1→K
J+1→L
K→M
L+20→N
If Mat C[K,L]=0:Then
If Mat A[K,L]=1:Then For 0→R To 2
For 0→S To 2
PxlOn 3I+R-2,3J+S-2
Next
Next
IfEnd
IfEnd
If Mat C[K,L]=1:Then
If Mat A[K,L]=0:Then For 0→R To 2
For 0→S To 2
PxlOff 3I+R-2,3J+S-2
Next
Next
IfEnd
IfEnd
Next
Next
For 1→I To D
For 1→J To D
0→C
I+1→K
J+1→L
Mat A[I,J]=1⇨C+1→C
Mat A[I+1,J]=1⇨C+1→C
Mat A[I+2,J]=1⇨C+1→C
Mat A[I+2,J+1]=1⇨C+1→C
Mat A[I+2,J+2]=1⇨C+1→C
Mat A[I+1,J+2]=1⇨C+1→C
Mat A[I,J+2]=1⇨C+1→C
Mat A[I,J+1]=1⇨C+1→C
If Mat A[K,L]=1:Then
C<2⇨0→Mat B[K,L]
C>3⇨0→Mat B[K,L]
IfEnd
If Mat A[K,L]=0:Then
C=3⇨1→Mat B[K,L]
IfEnd
Next
Next
Goto 1
</syntaxhighlight>
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">' FreeBASIC Conway's Game of Life
' May 2015
' 07-10-2016 cleanup/little changes
Line 1,099 ⟶ 2,386:
Print " Press any key to exit "
Sleep
End</langsyntaxhighlight>
 
==={{header|GFA Basic}}===
 
<syntaxhighlight lang="text">
'
' Conway's Game of Life
Line 1,247 ⟶ 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.
 
<syntaxhighlight 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)
40 RANDOMIZE TIMER
50 CUR = 0 : BUF = 1
60 CLS
70 SCREEN 2
80 LOCATE 5,10: PRINT "Press space to perform one iteration"
90 LOCATE 6,10: PRINT "B to load a blinker"
100 LOCATE 7,10: PRINT "R to randomise the world"
110 LOCATE 8,10: PRINT "Q to quit"
120 K$ = INKEY$
130 IF K$=" " THEN GOSUB 250: GOSUB 180
140 IF K$="B" OR K$="b" THEN GOSUB 400: GOSUB 180
150 IF K$="R" OR K$="r" THEN GOSUB 480: GOSUB 180
160 IF K$="Q" OR K$="q" THEN SCREEN 0: END
170 GOTO 120
180 REM draw the world
190 FOR XX=1 TO 30
200 FOR YY=1 TO 30
210 PSET (XX, YY), 15*WORLD(XX, YY, CUR)
220 NEXT YY
230 NEXT XX
240 RETURN
250 REM perform one iteration
260 FOR XX=1 TO 30
270 FOR YY=1 TO 30
280 SM=0
290 SM = SM + WORLD(XX-1, YY-1, CUR) + WORLD(XX, YY-1, CUR) + WORLD(XX+1, YY-1, CUR)
300 SM = SM + WORLD(XX-1, YY, CUR) + WORLD(XX+1, YY, CUR)
310 SM = SM + WORLD(XX-1, YY+1, CUR) + WORLD(XX, YY+1, CUR) + WORLD(XX+1, YY+1, CUR)
320 IF SM<2 OR SM>3 THEN WORLD(XX, YY, BUF) = 0
330 IF SM=3 THEN WORLD(XX, YY, BUF) = 1
340 IF SM=2 THEN WORLD(XX,YY,BUF) = WORLD(XX,YY,CUR)
350 NEXT YY
360 NEXT XX
370 CUR = BUF : REM exchange identities of current and buffer
380 BUF = 1 - BUF
390 RETURN
400 REM produces a vertical blinker at the top left corner, and blanks the rest
410 FOR XX=1 TO 30
420 FOR YY=1 TO 30
430 WORLD(XX,YY,CUR) = 0
440 IF XX=2 AND YY<4 THEN WORLD(XX, YY, CUR) = 1
450 NEXT YY
460 NEXT XX
470 RETURN
480 REM randomizes the world with a density of 1/2
490 FOR XX = 1 TO 30
500 FOR YY = 1 TO 30
510 WORLD(XX, YY, CUR) = INT(RND*2)
520 NEXT YY
530 NEXT XX
540 RETURN</syntaxhighlight>
 
==={{header|Liberty BASIC}}===
It will run slow for grids above say 25!
<syntaxhighlight lang="lb">
<lang lb>
nomainwin
 
Line 1,320 ⟶ 2,665:
close #w
end
</syntaxhighlight>
</lang>
 
==={{header|MSX Basic}}===
<syntaxhighlight lang="basic">
10 DEFINT A-Z
20 DIM L(16,16), N(16,16)
30 M = 16
40 CLS
50 PRINT "PRESS A KEY TO START...";
60 W = RND(1)
70 IF INKEY$ = "" THEN 60
80 CLS
100 FOR I=1 TO M
110 FOR J=1 TO M
120 IF RND(1)>=.7 THEN N(I,J) = 1 ELSE N(I,J) = 0
130 NEXT J
140 NEXT I
1000 FOR I=0 TO M+1
1010 LOCATE I,0 : PRINT "+";
1020 LOCATE I,M+1 : PRINT "+";
1030 LOCATE 0,I : PRINT "+";
1040 LOCATE M+1,I : PRINT "+";
1050 NEXT I
1080 G=0
1090 LOCATE 1,M+3 : PRINT USING "#####";G
1100 FOR I=1 TO M
1110 FOR J=1 TO M
1115 W = N(I,J) : L(I,J) = W
1120 LOCATE I,J
1130 IF W=0 THEN PRINT " "; ELSE PRINT "*";
1160 NEXT J
1170 NEXT I
1180 FOR I=1 TO M
1190 FOR J=1 TO M
1200 NC=0
1210 FOR K=I-1 TO I+1
1215 IF K=0 OR K>M THEN 1260
1220 FOR W=J-1 TO J+1
1230 IF W=0 OR W>M OR (K=I AND W=J) THEN 1250
1240 NC = NC + L(K,W)
1250 NEXT W
1260 NEXT K
1270 IF NC=2 THEN N(I,J)=L(I,J) : GOTO 1300
1280 IF NC=3 THEN N(I,J)=1 ELSE N(I,J)=0
1300 NEXT J
1310 NEXT I
1350 G=G+1
1360 GOTO 1090
</syntaxhighlight>
 
==={{header|PureBasic}}===
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
Define.i x, y ,Xmax ,Ymax ,N
Xmax = 13 : Ymax = 20
Line 1,379 ⟶ 2,771:
Until Inkey() <> ""
PrintN("Press any key to exit"): Repeat: Until Inkey() <> ""</langsyntaxhighlight>
'''Sample output:'''<br>
[[File:Game-of-life-PureBasic.gif‎]]
 
 
==={{header|QBasic}}===
El código es de Ben Wagner (bwgames.org)<br>
The code is from Ben Wagner (bwgames.org)<br>
Yo solo lo transcrito y comento al español.<br>
I just transcribed it and comment it in Spanish.
<syntaxhighlight lang="qbasic">SCREEN 9, 0, 0, 1
 
RANDOMIZE TIMER
 
WINDOW (0, 0)-(80, 80)
 
'La matrizA es la actual, la matrizB es la siguiente iteración
'ArrayA is current, arrayB is next iteration
DIM matrizA(-1 TO 81, -1 TO 81)
DIM matrizB(-1 TO 81, -1 TO 81)
 
'Aleatorizar las celdas de matrizA,
'Randomize cells in arrayA,
'y establecer las de matrizB a 0
'and set those of matrixB to 0
y = 0
DO
x = 0
DO
x = x + 1
matrizA(x, y) = INT(RND + .5)
matrizB(x, y) = 0
LOOP UNTIL x > 80
y = y + 1
LOOP UNTIL y > 80
 
''--- Bucle Principal ---
'' --- Main Loop ---
DO
CLS
'Dibuja la matriz
'Draw the matrix
y = 0
DO
x = 0
DO
IF matrizA(x, y) = 1 THEN LINE (x, y)-(x + 1, y + 1), 1, BF
x = x + 1
LOOP UNTIL x > 80
y = y + 1
LOOP UNTIL y > 80
'Cuenta el recuento de la celda circundante
'Counts the count of the surrounding cell
'Luego aplica la operación a la celda
'Then apply the operation to the cell
y = 0
DO
x = 0
DO
'Cuenta las células circundantes
'Count the surrounding cells
cuenta = 0
IF matrizA(x - 1, y + 1) = 1 THEN cuenta = cuenta + 1
IF matrizA(x, y + 1) = 1 THEN cuenta = cuenta + 1
IF matrizA(x + 1, y + 1) = 1 THEN cuenta = cuenta + 1
IF matrizA(x - 1, y) = 1 THEN cuenta = cuenta + 1
IF matrizA(x + 1, y) = 1 THEN cuenta = cuenta + 1
IF matrizA(x - 1, y - 1) = 1 THEN cuenta = cuenta + 1
IF matrizA(x, y - 1) = 1 THEN cuenta = cuenta + 1
IF matrizA(x + 1, y - 1) = 1 THEN cuenta = cuenta + 1
'Aplica las operaciones
'Apply the operations
'Muerte
'Death
IF matrizA(x, y) = 1 THEN
IF cuenta = 2 OR cuenta = 3 THEN matrizB(x, y) = 1 ELSE matrizB(x, y) = 0
END IF
'Nacimiento
'Birth
IF matrizA(x, y) = 0 THEN
IF cuenta = 3 THEN matrizB(x, y) = 1 ELSE matrizB(x, y) = 0
END IF
x = x + 1
LOOP UNTIL x > 80
y = y + 1
LOOP UNTIL y > 80
'Actualiza la matriz con la nueva matriz que hemos calculado.
'Update the matrix with the new matrix that we have calculated.
y = 0
DO
x = 0
DO
x = x + 1
matrizA(x, y) = matrizB(x, y)
LOOP UNTIL x > 80
y = y + 1
LOOP UNTIL y > 80
PCOPY 0, 1
LOOP WHILE INKEY$ = ""</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Line 1,387 ⟶ 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 1,423 ⟶ 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 1,438 ⟶ 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 1,464 ⟶ 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 1,472 ⟶ 2,969:
:End
:End
</syntaxhighlight>
</lang>
 
==={{header|TI-89 BASIC}}===
Line 1,479 ⟶ 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 1,554 ⟶ 3,051:
setGraph("Grid", save[2])
setGraph("Labels", save[3])
EndPrgm</langsyntaxhighlight>
 
=={{header|Batch File}}==
Line 1,566 ⟶ 3,063:
If no parameters are parsed, it defaults to 5 iterations of the blinking example.
 
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 1,675 ⟶ 3,172:
 
exit /b
</syntaxhighlight>
</lang>
{{out}}
Blinking example:
Line 1,771 ⟶ 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 1,778 ⟶ 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 1,815 ⟶ 3,312:
=={{header|Brat}}==
 
<langsyntaxhighlight lang="brat">width = 3
height = 3
rounds = 3
Line 1,875 ⟶ 3,372:
p
step
}</langsyntaxhighlight>
 
{{out}}
Line 1,891 ⟶ 3,388:
-O-
</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">Life←{
r←¯1(⌽⎉1)¯1⌽(2+≢𝕩)↑𝕩
s←∨´ (1∾<r) ∧ 3‿4 = <+´⥊ ¯1‿0‿1 (⌽⎉1)⌜ ¯1‿0‿1 ⌽⌜ <r
1(↓⎉1) ¯1(↓⎉1) 1↓ ¯1↓s
}
 
blinker←>⟨0‿0‿0,1‿1‿1,0‿0‿0⟩
(<".#") ⊏¨˜ Life⍟(↕3) blinker</syntaxhighlight>
{{out}}
<pre>┌─
· ┌─ ┌─ ┌─
╵"... ╵".#. ╵"...
### .#. ###
..." .#." ..."
┘ ┘ ┘
┘</pre>
 
=={{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 1,949 ⟶ 3,464:
if (h <= 0) h = 30;
game(w, h);
}</langsyntaxhighlight>
Also see [[Conway's Game of Life/C]]
 
=={{header|=C for Arduino}}===
Play game of life on your arduino (using FastLED) - based on the C example.
<syntaxhighlight lang="c">
#include <FastLED.h>
 
#define LED_PIN 3
#define LED_TYPE WS2812B
#define WIDTH 20
#define HEIGHT 15
#define NUM_LEDS (WIDTH*HEIGHT)
#define BRIGHTNESS 100
#define COLOR_ORDER GRB
#define SERPENTINE 1
#define FRAMERATE 1
#define SCALE 1
 
CRGB leds[NUM_LEDS];
 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
 
#define for_x for (int x = 0; x < w; x++)
#define for_y for (int y = 0; y < h; y++)
#define for_xy for_x for_y
 
const int w = WIDTH, h = HEIGHT;
unsigned univ[h][w];
 
int getLEDpos(int x, int y){ // for a serpentine raster
return (y%2 || !SERPENTINE) ? y*WIDTH + x : y*WIDTH + (WIDTH - 1 - x);
}
 
void show(void *u, int w, int h)
{
int (*univ)[w] = u;
for_xy {
leds[getLEDpos(x, y)] = univ[y][x] ? CRGB::White: CRGB::Black;
}
FastLED.show();
}
 
void evolve(void *u, int w, int h)
{
unsigned (*univ)[w] = u;
unsigned newU[h][w];
 
for_y for_x {
int n = 0;
for (int y1 = y - 1; y1 <= y + 1; y1++)
for (int x1 = x - 1; x1 <= x + 1; x1++)
if (univ[(y1 + h) % h][(x1 + w) % w])
n++;
 
if (univ[y][x]) n--;
newU[y][x] = (n == 3 || (n == 2 && univ[y][x]));
}
for_y for_x univ[y][x] = newU[y][x];
}
 
void setup(){
//Initialize leds after safety period
FastLED.delay(500);
FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
FastLED.setBrightness( BRIGHTNESS );
//Seed random with analog noise
randomSeed(analogRead(0));
 
for_xy univ[y][x] = random() %10 <= 1 ? 1 : 0;
}
 
void loop(){
show(univ, w, h);
evolve(univ, w, h);
FastLED.delay(1000/FRAMERATE);
}
</syntaxhighlight>
 
===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 for Arduino>
 
#include <MaxMatrix.h>
Line 2,042 ⟶ 3,636:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Text;
Line 2,222 ⟶ 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 2,438 ⟶ 4,294:
gol2.iterate(4);
}
</syntaxhighlight>
</lang>
{{out}} first a glider, then a blinker, over a few iterations
(reformatted for convenience).
Line 2,458 ⟶ 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 2,645 ⟶ 4,501:
return system( "pause" );
}
</syntaxhighlight>
</lang>
{{out}}<pre>
+--------------------+ +--------------------+ +--------------------+ +--------------------+
Line 2,663 ⟶ 4,519:
Shows a glider over 20 generations
Board edges wrap around to simulate infinite board
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 2,748 ⟶ 4,604:
}
}
</syntaxhighlight>
</lang>
{{out}}<pre>
generation 0:
Line 2,801 ⟶ 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 2,894 ⟶ 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 2,921 ⟶ 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 2,944 ⟶ 4,827:
05 check-row pic s9.
05 check-cell pic s9.
 
procedure division.
control-paragraph.
Line 2,992 ⟶ 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 3,016 ⟶ 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 3,057 ⟶ 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 3,082 ⟶ 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 3,123 ⟶ 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 3,189 ⟶ 5,075:
uni.writeln;
}
}</langsyntaxhighlight>
{{out|Output, first iteration}}
<pre>-------------------------------------------------------------
Line 3,215 ⟶ 5,101:
===Faster Version===
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.typetuple,
std.array, std.conv;
 
Line 3,285 ⟶ 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 3,444 ⟶ 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 3,544 ⟶ 5,430:
});
});
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,567 ⟶ 5,453:
 
</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| Velthuis.Console}}
{{Trans|Go}}
Thanks Rudy Velthuis for the [https://github.com/rvelthuis/Consoles Velthuis.Console] library.
<syntaxhighlight lang="delphi">
program game_of_life;
 
{$APPTYPE CONSOLE}
 
 
 
uses
System.SysUtils,
Velthuis.Console; // CrlScr
 
type
TBoolMatrix = TArray<TArray<Boolean>>;
 
TField = record
s: TBoolMatrix;
w, h: Integer;
procedure SetValue(x, y: Integer; b: boolean);
function Next(x, y: Integer): boolean;
function State(x, y: Integer): boolean;
class function NewField(w1, h1: Integer): TField; static;
end;
 
TLife = record
a, b: TField;
w, h: Integer;
class function NewLife(w1, h1: Integer): TLife; static;
procedure Step;
function ToString: string;
end;
 
{ TField }
 
class function TField.NewField(w1, h1: Integer): TField;
var
s1: TBoolMatrix;
begin
SetLength(s1, h1);
for var i := 0 to High(s1) do
SetLength(s1[i], w1);
with Result do
begin
s := s1;
w := w1;
h := h1;
end;
end;
 
function TField.Next(x, y: Integer): boolean;
var
_on: Integer;
begin
_on := 0;
for var i := -1 to 1 do
for var j := -1 to 1 do
if self.State(x + i, y + j) and not ((j = 0) and (i = 0)) then
inc(_on);
Result := (_on = 3) or (_on = 2) and self.State(x, y);
end;
 
procedure TField.SetValue(x, y: Integer; b: boolean);
begin
self.s[y, x] := b;
end;
 
function TField.State(x, y: Integer): boolean;
begin
while y < 0 do
inc(y, self.h);
while x < 0 do
inc(x, self.w);
result := self.s[y mod self.h, x mod self.w]
end;
 
{ TLife }
 
class function TLife.NewLife(w1, h1: Integer): TLife;
var
a1: TField;
begin
a1 := TField.NewField(w1, h1);
for var i := 0 to (w1 * h1 div 2) do
a1.SetValue(Random(w1), Random(h1), True);
with Result do
begin
a := a1;
b := TField.NewField(w1, h1);
w := w1;
h := h1;
end;
end;
 
procedure TLife.Step;
var
tmp: TField;
begin
for var y := 0 to self.h - 1 do
for var x := 0 to self.w - 1 do
self.b.SetValue(x, y, self.a.Next(x, y));
tmp := self.a;
self.a := self.b;
self.b := tmp;
end;
 
function TLife.ToString: string;
begin
result := '';
for var y := 0 to self.h - 1 do
begin
for var x := 0 to self.w - 1 do
begin
var b: char := ' ';
if self.a.State(x, y) then
b := '*';
result := result + b;
end;
result := result + #10;
end;
end;
 
begin
Randomize;
 
var life := TLife.NewLife(80, 15);
 
for var i := 1 to 300 do
begin
life.Step;
ClrScr;
writeln(life.ToString);
sleep(30);
end;
readln;
end.</syntaxhighlight>
{{out}}
<pre> * *** * * *
* ** ** *
**** * * * *
*** * * ** * *
*** ** * * *
* * *
** ** **** ** *
****** ** * *
* * * *** ** ***
** * *
* * **
* * *
* * * *
* *** * * * **
* *** * * * ***</pre>
 
=={{header|E}}==
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 3,631 ⟶ 5,672:
currentFrame := frame
println(currentFrame)
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
[https://easylang.onlinedev/apps/game-of-life.html Run it]
 
<syntaxhighlight lang="text">
<lang>intvars
n = 70
time = 0.1
#
nx = n + 1
subr init
for r range= 1 to 50n
for c range= 1 to 50n
i = r * 52nx + c + 53
if randomf < 0.3
f[i] = 1
else .
f[i] = 0
.
.
.
timer 0
.
f = 100 / n
subr show
clear
for r range= 1 to 50n
for c range= 1 to 50n
if f[r * 52nx + c + 53] = 1
move c * 2f - f r * 2f - f
rect 1f * 0.89 f * 10.89
.
.
.
.
.
subr update
swap f[] p[]
for r range= 1 to 50n
for c rangesm 50= 0
i = r * 52nx + c + 531
ssr = p[i - 53nx] + p[i - 52] + p[i -+ 51nx]
sfor c += p[i - 1] +to p[i + 1]n
s += p[i +sl 51] + p[i + 52] + p[i += 53]sm
if s <= 1 or ssm >= 4sr
f[i] in = 0i + 1
elif s sr = 3p[in - nx] + p[in] + p[in + nx]
f[i] s = 1sl + sm + sr
if s = 3 or s = 4 and p[i] = 1
else
f[i] = p[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 + 21
r = mouse_y /div f + 21
i = r * 52nx + c + 53
f[i] = 1 - f[i]
call show
timer 3
.
len f[] 52nx * 52nx + nx
len p[] 52nx * 52nx + nx
call init</lang>
timer 0
</syntaxhighlight>
 
=={{header|eC}}==
{{libheader|Ecere}}
 
<syntaxhighlight lang="ec">
<lang eC>
import "ecere"
 
Line 3,796 ⟶ 5,844:
 
GameOfLife life {};
</syntaxhighlight>
</lang>
 
=={{header|Egel}}==
 
<langsyntaxhighlight Egellang="egel">import "prelude.eg"
import "io.ego"
 
Line 3,854 ⟶ 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 3,869 ⟶ 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 3,969 ⟶ 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 4,046 ⟶ 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 4,137 ⟶ 6,179:
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight lang="lisp">#!/usr/bin/env emacs -script
;; -*- lexical-binding: t -*-
;; run: ./conways-life conways-life.config
Line 4,230 ⟶ 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 4,242 ⟶ 6,284:
;; This is a custom pattern.
(4 4 (".***"
"***."))))</langsyntaxhighlight>
 
{{out}}
Line 4,276 ⟶ 6,318:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
 
-module(life).
Line 4,485 ⟶ 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 4,563 ⟶ 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 4,601 ⟶ 6,643:
Media.CompositionTarget.Rendering.Add update
Window(Content=image, Title="Game of Life")
|> (Application()).Run |> ignore</langsyntaxhighlight>
 
=={{header|Fermat}}==
<syntaxhighlight lang="fermat">;{Conway's Game of Life in Fermat}
;{square grid with wrap-around boundaries}
 
size:=50; {how big a grid do you want? This fits my screen OK, change this for your own screen}
 
Array w1[size,size], w2[size,size]; {set up an active world and a 'scratchpad' world}
act:=1;
buf:=2;
%[1]:=[w1]; {Fermat doesn't have 3D arrays in the normal sense--}
%[2]:=[w2]; {we need to use the somewhat odd "array of arrays" functionality}
 
Func Cls = for i = 1 to size do !!; od.; {"clear screen" by printing a bunch of newlines}
 
Func Draw = {draw the active screen}
for i = 1 to size do
for j = 1 to size do
if %[act][i, j] = 1 then !('# ') else !('. ') fi;
od;
!;
od;
.;
 
Func Rnd = {randomize the grid with a density of 40% live cells}
for i = 1 to size do
for j = 1 to size do
if Rand|5<2 then %[act][i, j] := 1 else %[act][i, j] := 0 fi;
od;
od;
Cls;
Draw;
.;
 
Func Blinker = {clears the screen except for a blinker in the top left corner}
for i = 1 to size do
for j = 1 to size do
%[act][i, j] := 0;
od;
od;
%[act][1,2] := 1;
%[act][2,2] := 1;
%[act][3,2] := 1;
Cls;
Draw;
.;
 
Func Iter = {do one iteration}
for i = 1 to size do
if i = 1 then im := size else im := i - 1 fi; {handle wrap around}
if i = size then ip := 1 else ip := i + 1 fi;
for j = 1 to size do
if j = 1 then jm := size else jm := j - 1 fi;
if j = size then jp := 1 else jp := j + 1 fi;
neigh := %[act][im, jm]; {count neigbours}
neigh :+ (%[act][im, j ]);
neigh :+ (%[act][im, jp]);
neigh :+ (%[act][i , jm]);
neigh :+ (%[act][i , jp]);
neigh :+ (%[act][ip, jm]);
neigh :+ (%[act][ip, j ]);
neigh :+ (%[act][ip, jp]);
if neigh < 2 or neigh > 3 then %[buf][i, j] := 0 fi; {alive and dead rules}
if neigh = 2 then %[buf][i, j] := %[act][i, j] fi;
if neigh = 3 then %[buf][i, j] := 1 fi;
od;
od;
Swap(act, buf); {rather than copying the scratch over into the active, just exchange their identities}
Cls;
Draw;
.;
 
choice := 9;
while choice <> 0 do {really rough menu, not the point of this exercise}
?choice;
if choice=4 then Cls fi;
if choice=3 then Blinker fi;
if choice=2 then Rnd fi;
if choice=1 then Iter fi;
od;
 
!!'John Horton Conway (26 December 1937 – 11 April 2020)';
</syntaxhighlight>
{{out}} One iteration starting from random soup, showing a few well-known objects (blinker, block, glider, beehive, loaf)
<pre>
# . . . . . . . . . # . . # . . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . # # . . .
. . . . . . . # . . # . . . # . . . . # # . # # . . # # # . . . . . . . . . . . . . . . # # . # . #
. . . . . . # . # # . . . # . . . . . # # . # . . . # . . # . . . . . . . . . . . . . . # # . . # .
. . . . . . # . # . # . . # . . . . . # . # # . . # . . . # . . . . # # . . . . . . . . . . . . . .
. . . . . . . # . # # . . # . . . # # # # . . . . # . . # . . . . # . . # . . . . . . . . . . . . .
. . . . . . . . . . . . # . . . . # . . . . . . . . . . . . . . . . # . . # . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . # # # . . . . . . # # . . . . . . # . . # . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . # . . . . . . . . . . . . . . . # . # . . . . . . . . . . . . .
. . . . # # # . . . . . . . . . . . # . . . . # # . . . . . . . . . . # . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . # # # # . . # . # . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . # # . . # . . # . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . # # # . . . . . . . # # . . . . . # . . . . . . . . . . # . . . . . . . . . . . . . . .
. . . . . . # # # . . . . . . . . . . . # # . . . . . . . . . . . # . # . . . . . . . . . . . . . .
. . . . . # . . # . # # . . . . . . # # . # . . . . . . . . . . . # . . # . . . . . . . . . . . . .
. . . . . . # # . # # . . . . . . . . # # . . . . . . . . . . . . . # # . . . . . . . . . . . . . .
. . . . . . # # # # # . . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . # . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . . . . . . . .
. . . . . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . . . . . . .
. . . . . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # # . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . # # . . . . . . # # #
# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . . . . . . # . . .
# . . . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . #
. . . . . . # . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . # . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . . . . . . .
# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # #
# # . . . . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . # #
. # # . . . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . . #
. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . # . # # . . . . . . . # # . . .
# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . # . # . . . . . . . . . # # . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . # . # # . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . # # # # . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # # . . # # . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . # # # . . . . . . . . . . # . . . . . . . .
. . . . . . . . . . . . # . . . . . . . . . . . . . . # . # . # # . # . . . . . . # . . . . . . . .
. . . . . . . . . . . . # . . . . . . . . . . . . . # . . . . . . . . # . . . . . . . . . . . . . .
. . . . . . . . . . . . # . . . . . . . . . . . . # . . # # # # . . . # . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . # # # . . . . . . # . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # .
. . . . . . . . . . . . . . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . # . # .
. . . . . . . . . . . . # # . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . # .
. . . . . . . . . . . . # . # . . # . . . . . . . . . . . . . . # . . . . . . . . . . . . # . . . .
. . . . . . . . . . . . # . . . . . . # . . . . . . . . . . . # . . # . . . . . . . . . # # . # . .
. . . . . . . . . . . . . . . . . . # . . . . . . . . . . . . . # # . . . . . . . . . . . . . . # #
. . . . . . . . . . . # . # . . . . # . . # . . . . . . . . . . . . . . . . . . . . . . . # # # . #
</pre>
 
=={{header|Forth}}==
'''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 4,684 ⟶ 6,862:
**
*
Generation 1 ok</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran"> PROGRAM LIFE_2D
IMPLICIT NONE
Line 4,787 ⟶ 6,965:
END SUBROUTINE NextgenV2
!###########################################################################
END PROGRAM LIFE_2D</langsyntaxhighlight>
{{out}}
<pre style="height:45ex;overflow:scroll">
Line 4,914 ⟶ 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 5,020 ⟶ 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 5,111 ⟶ 7,289:
 
repeat 5
iteration()</langsyntaxhighlight>
 
{{out}}
Line 5,159 ⟶ 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 5,262 ⟶ 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 5,311 ⟶ 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 5,411 ⟶ 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 5,433 ⟶ 7,776:
=={{header|Groovy}}==
 
<syntaxhighlight lang="groovy">
<lang Groovy>
class GameOfLife {
 
Line 5,538 ⟶ 7,881:
game.board = game.createGliderBoard()
game.start()
</syntaxhighlight>
</lang>
 
The output of this program:
Line 5,716 ⟶ 8,059:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Array.Unboxed
 
type Grid = UArray (Int,Int) Bool
Line 5,737 ⟶ 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 5,780 ⟶ 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 5,826 ⟶ 8,169:
putStrLn "Blinker >> 3"
putStrLn "------------"
runLife 3 blinker</langsyntaxhighlight>
 
=={{header|HolyC}}==
Line 5,834 ⟶ 8,177:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">global limit
 
procedure main(args)
Line 5,912 ⟶ 8,255:
initial count := 0
return ((count +:= 1) > \limit) | (trim(!g) == " ")
end</langsyntaxhighlight>
 
A sample run:
Line 5,942 ⟶ 8,285:
->
</pre>
 
=={{header|INTERCAL}}==
{{works with|https://web.archive.org/web/20010213211806/http://www.webcom.com/nazgul/pit/life.i the Pit|1}}
 
=={{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 5,959 ⟶ 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 5,970 ⟶ 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 6,000 ⟶ 8,348:
=={{header|JAMES II/Rule-based Cellular Automata}}==
{{libheader|JAMES II}}
<langsyntaxhighlight lang="j2carules">@caversion 1;
 
dimensions 2;
Line 6,024 ⟶ 8,372:
ALIVE
*/
rule{DEAD}:ALIVE{3}->ALIVE;</langsyntaxhighlight>
Animated output for the blinker example:
 
Line 6,030 ⟶ 8,378:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class GameOfLife{
public static void main(String[] args){
String[] dish= {
Line 6,120 ⟶ 8,468:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Generation 0:
Line 6,138 ⟶ 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 6,293 ⟶ 8,641:
}
}
</syntaxhighlight>
</lang>
 
Glider Gun design. Save it in GOLglidergun.txt and uncomment the setCustomConfig function.
Line 6,323 ⟶ 8,671:
 
===Java 10===
<langsyntaxhighlight lang="java">
import static java.util.List.of;
 
Line 6,416 ⟶ 8,764:
 
}
</syntaxhighlight>
</lang>
Outputs:
<pre>
Line 6,437 ⟶ 8,785:
{{works with|SpiderMonkey}}
{{works with|V8}}
<langsyntaxhighlight lang="javascript">function GameOfLife () {
 
this.init = function (turns,width,height) {
Line 6,535 ⟶ 8,883:
print("---\nRandom 5x10");
game.init(5,5,10);
game.start();</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">---
Line 6,660 ⟶ 9,008:
{{libheader|HTML5}}
Essentially the same as the above straight [[JavaScript]] but displayed in an [[HTML5]] Canvas.
<langsyntaxhighlight lang="javascript">
<html>
<head>
Line 6,811 ⟶ 9,159:
</canvas><br>
</body>
</html></langsyntaxhighlight>
{{out}} for 3x3 Blinker:
 
Line 6,818 ⟶ 9,166:
 
'''More functional style''':
<langsyntaxhighlight lang="javascript">
const _ = require('lodash');
 
Line 6,860 ⟶ 9,208:
displayWorld(world);
}, 1000);
</syntaxhighlight>
</lang>
 
'''ES6 + ''':
<langsyntaxhighlight lang="javascript">
const alive = 1;
const dead = 0;
Line 6,935 ⟶ 9,283:
run()
 
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 6,941 ⟶ 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 6,985 ⟶ 9,333:
end )
| [., $lines, $w] ;
</syntaxhighlight>
</lang>
'''Animation''':
<langsyntaxhighlight lang="jq"># "clear screen":
def cls: "\u001b[2J";
 
Line 7,013 ⟶ 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 7,029 ⟶ 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 7,065 ⟶ 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 7,212 ⟶ 9,560:
 
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 7,223 ⟶ 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 7,233 ⟶ 9,581:
 
julia> gameOfLife(15, 30, 5)
30x15x5 Cellular Automaton</langsyntaxhighlight>
 
# ## # ###### ### ### ##
Line 7,321 ⟶ 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 7,364 ⟶ 9,712:
lifegame("lwss.gif", lwss)
lifegame("glidergun.gif", glidergun, 90, 200)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 7,375 ⟶ 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 7,485 ⟶ 9,833:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 7,582 ⟶ 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 7,621 ⟶ 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 7,643 ⟶ 10,100:
end
for i = 6,20 do life:evolve() end
life:render()</langsyntaxhighlight>
{{out}}
<pre>GLIDER:
Line 7,732 ⟶ 10,189:
□ □ □ □ □ □ □ □ □ □
□ □ □ □ □ □ □ □ □ □</pre>
=={{header|ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
# # Version AJM 93u+ 2012-08-01
 
# Conway's Game of Life
 
# # Variables:
#
integer RAND_MAX=32767
LIFE="�[07m �[m"
NULL=" "
typeset -a char=( "$NULL" "$LIFE" )
 
# # Input x y or default to 30x30, positive integers only
#
integer h=${1:-30} ; h=$(( h<=0 ? 30 : h )) # Height (y)
integer w=${2:-30} ; w=$(( w<=0 ? 30 : w )) # Width (x)
 
# # Functions:
#
 
# # Function _display(map, h, w)
#
function _display {
typeset _dmap ; nameref _dmap="$1"
typeset _h _w ; integer _h=$2 _w=$3
 
typeset _x _y ; integer _x _y
 
printf %s "�[H"
for (( _y=0; _y<_h; _y++ )); do
for (( _x=0; _x<_w; _x++ )); do
printf %s "${char[_dmap[_y][_x]]}"
done
printf "%s\n"
done
}
 
# # Function _evolve(h, w)
#
_evolve() {
typeset _h _w ; integer _h=$1 _w=$2
 
typeset _x _y _n _y1 _x1 ; integer _x _y _n _y1 _x1
typeset _new _newdef ; typeset -a _new
 
for (( _y=0; _y<_h; _y++ )); do
for (( _x=0; _x<_w; _x++ )); do
_n=0
for (( _y1=_y-1; _y1<=_y+1; _y1++ )); do
for (( _x1=_x-1; _x1<=_x+1; _x1++ )); do
(( _map[$(( (_y1 + _h) % _h ))][$(( (_x1 + _w) % _w ))] )) && (( _n++ ))
done
done
(( _map[_y][_x] )) && (( _n-- ))
_new[_y][_x]=$(( (_n==3) || (_n==2 && _map[_y][_x]) ))
done
done
for (( _y=0; _y<_h; _y++ )); do
for (( _x=0; _x<_w; _x++ )); do
_map[_y][_x]=${_new[_y][_x]}
done
done
}
 
# # Function _game(h, w)
#
function _game {
typeset _h ; integer _h=$1
typeset _w ; integer _w=$2
 
typeset _x _y ; integer _x _y
typeset -a _map
 
for (( _y=0 ; _y<_h ; _y++ )); do
for (( _x=0 ; _x<_h ; _x++ )); do
_map[_x][_y]=$(( RANDOM < RAND_MAX / 10 ? 1 : 0 )) # seed map
done
done
 
while : ; do
_display _map ${_h} ${_w}
_evolve ${_h} ${_w}
sleep 0.2
done
}
 
######
# main #
######
 
_game ${h} ${w}
 
</syntaxhighlight>
 
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Life {
Font "courier new"
Line 7,743 ⟶ 10,298:
Cls 5, 2
Const Mx=20, My=10
Dim A(-10 to Mx+1, -10 to My+1)=0
Flush
RemREM Data (2,2),(2,3),(3,3),(4,3),(5,4),(,3,4),(5, 3), (6,2),(8,5),(5,8)
Data (5,3)
Data (5,4)
Line 7,754 ⟶ 10,309:
A(A,B)=1
End While
cls, 3
Display()
Do
k$=Key$
If k$=chr$(13) thenThen exit
A()=@GetNext(A())
refresh 500
cls, 3
Display()
Until A()#Sum()=0
K$=Key$
Cls, 0
Function GetNext(A())
End
Local B(-1 to Mx+1, -1 to My+1)=0
Function GetNext()
Local B()
B()=A() ' copy array
Local B=B() ' get a pointer
B*=0 ' make all element zero
Local i, j, tot
For j=1 to My
For i=1 to Mx
tot=-A(i,j)
forFor k=j-1 to j+1
forFor m=i-1 to i+1
tot+=A(m, k)
nextNext
nextNext
ifIf A(i,j)=1 thenThen
ifIf tot=2 or tot=3 thenThen B(i,j)=1
Else.if tot=3 thenThen
B(i,j)=1
endEnd ifIf
Next
Next
Line 7,786 ⟶ 10,344:
End Function
Sub Display()
Cursor 0,2
move ! ' move graphic to character cursor
Fill scale.x, scale.y-pos.Y, 1, 5
Print "Generation:";Generation
Generation++
Line 7,792 ⟶ 10,353:
Print @(width div 2-Mx div 2);
For i=1 to Mx
Print ifIf$(A(I,J)=1->"■", "□");
Next
Print
Next
Print
Report "Press enter to exit or any other key for next generation"
Report 2, "Press enter to exit or any other key for Next generation"
End Sub
}
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 7,857 ⟶ 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 7,910 ⟶ 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 7,985 ⟶ 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 8,000 ⟶ 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 8,055 ⟶ 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].
<syntaxhighlight lang="miniscript">// Conway's Game of Life
clear
rows = 64; rowRange = range(0, rows-1)
cols = 96; colRange = range(0, cols-1)
// prepare two tile displays, in display layers 4 and 5
img = Image.create(2, 1); img.setPixel 1, 0, color.white
grids = []
for dispIdx in [4,5]
display(dispIdx).mode = displayMode.tile
td = display(dispIdx)
td.cellSize = 9 // size of cells on screen
td.extent = [cols, rows]
td.overlap = -1 // adds a small gap between cells
td.tileSet = img; td.tileSetTileSize = 1
td.clear 0
grids.push td
end for
 
// initialize to a random state
for x in colRange
for y in rowRange
td.setCell x, y, rnd > 0.5
end for
end for
 
curIdx = 5
// main loop
while true
yield
td = grids[curIdx-4]
newIdx = 4 + (curIdx == 4)
newTd = grids[newIdx-4]
for x in colRange
for y in rowRange
// get sum of neighboring states
sum = 0
for i in [x-1, x, x+1]
if i < 0 or i >= cols then continue
for j in [y-1, y, y+1]
if j < 0 or j >= rows then continue
if i==x and j==y then continue
sum = sum + td.cell(i,j)
end for
end for
// Now, update the cell based on current state
// and neighboring sum.
if td.cell(x,y) then
newTd.setCell x, y, (sum == 2 or sum == 3)
else
newTd.setCell x, y, sum == 3
end if
end for
end for
display(newIdx).mode = displayMode.tile
display(curIdx).mode = displayMode.off
curIdx = newIdx
end while</syntaxhighlight>
 
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">import os, strutils, random
 
randomize()
Line 8,074 ⟶ 10,703:
univ[y].newSeq w
utmp[y].newSeq w
for x in 0 .. < w:
if randomrand(109) < 1:
univ[y][x] = true
 
Line 8,100 ⟶ 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 8,148 ⟶ 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 8,212 ⟶ 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 8,292 ⟶ 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 8,373 ⟶ 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 8,450 ⟶ 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 8,896 ⟶ 11,523:
Else
Return
</syntaxhighlight>
</lang>
{{out}}
<pre>blinker.txt
Line 8,912 ⟶ 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 9,015 ⟶ 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 9,028 ⟶ 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 9,035 ⟶ 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 9,214 ⟶ 11,841:
PrintGen;
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
Line 9,224 ⟶ 11,851:
would do 15 iterations over 5 rows and 10 columns.
<langsyntaxhighlight lang="perl">my ($width, $height, $generations) = @ARGV;
 
my $printed;
Line 9,282 ⟶ 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 9,315 ⟶ 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 9,333 ⟶ 11,960:
s/$neighborhood/ substr " $&# ", "$1$2$3$4" =~ tr|#||, 1 /ge;
print;
}</langsyntaxhighlight>
{{out}}
Line 9,358 ⟶ 11,985:
{{trans|basic256}}
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
<lang Phix>-- demo\rosetta\Conways_Game_of_Life.exw
You can run this online [http://phix.x10.mx/p2js/conways_game_of_life.htm here].
include pGUI.e
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Conways_Game_of_Life.exw
-- =====================================
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Conway's Game of Life"</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span>
<span style="color: #004080;">Ihandln</span> <span style="color: #000000;">hTimer</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">NULL</span>
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span> <span style="color: #000080;font-style:italic;">-- cells</span>
<span style="color: #000000;">cn</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- new cells</span>
<span style="color: #000000;">cl</span> <span style="color: #000080;font-style:italic;">-- last cells</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">draw</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">what</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">switch</span> <span style="color: #000000;">what</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">case</span> <span style="color: #008000;">' '</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Clear</span>
<span style="color: #008080;">case</span> <span style="color: #008000;">'+'</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">][</span><span style="color: #000000;">y</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Blinker</span>
<span style="color: #008080;">case</span> <span style="color: #008000;">'G'</span><span style="color: #0000FF;">:</span> <span style="color: #0000FF;">{</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">4</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">4</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">4</span><span style="color: #0000FF;">]}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Glider</span>
<span style="color: #008080;">case</span> <span style="color: #008000;">'T'</span><span style="color: #0000FF;">:</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span> <span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">],</span><span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">4</span><span style="color: #0000FF;">],</span><span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span> <span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">5</span><span style="color: #0000FF;">]}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Thunderbird</span>
<span style="color: #008080;">case</span> <span style="color: #008000;">'X'</span><span style="color: #0000FF;">:</span> <span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Cross</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">switch</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">fps</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">redraw_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">width</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">),</span>
<span style="color: #000080;font-style:italic;">-- limit to 10K cells (performance target of 10fps)
-- n here is the cell size in pixels (min of 1x1)</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">ceil</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">width</span><span style="color: #0000FF;">*</span><span style="color: #000000;">height</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10000</span><span style="color: #0000FF;">)),</span>
<span style="color: #000000;">w</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">width</span><span style="color: #0000FF;">/</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- (see cx below)</span>
<span style="color: #000000;">h</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">height</span><span style="color: #0000FF;">/</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">alive</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #000080;font-style:italic;">-- keep w, h odd for symmetry (plus I suspect the
-- "Cross" code above may now crash without this)</span>
<span style="color: #000000;">w</span> <span style="color: #0000FF;">-=</span> <span style="color: #7060A8;">even</span><span style="color: #0000FF;">(</span><span style="color: #000000;">w</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">h</span> <span style="color: #0000FF;">-=</span> <span style="color: #7060A8;">even</span><span style="color: #0000FF;">(</span><span style="color: #000000;">h</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">w</span>
<span style="color: #008080;">or</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])!=</span><span style="color: #000000;">h</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">),</span><span style="color: #000000;">w</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">draw</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'X'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">hTimer</span><span style="color: #0000FF;">!=</span><span style="color: #004600;">NULL</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupStoreAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hTimer</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RUN"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"YES"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">cdCanvasActivate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--
-- There is a "dead border" of 1 cell all around the edge of c (etc) which
-- we never display or update. If we have got this right/an exact fit, then
-- w*n should be exactly 2n too wide, whereas in the worst case there is an
-- (2n-1) pixel border, which we split between left and right, ditto cy.
--</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">cx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">width</span><span style="color: #0000FF;">-</span><span style="color: #000000;">w</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">cy</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">height</span><span style="color: #0000FF;">-</span><span style="color: #000000;">h</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">cxy</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">clxy</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cl</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">cnxy</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">cxy</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">x</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">y</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">cnxy</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">live</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cxy</span><span style="color: #0000FF;">?</span><span style="color: #000000;">cnxy</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">2</span> <span style="color: #008080;">and</span> <span style="color: #000000;">cnxy</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">3</span><span style="color: #0000FF;">:</span><span style="color: #000000;">cnxy</span><span style="color: #0000FF;">==</span><span style="color: #000000;">3</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">colour</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">live</span><span style="color: #0000FF;">?</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cxy</span><span style="color: #0000FF;">?</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">clxy</span><span style="color: #0000FF;">?</span><span style="color: #004600;">CD_PURPLE</span> <span style="color: #000080;font-style:italic;">-- adult</span>
<span style="color: #0000FF;">:</span><span style="color: #004600;">CD_GREEN</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- newborn</span>
<span style="color: #0000FF;">:</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">clxy</span><span style="color: #0000FF;">?</span><span style="color: #004600;">CD_RED</span> <span style="color: #000080;font-style:italic;">-- old</span>
<span style="color: #0000FF;">:</span><span style="color: #004600;">CD_YELLOW</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- shortlived</span>
<span style="color: #0000FF;">:</span><span style="color: #004600;">CD_BLACK</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cn</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">live</span>
<span style="color: #000000;">alive</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">live</span>
<span style="color: #7060A8;">cdCanvasSetForeground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">colour</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasBox</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cx</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cy</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cy</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">n</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">cx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">n</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">cdCanvasFlush</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">alive</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupStoreAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hTimer</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RUN"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"NO"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupStoreAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"died"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #000000;">cn</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupStoreAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hTimer</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RUN"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"NO"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupStoreAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"stable"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">cl</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">c</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cn</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">fps</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()>=</span><span style="color: #000000;">t1</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s (%d FPS)"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">title</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fps</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
<span style="color: #000000;">fps</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">map_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cdcanvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_IUP</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cddbuffer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_DBUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetBackground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_WHITE</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetForeground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_RED</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">key_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_ESC</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CLOSE</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- (standard practice for me)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_F5</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- (let browser reload work)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">draw</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Clear</span>
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"+bB"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">draw</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'+'</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Blinker</span>
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"gG"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">draw</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'G'</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Glider</span>
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"tT"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">draw</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'T'</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Thunderbird</span>
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"xX"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">draw</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'X'</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Cross</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">IupStoreAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hTimer</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RUN"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"YES"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">timer_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupUpdate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_IGNORE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">canvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupCanvas</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"RASTERSIZE=390x390"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetCallbacks</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"MAP_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"map_cb"</span><span style="color: #0000FF;">),</span>
<span style="color: #008000;">"ACTION"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"redraw_cb"</span><span style="color: #0000FF;">)})</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="%s", MINSIZE=350x55`</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">title</span><span style="color: #0000FF;">})</span>
<span style="color: #000080;font-style:italic;">-- (above MINSIZE prevents the title from getting squished)</span>
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"KEY_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"key_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- hTimer = IupTimer(Icallback("timer_cb"),40) -- 25fps (maybe)</span>
<span style="color: #000000;">hTimer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupTimer</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"timer_cb"</span><span style="color: #0000FF;">),</span><span style="color: #000000;">100</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 10fps</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|Picat}}==
Ihandle dlg, canvas, hTimer
===Blinker===
cdCanvas cddbuffer, cdcanvas
<syntaxhighlight lang="picat">go =>
Rows = 3,
Cols = 3,
println(blinker),
pattern(blinker, Pattern,I,J),
life(fill(Rows,Cols,Pattern,I,J)),
nl.
 
fill(Rows, Cols, Obj) = fill(Rows, Cols, Obj,1,1).
sequence c = {}, -- cells
fill(Rows, Cols, Obj,OffsetI,OffsetJ) = Grid =>
cn, -- new cells
Grid = new_array(Rows,Cols), bind_vars(Grid,0),
cl -- last cells
foreach(I in 1..Obj.length, J in 1..Obj[1].length)
Grid[I+OffsetI-1,J+OffsetJ-1] := Obj[I,J]
end.
 
% We stop whenever a fixpoint/cycle is detected
procedure draw(integer what)
life(S) =>
integer lx = length(c)
integer ly Rows = S.length(c[1]),
Cols = S[1].length,
integer x = floor(lx/2)
println([rows=Rows, cols=Cols]),
integer y = floor(ly/2)
switch what doprint_grid(S),
Seen = new_map(), % casedetect 'fixpoint 'and : -- Clearcycle
cCount = sq_mul(c0,0)
while (not Seen.has_key(S))
case '+' : -- Blinker
{c[x-1Seen.put(S,y],c[x,y],c[x+1),y]} @= 1
T case= 'G' : -- Glidernew_array(Rows,Cols),
foreach(I in 1..Rows, J in 1..Cols)
{ c[x+1,y+4],
Sum = csum([xS[I+2A,yJ+2B], : A in -1..1,B in -1..1, c[x+2,y+4],
c[x I+3A > 0,y J+3],c[x+3,y+4]}B @=> 0, 1
I+A =< Rows, J+B =< Cols]) - S[I,J],
case 'T' : -- Thunderbird
C {c= rules(S[x-1I,y+1J],c[x,y+1],c[x+1,y+1] Sum),
c[x,y+3],c[x,y+4],cT[xI,y+5J]} @:= 1C
case 'X' : -- Crossend,
for x=2 to lx-1 doprint_grid(T),
S y := floor(ly*x/lx)T,
Count := Count + if y>1 then
end,
{c[x,y],c[x,ly-y]} @= 1
printf("%d generations\n", Count).
end if
end for
end switch
end procedure
 
print_grid(G) =>
atom t0 = time()
foreach(I in 1..G.length)
foreach(J in 1..G[1].length)
if G[I,J] == 1 then print("#") else print(".") end
end,
nl
end,
nl.
 
% The Rules of Life
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
rules(This,Sum) = 1, (This == 1, member(Sum,[2,3]); This == 0, Sum == 3) => true.
integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
rules(_This, _Sum) = 0 => true.
integer colour, cnxy, live, alive = 0
if length(c)!=height
or length(c[1])!=width then
c = repeat(repeat(0,height),width)
cn = c
cl = c
draw('X')
end if
cdCanvasActivate(cddbuffer)
for y=2 to height-1 do
for x=2 to width-1 do
integer xm1 = x-1, xp1 = x+1,
ym1 = y-1, yp1 = y+1
cnxy = c[xm1,ym1] + c[x,ym1] + c[xp1,ym1] +
c[xm1,y] + c[xp1,y] +
c[xm1,yp1] + c[x,yp1] + c[xp1,yp1]
if c[x,y]=1 then
live = (cnxy>=2 and cnxy<=3)
else
live = (cnxy=3)
end if
cn[x,y] = live
alive += live
if live then
if c[x,y] then
colour = iff(cl[x,y]?CD_PURPLE -- adult
:CD_GREEN) -- newborn
else
colour = iff(cl[x,y]?CD_RED -- old
:CD_YELLOW) -- shortlived
end if
else
colour = CD_BLACK
end if
cdCanvasPixel(cddbuffer, x, y, colour)
end for
end for
cdCanvasFlush(cddbuffer)
if not alive then
IupStoreAttribute(hTimer, "RUN", "NO")
IupStoreAttribute(dlg, "TITLE", "died")
-- elsif cl=cn then -- (made blinker stable)
elsif c=cn then
IupStoreAttribute(hTimer, "RUN", "NO")
IupStoreAttribute(dlg, "TITLE", "stable")
else
cl = c
c = cn
IupSetStrAttribute(dlg, "TITLE", "%3.2f", {time()-t0})
end if
return IUP_DEFAULT
end function
 
%
function map_cb(Ihandle ih)
% The patterns
cdcanvas = cdCreateCanvas(CD_IUP, ih)
% pattern(Name, Pattern, OffsetI, OffsetJ)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
% where Offset* is the recommended offsets in a grid.
cdCanvasSetBackground(cddbuffer, CD_WHITE)
%
cdCanvasSetForeground(cddbuffer, CD_RED)
return IUP_DEFAULT
end function
 
% For the task
function key_cb(Ihandle /*ih*/, atom c)
pattern(blinker, Pattern,I,J) ?=>
if find(c," ") then draw(' ') -- Clear
Pattern = [[0,0,0],
elsif find(c,"+bB") then draw('+') -- Blinker
elsif find(c,"gG") then draw('G') -- Glider [1,1,1],
[0,0,0]],
elsif find(c,"tT") then draw('T') -- Thunderbird
I=1,J=1.</syntaxhighlight>
elsif find(c,"xX") then draw('X') -- Cross
end if
IupStoreAttribute(hTimer, "RUN", "YES")
IupStoreAttribute(dlg, "TITLE", "Life")
if c=K_ESC then return IUP_CLOSE end if
return IUP_CONTINUE
end function
 
{{out}}
function timer_cb(Ihandle /*ih*/)
<pre>
IupUpdate(canvas)
blinker
return IUP_IGNORE
[rows = 3,cols = 3]
end function
...
###
...
 
.#.
.#.
.#.
 
...
###
...
 
2 generations</pre>
 
===Testing some more forms===
procedure main()
<syntaxhighlight lang="picat">go2 =>
IupOpen()
Rows = 20,
Cols = 20,
Names = [blinker2, p4, p5, glider, figure_eight],
foreach(Name in Names )
pattern(Name, Pattern,I,J),
println(Name),
life(fill(Rows,Cols,Pattern,I,J)),
nl
end,
nl.
 
% Increase the recommended offset
canvas = IupCanvas(NULL)
pattern(blinker2, Pattern,I,J) ?=>
IupSetAttribute(canvas, "RASTERSIZE", "200x200") -- initial size
Pattern = [[0,0,0],
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
[1,1,1],
[0,0,0]],
I=5,J=5.
 
pattern(p4, Pattern,I,J) ?=>
dlg = IupDialog(canvas)
Pattern = [[0,0,0,0],
IupSetAttribute(dlg, "TITLE", "Conway's Game of Life")
[1,1,1,1],
IupSetCallback(dlg, "K_ANY", Icallback("key_cb"))
[1,1,1,1],
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
[0,0,0,0]],
I=10,J=10.
 
pattern(p5, Pattern,I,J) ?=>
hTimer = IupTimer(Icallback("timer_cb"), 30)
Pattern = [[0,0,0,0,0],
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1],
[0,0,0,0,0]],
I=10,J=10.
 
pattern(glider, Pattern,I,J) ?=>
IupMap(dlg)
Pattern = [[0,0,1],
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
[1,0,1],
IupShowXY(dlg,IUP_CENTER,IUP_CENTER)
[0,1,1]],
IupMainLoop()
IupClose()I=5,J=5.
end procedure
 
pattern(figure_eight, Pattern,I,J) =>
main()</lang>
Pattern = [[1,1,1,0,0,0],
[1,1,1,0,0,0],
[1,1,1,0,0,0],
[0,0,0,1,1,1],
[0,0,0,1,1,1],
[0,0,0,1,1,1]],
I=10,J=10.</syntaxhighlight>
 
=={{header|PicoLisp}}==
Line 9,505 ⟶ 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 9,534 ⟶ 12,315:
(=: life (: next)) ) ) ) ) )
 
(life 5 5 b3 c3 d3)</langsyntaxhighlight>
Output:
<pre> 5
Line 9,556 ⟶ 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 9,615 ⟶ 12,396:
end;
end;
end Conway;</langsyntaxhighlight>
Results:
<pre>
Line 9,657 ⟶ 12,438:
00000
</pre>
 
=={{header|Pointless}}==
<syntaxhighlight lang="pointless">-----------------------------------------------------------
-- Print 100 simulated states of conway's game of life
-- for a glider starting pattern on a wrapping grid
-- Print generation number along with cells
 
output =
initCells
|> iterate(updateCells)
|> take(130)
|> enumerate
|> map(showPair)
|> printFrames
 
initCells =
[[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 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 0 0 0 0 1 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 1 0 0 0 1 1 1 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 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]]
 
width = length(initCells[0])
height = length(initCells)
 
positions =
for y in range(0, height - 1)
for x in range(0, width - 1)
yield (x, y)
 
-----------------------------------------------------------
-- Update each cell in the grid according to its position,
-- and convert the resulting list back to a 2D array
 
updateCells(cells) =
positions
|> map(tick(cells))
|> toNDArray((height, width))
 
-----------------------------------------------------------
-- Get the new value for a cell at a give position
-- based on the current cell values in the grid
 
tick(cells, pos) = toInt(survive or birth) where {
survive = cells[y][x] == 1 and count in {2, 3}
birth = cells[y][x] == 0 and count == 3
count = getCount(x, y, cells)
(x, y) = pos
}
 
-----------------------------------------------------------
-- Get the number of live neighbors of a given position
 
getCount(x, y, cells) = sum(
for dx in [-1, 0, 1]
for dy in [-1, 0, 1]
when (dx != 0 or dy != 0)
yield getNeighbor(x + dx, y + dy, cells)
)
 
getNeighbor(x, y, cells) = cells[y % height][x % width]
 
-----------------------------------------------------------
-- Print the board and generation number given pairs
-- of (gen, cells) from the enumerate function
 
showPair(pair) =
format("{}\ngeneration: {}", [showCells(cells), gen])
where (gen, cells) = pair
 
showCells(cells) =
toList(cells)
|> map(showRow)
|> join("\n")
 
showRow(row) =
format("|{}|", [map(showCell, toList(row)) |> join("")])
 
showCell(cell) =
if cell == 1 then "*" else " "</syntaxhighlight>
 
=={{header|PostScript}}==
<langsyntaxhighlight PostScriptlang="postscript">%!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400
 
Line 9,707 ⟶ 12,578:
 
1000 { drawboard showpage iter } repeat
%%EOF</langsyntaxhighlight>
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">
<lang Prolog>
%----------------------------------------------------------------------%
% GAME OF LIFE %
Line 9,890 ⟶ 12,761:
write_line(S,T).
write_line(_,[]) :- !.
</syntaxhighlight>
</lang>
 
'''Sample output:'''<br>
Line 9,897 ⟶ 12,768:
 
=={{header|Processing}}==
Inspired by Daniel ShiffmaShiffman's book The Nature of Code (http://natureofcode.com)
 
<langsyntaxhighlight lang="java">boolean play = true;
int cellSize = 10;
int cols, rows;
Line 10,038 ⟶ 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 10,151 ⟶ 13,022:
if p != last_cell:
last_cell = p
grid[i][j] = (1, 0)[grid[i][j]]</langsyntaxhighlight>
 
=={{header|Python}}==
Line 10,166 ⟶ 13,037:
of <u>universe</u> returns zero.
 
<langsyntaxhighlight lang="python">import random
from collections import defaultdict
 
Line 10,206 ⟶ 13,077:
 
for i in range(maxgenerations):
print ("\nGeneration %3i:" % ( i, ))
for row in range(cellcount[1]):
print (" ", ''.join(str(universe[(row,col)])
for col in range(cellcount[0])).replace(
'0', printdead).replace('1', printlive))
nextgeneration = defaultdict(int)
for row in range(cellcount[1]):
Line 10,220 ⟶ 13,091:
for c in range(col-1, col+2) )
) ]
universe = nextgeneration</langsyntaxhighlight>
{{out}} (sample)
<pre style="height:30ex;overflow:scroll">
Line 10,243 ⟶ 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 10,264 ⟶ 13,135:
def display(world, g):
"Display the world as a grid of characters."
print (' GENERATION {}:'.format(g))
Xs, Ys = zip(*world)
Xrange = range(min(Xs), max(Xs)+1)
for y in range(min(Ys), max(Ys)+1):
print (''.join('#' if (x, y) in world else '.'
for x in Xrange))
 
blinker = {(1, 0), (1, 1), (1, 2)}
Line 10,279 ⟶ 13,150:
 
 
life(world, 5)</langsyntaxhighlight>
 
{{out}}
Line 10,344 ⟶ 13,215:
.........................##........##
</pre>
 
===Using Array define the world===
===Using an array to define the world===
<lang python>import numpy as np
<syntaxhighlight lang="python">import numpy as np
from pandas import DataFrame
import matplotlib.pyplot as plt
Line 10,406 ⟶ 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 10,490 ⟶ 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 10,624 ⟶ 13,650:
;;; (game-of-life (thunder) 2)
;;; (game-of-life (cross) 2)
</syntaxhighlight>
</lang>
 
Output for an 80x80 cross:
Line 10,632 ⟶ 13,658:
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>class Automaton {
subset World of Str where {
.lines>>.chars.unique == 1 and m/^^<[.#\n]>+$$/
Line 10,689 ⟶ 13,715:
say $glider++;
say '--';
}</langsyntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="red">Red [
Purpose: "Conway's Game of Life"
Author: "Joe Smith"
]
 
neigh: [[0 1] [0 -1] [1 0] [-1 0] [1 1] [1 -1] [-1 1] [-1 -1]]
conway: function [petri] [
new-petri: copy/deep petri
repeat row length? petri [
repeat col length? petri [
live-neigh: 0
foreach cell neigh [
try [
if petri/(:row + cell/1)/(:col + cell/2) = 1 [live-neigh: live-neigh + 1]
]
]
switch petri/:row/:col [
1 [if any [live-neigh < 2 live-neigh > 3]
[new-petri/:row/:col: 0]
]
0 [if live-neigh = 3 [new-petri/:row/:col: 1]]
]]]
clear insert petri new-petri
]
 
*3-3: [
[0 1 0]
[0 1 0]
[0 1 0]
]
 
*8-8: [
[0 0 1 0 0 0 0 0]
[0 0 0 1 0 0 0 0]
[0 1 1 1 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
]
 
display: function [table] [
foreach row table [
print replace/all (replace/all to-string row "0" "_") "1" "#"
] print ""
]
 
loop 5 [
display *3-3
conway *3-3
]
loop 23 [
display *8-8
conway *8-8
]
</syntaxhighlight>
 
{{out}}
<pre style="height:50ex;overflow:scroll">
_#_
_#_
_#_
 
___
###
___
 
_#_
_#_
_#_
 
___
###
___
 
_#_
_#_
_#_
 
__#_____
___#____
_###____
________
________
________
________
________
 
________
_#_#____
__##____
__#_____
________
________
________
________
 
________
___#____
_#_#____
__##____
________
________
________
________
 
________
__#_____
___##___
__##____
________
________
________
________
 
________
___#____
____#___
__###___
________
________
________
________
 
________
________
__#_#___
___##___
___#____
________
________
________
 
________
________
____#___
__#_#___
___##___
________
________
________
 
________
________
___#____
____##__
___##___
________
________
________
 
________
________
____#___
_____#__
___###__
________
________
________
 
________
________
________
___#_#__
____##__
____#___
________
________
 
________
________
________
_____#__
___#_#__
____##__
________
________
 
________
________
________
____#___
_____##_
____##__
________
________
 
________
________
________
_____#__
______#_
____###_
________
________
 
________
________
________
________
____#_#_
_____##_
_____#__
________
 
________
________
________
________
______#_
____#_#_
_____##_
________
 
________
________
________
________
_____#__
______##
_____##_
________
 
________
________
________
________
______#_
_______#
_____###
________
 
________
________
________
________
________
_____#_#
______##
______#_
 
________
________
________
________
________
_______#
_____#_#
______##
 
________
________
________
________
________
______#_
_______#
______##
 
________
________
________
________
________
________
_______#
______##
 
________
________
________
________
________
________
______##
______##
 
________
________
________
________
________
________
______##
______##
</pre>
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">:w/l [ $. eq? [ #0 ] [ #1 ] choose , ] s:for-each ;
 
'World d:create
Line 10,761 ⟶ 14,076:
}}
#12 gens</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 10,767 ⟶ 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 10,811 ⟶ 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 10,842 ⟶ 14,157:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 02.08.2014 Walter Pachl
* Input is a file containing the initial pattern
Line 11,026 ⟶ 14,341:
Return lineout(dbg,arg(1))
Else
Return</langsyntaxhighlight>
{{out}}
<pre> blinker
Line 11,047 ⟶ 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 11,110 ⟶ 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 11,228 ⟶ 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 11,332 ⟶ 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 11,409 ⟶ 14,724:
life(glider, 20, 8, 8);
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
Line 11,417 ⟶ 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 11,506 ⟶ 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 11,804 ⟶ 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 11,906 ⟶ 15,221:
Curr_state=Next_state;
end</langsyntaxhighlight>
 
{{out}}
Line 11,946 ⟶ 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 12,018 ⟶ 15,333:
wait 1 second
end repeat
end RunGameOfLife</langsyntaxhighlight>
 
=={{header|SequenceL}}==
Line 12,024 ⟶ 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 12,044 ⟶ 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 12,226 ⟶ 15,541:
}
throw(errno);
}</langsyntaxhighlight>
 
'''Usage:'''
Line 12,259 ⟶ 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 12,293 ⟶ 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 12,429 ⟶ 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 12,464 ⟶ 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 12,633 ⟶ 15,948:
 
END.
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 12,930 ⟶ 16,245:
180 garbage collection(s) in 0.1 seconds.
</pre>
 
=={{header|Smalltalk}}==
This implementation has been developed using '''Cuis Smalltalk''' [https://github.com/Cuis-Smalltalk/Cuis-Smalltalk-Dev].
Here are different configurations:
<syntaxhighlight lang="smalltalk">
"Blinker"
GameOfLife withAliveCells: { 4@2. 4@3. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10.
 
"Toad"
GameOfLife withAliveCells: { 2@4. 3@4. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10
</syntaxhighlight>
This is the implementation:
<syntaxhighlight lang="smalltalk">
Object subclass: #GameOfLife
instanceVariableNames: 'aliveCells boardSize'
classVariableNames: ''
poolDictionaries: ''
category: 'GameOfLife'
 
GameOfLife class>>withAliveCells: aCollectionOfCells ofSize: aBoardSize
self assertAll: aCollectionOfCells areInside: aBoardSize.
^self new initializeWithAliveCells: aCollectionOfCells ofSize: aBoardSize
GameOfLife class>>assertAll: aCollectionOfAliveCells areInside: aSize
| origin |
origin := 0@0.
aCollectionOfAliveCells do: [:aCell |
(aCell between: origin and: aSize) ifFalse: [ self error: 'Cell ', aCell printString,' out of range' ]]
 
initializeWithAliveCells: aCollectionOfCells ofSize: aBoardSize
aliveCells := aCollectionOfCells asSet.
boardSize := aBoardSize
 
calculateNextGeneration
aliveCells := self boardCellsSelect: [ :aCell | self shouldBeAliveOnNextGeneration: aCell ]
 
shouldBeAliveOnNextGeneration: aCell
| numberOfAliveNeighbors |
numberOfAliveNeighbors := self numberOfAliveNeighborsOf: aCell.
^numberOfAliveNeighbors = 3 or: [ self shouldSurvive: aCell with: numberOfAliveNeighbors]
 
shouldSurvive: aCell with: numberOfAliveNeighbors
^ (self isAlive: aCell) and: [ numberOfAliveNeighbors = 2 ]
 
isAlive: aCell
^aliveCells includes: aCell
 
isDead: aCell
^(self isAlive: aCell) not
 
boardCellsDo: aClosure
0 to: boardSize x do: [ :x |
0 to: boardSize y do: [ :y | aClosure value: x@y ]]
 
boardCellsSelect: aCondition
| selectedCells |
selectedCells := Set new.
self boardCellsDo: [ :aCell | (aCondition value: aCell) ifTrue: [ selectedCells add: aCell ]].
^selectedCells
numberOfAliveNeighborsOf: aCell
^aCell eightNeighbors count: [ :aNeighbor | self isAlive: aNeighbor ]
</syntaxhighlight>
The implementation was developed using TDD. This are the tests used to implement it.
<syntaxhighlight lang="smalltalk">
TestCase subclass: #GameOfLifeTest
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'GameOfLife'
 
test01AliveCellWithLessThatTwoAliveCellsDies
| gameOfLife |
gameOfLife := GameOfLife withAliveCells: {1@1} ofSize: 3@3.
gameOfLife calculateNextGeneration.
self assert: (gameOfLife isDead: 1@1)
 
test02AliveCellWithTwoAliveNeighborsSurvives
| gameOfLife |
gameOfLife := GameOfLife withAliveCells: {1@1. 1@2. 2@1} ofSize: 3@3.
gameOfLife calculateNextGeneration.
self assert: (gameOfLife isAlive: 1@1).
 
test03AliveCellWithThreeAliveNeighborsSurvives
| gameOfLife |
gameOfLife := GameOfLife withAliveCells: {1@1. 1@2. 2@1. 2@2} ofSize: 3@3.
gameOfLife calculateNextGeneration.
self assert: (gameOfLife isAlive: 1@1).
 
test04DeadCellWithThreeAliveNeighborsBecomesAlive
| gameOfLife |
gameOfLife := GameOfLife withAliveCells: {1@1. 1@2. 2@1} ofSize: 3@3.
gameOfLife calculateNextGeneration.
self assert: (gameOfLife isAlive: 2@2).
 
test05DeadCellWithAliveNeighborsDifferentToThreeKeepsDead
| gameOfLife |
gameOfLife := GameOfLife withAliveCells: {1@2. 2@2. 3@2. 1@3} ofSize: 3@3.
gameOfLife calculateNextGeneration.
self assert: (gameOfLife isDead: 1@1).
self assert: (gameOfLife isDead: 2@3).
 
test06CanNotCreateGameWithCellOutsideXOrigin
self
should: [ GameOfLife withAliveCells: { 2@0. 1@0. -1@1 } ofSize: 3@3 ]
raise: Error - MessageNotUnderstood
withMessageText: 'Cell -1@1 out of range'
 
test07CanNotCreateGameWithCellOutsideYOrigin
self
should: [ GameOfLife withAliveCells: { 2@0. 1@0. 1@-1 } ofSize: 3@3 ]
raise: Error - MessageNotUnderstood
withMessageText: 'Cell 1@-1 out of range'
 
test08CanNotCreateGameWithCellOutsideXLimit
self
should: [ GameOfLife withAliveCells: { 2@0. 1@0. 4@1 } ofSize: 3@3 ]
raise: Error - MessageNotUnderstood
withMessageText: 'Cell 4@1 out of range'
 
test09CanNotCreateGameWithCellOutsideYLimit
self
should: [ GameOfLife withAliveCells: { 2@0. 1@0. 1@4 } ofSize: 3@3 ]
raise: Error - MessageNotUnderstood
withMessageText: 'Cell 1@4 out of range'
</syntaxhighlight>
If you want to have a visual representation, here is a view for it:
<syntaxhighlight lang="smalltalk">
ImageMorph subclass: #GameOfLifeView
instanceVariableNames: 'game'
classVariableNames: ''
poolDictionaries: ''
category: 'GameOfLife'
 
GameOfLifeView class>>for: aGameOfLife
^self new initializeFor: aGameOfLife
 
GameOfLifeView class>>openFor: aGameOfLife
^(self for: aGameOfLife) open
 
GameOfLifeView class>>blinker
^GameOfLife withAliveCells: { 4@2. 4@3. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10
GameOfLifeView class>>toad
^GameOfLife withAliveCells: { 2@4. 3@4. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10
 
GameOfLifeView class>>openBlinker
^self openFor: self blinker
 
GameOfLifeView class>>openToad
^self openFor: self toad
 
initializeFor: aGameOfLife
game := aGameOfLife.
self image: (Form extent: game boardSize * 5 depth: 2).
 
open
self showBoard.
self openInWorld.
self startSteppingStepTime: 500
 
showBoard
game boardCellsDo: [ :aPoint |
(game isAlive: aPoint)
ifTrue: [ self form fillBlack: (aPoint*5 extent: 5@5) ]
ifFalse: [ self form fillWhite: (aPoint*5 extent: 5@5) ]].
 
step
game calculateNextGeneration.
self showBoard.
self redrawNeeded.
</syntaxhighlight>
 
=={{header|SQL}}==
Line 12,935 ⟶ 16,422:
 
{{works with|Oracle}}
<langsyntaxhighlight lang="sql">
-- save these lines in a file called
-- setupworld.sql
Line 13,052 ⟶ 16,539:
from output
order by y desc;
</syntaxhighlight>
</lang>
 
<pre>
Line 13,084 ⟶ 16,571:
{{trans|Rust}}
 
<langsyntaxhighlight lang="swift">struct Cell: Hashable {
var x: Int
var y: Int
Line 13,178 ⟶ 16,665:
 
print("Glider: ")
col.run(iterations: 20)</langsyntaxhighlight>
 
{{out}}
Line 13,416 ⟶ 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 13,444 ⟶ 16,931:
end
 
endmodule</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc main {} {
Line 13,526 ⟶ 17,013:
}
 
main</langsyntaxhighlight>
<pre style='height:30ex; overflow:scroll'>blinker generation 1:
. # .
Line 13,565 ⟶ 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 13,573 ⟶ 17,205:
sequence of n boards evolving from it.
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 13,580 ⟶ 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 13,600 ⟶ 17,232:
#show+
 
examples = mat0 ~&?(`O!,`+!)*** evolve3(blinker)-- evolve5(glider)</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">+++
Line 13,656 ⟶ 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 13,713 ⟶ 17,345:
Ins_Char(Cur_Char+1,OVERWRITE)
}
Return</langsyntaxhighlight>
 
{{out}}
Line 13,733 ⟶ 17,365:
=={{header|Wortel}}==
Mapping over a matrix.
<langsyntaxhighlight lang="wortel">@let {
life &m ~!* m &[a y] ~!* a &[v x] @let {
neigh @sum [
Line 13,756 ⟶ 17,388:
!^life 2 blinker
]]
}</langsyntaxhighlight>
{{out}}
<pre>[
Line 13,777 ⟶ 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 13,829 ⟶ 17,461:
!^life 2 blinker
]]
}</langsyntaxhighlight>
{{out}}
<pre>[
Line 13,848 ⟶ 17,480:
[0 0 0 0 0]]
]</pre>
 
=={{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">
option explicit
const tlcr=3, tlcc=3
const maxdim=15
 
dim a(15,15)
dim b(15,15)
dim ans0:ans0=chr(27)&"["
dim gen,n
 
erase a
'glider
a(0,1)=true:a(1,2)=true:a(2,0)=true:a(2,1)=true:a(2,2)=true
'blinker
a(3,13)=true:a(4,13)=true:a(5,13)=true
'beacon
a(11,1)=true:a(11,2)=true: a(12,1)=true:a(12,2)=true
a(13,3)=true:a(13,4)=true: a(14,3)=true:a(14,4)=true
 
gen=0
doframe
 
do
display
wscript.sleep(100)
n=newgen
loop until n=0
display
 
sub cls() wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub 'hide cursor too
sub toxy(r,c,s) wscript.StdOut.Write ans0 & r & ";" & c & "f" & s :end sub
function iif(a,b,c) if a then iif=b else iif=c end if :end function
 
sub doframe
dim r,c,s
const frame="@"
cls
toxy 1,tlcc-1, "Conway's Game of Life"
toxy tlcr-1,tlcc-1,string(maxdim+3,frame)
s=frame&space(maxdim+1)&frame
for r=0 to maxdim
toxy tlcr+r,tlcc-1,s
next
toxy tlcr+maxdim+1,tlcc-1,string(maxdim+3,frame)
end sub
 
sub display
dim r,c
const pix="#"
for r=0 to maxdim
for c=0 to maxdim
toxy tlcr+r,tlcc+c,iif (a(r,c),pix," ")
next
next
toxy tlcr+maxdim+2,tlcc-1,gen & " " & n
toxy tlcr+maxdim+3,tlcc-1,""
gen=gen+1
end sub
 
function newgen
dim r,c,cnt,cp,cm,rp,rm
for r=0 to maxdim
for c=0 to maxdim
cp=(c+1) and maxdim 'wrap around
cm=(c-1) and maxdim
rp=(r+1) and maxdim
rm=(r-1) and maxdim
cnt=0
cnt=- a(rp,cp) - a(rp,c) - a(rp,cm) 'true =-1
cnt=cnt- a(r,cp)- a(r,cm)
cnt=cnt- a(rm,cp)- a(rm,c) - a(rm,cm)
if a(r,c) then
b(r,c)=iif (cnt=2 or cnt=3,true,false)
else
b(r,c)=iif (cnt=3,true,false)
end if
next
next
for r=0 to maxdim
for c=0 to maxdim
a(r,c)=b(r,c)
newgen=newgen- b(r,c)
next
next
end function
</syntaxhighlight>
<pre>
Conway's Game of Life
@@@@@@@@@@@@@@@@@@
@ @
@ @
@ @
@ # # @
@ # # # @
@ ## # @
@ @
@ @
@ @
@ @
@ @
@ ## @
@ # @
@ # @
@ ## @
@ @
@@@@@@@@@@@@@@@@@@
9 14
</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">
option explicit
const pix="##"
const cl_on=16
const cl_mnum=15
randomize timer
const tlcr=2, tlcc=2
const maxdim =31
settitle "Conway's game of life"
 
dim a(31,31)
 
dim ans0:ans0=chr(27)&"["
dim gen,n
gen=0
paintframe
'init1 'objects
init2 400 'random
 
do
n=nextgen
toxy tlcr-1,tlcc+maxdim*2+4,gen & " " & n
toxy tlcr,tlcc+maxdim*2+3,""
gen=gen+1
loop until n=0
 
sub pause() wscript.stdout.write vbcrlf & "Press Enter":wscript.stdin.readline: end sub
sub settitle(s) wscript.StdOut.Write chr(27)&"]0;"& s &chr(7):end sub
sub cls() wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub
sub toxy(r,c,s) wscript.StdOut.Write ans0 & r & ";" & c & "f" & s :end sub
function iif(a,b,c) if a then iif=b else iif=c end if :end function
 
sub init1
dim x
update 0,1,1,x:update 1,2,1,x:update 2,0,1,x:update 2,1,1,x:update 2,2,1,x
update 3,13,1,x:update 4,13,1,x:update 5,13,1,x
update 11,1,1,x:update 11,2,1,x: update 12,1,1,x:update 12,2,1,x
update 13,3,1,x:update 13,4,1,x: update 14,3,1,x:update 14,4,1,x
end sub
 
sub init2 (n)
dim i,r,c,x
for i=1 to n
do
r=cint(rnd*maxdim)
c=cint(rnd*maxdim)
loop until (a(r,c) and cl_on)=0
update r,c,1,x
next
end sub
 
sub paintframe
dim r,c,s
const frame="@"
cls
'toxy 1,tlcc-1, "Conway's Game of Life"
toxy tlcr-1,tlcc-1,string(maxdim*2+4,frame)
s=frame&space(maxdim*2+2)&frame
for r=0 to maxdim
toxy tlcr+r,tlcc-1,s
next
toxy tlcr+maxdim+1,tlcc-1,string(maxdim*2+4,frame)
end sub
 
function nextgen()
dim r,c,pre,cnt,a1,onoff,chg
nextgen=0
a1=a 'does a hard a copy of a
for r=0 to maxdim
for c=0 to maxdim
if a1(r,c)then 'check only cells alive or having neighbors
pre=a1(r,c) and cl_on
cnt=a1(r,c) and cl_mnum
'check life condition and update cell
if pre<>0 and (cnt<2 or cnt>3) then
update r,c,0,nextgen
elseif pre=0 and cnt=3 then
update r,c,1,nextgen
end if
end if
next
next
end function
 
sub update(r,c,onoff,nextgen)
'displays cell and update neighbors count in neighbors
dim cp,cm,rp,rm,inc,mask
mask=iif(onoff,cl_on,0)
a(r,c)= (a(r,c) and cl_mnum) or mask 'update cell
toxy tlcr+r,tlcc+c*2,iif (onoff,pix," ") 'display cell
cp=(c+1) and maxdim 'wrap around
cm=(c-1) and maxdim
rp=(r+1) and maxdim
rm=(r-1) and maxdim
if onoff then inc=1 else inc=-1
'update count in neighbors
a(rp,cp)=(a(rp,cp) and cl_on) or ((a(rp,cp) and cl_mnum)+inc)
a(rp,c)=(a(rp,c) and cl_on) or ((a(rp,c) and cl_mnum)+inc)
a(rp,cm)=(a(rp,cm) and cl_on) or ((a(rp,cm) and cl_mnum)+inc)
a(r,cp)=(a(r,cp) and cl_on) or ((a(r,cp) and cl_mnum)+inc)
a(r,cm)=(a(r,cm) and cl_on) or ((a(r,cm) and cl_mnum)+inc)
a(rm,cp)=(a(rm,cp) and cl_on) or ((a(rm,cp) and cl_mnum)+inc)
a(rm,c)=(a(rm,c) and cl_on) or ((a(rm,c) and cl_mnum)+inc)
a(rm,cm)=(a(rm,cm) and cl_on) or ((a(rm,cm) and cl_mnum)+inc)
nextgen=nextgen+1
end sub
</syntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import rand
import strings
import time
 
struct Field {
mut:
s [][]bool
w int
h int
}
fn new_field(w int, h int) Field {
s := [][]bool{len: h, init: []bool{len: w}}
return Field{s, w, h}
}
fn (mut f Field) set(x int, y int, b bool) {
f.s[y][x] = b
}
fn (f Field) next(x int, y int) bool {
mut on := 0
for i := -1; i <= 1; i++ {
for j := -1; j <= 1; j++ {
if f.state(x+i, y+j) && !(j == 0 && i == 0) {
on++
}
}
}
return on == 3 || (on == 2 && f.state(x, y))
}
fn (f Field) state(xx int, yy int) bool {
mut x, mut y := xx, yy
for y < 0 {
y += f.h
}
for x < 0 {
x += f.w
}
return f.s[y%f.h][x%f.w]
}
struct Life {
mut:
w int
h int
a Field
b Field
}
fn new_life(w int, h int) Life {
mut a := new_field(w, h)
for _ in 0..(w * h / 2) {
a.set(rand.intn(w) or {0}, rand.intn(h) or {0}, true)
}
return Life{
a: a,
b: new_field(w, h),
w: w
h: h,
}
}
fn (mut l Life) step() {
for y in 0..l.h {
for x in 0.. l.w {
l.b.set(x, y, l.a.next(x, y))
}
}
l.a, l.b = l.b, l.a
}
fn (l Life) str() string {
mut buf := strings.new_builder(128)
for y in 0..l.h {
for x in 0..l.w {
mut b := ' '
if l.a.state(x, y) {
b = '*'
}
buf.write_string(b)
}
buf.write_string('\n')
}
return buf.str()
}
fn main() {
mut l := new_life(80, 15)
for i := 0; i < 300; i++ {
l.step()
//println("------------------------------------------------")
print('\x0c')
println(l)
time.sleep(time.second / 30)
}
}</syntaxhighlight>
 
{{out}}
Generation 300:
<pre> ** *** *
* **
* * **
** ** ** *
** **
** *** * *
****** *
* * **
* * ** * *
** * * **
** * * * * **
* * ** **
* * ** *
** * </pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">import "random" for Random
import "timer" for Timer
 
var Rand = Random.new(0) // using a constant seed to produce same output on each run
 
// patterns
var BLINKER = 0
var GLIDER = 1
var RANDOM = 2
 
class Field {
construct new(w, h) {
_w = w
_h = h
_s = List.filled(h, null)
for (i in 0...h) _s[i] = List.filled(w, false)
}
 
[x, y]=(b) { _s[y][x] = b }
 
state(x, y) {
if (!(0..._w).contains(x) || !(0..._h).contains(y)) return false
return _s[y][x]
}
 
next(x, y) {
var on = 0
for (i in -1..1) {
for (j in -1..1) {
if (state(x + i, y + j) && !(j == 0 && i == 0)) on = on + 1
}
}
return on == 3 || (on == 2 && state(x, y))
}
}
 
class Life {
construct new(pattern) {
if (pattern == BLINKER) {
_w = 3
_h = 3
_a = Field.new(_w, _h)
_b = Field.new(_w, _h)
_a[0, 1] = true
_a[1, 1] = true
_a[2, 1] = true
} else if (pattern == GLIDER) {
_w = 4
_h = 4
_a = Field.new(_w, _h)
_b = Field.new(_w, _h)
_a[1, 0] = true
_a[2, 1] = true
for (i in 0..2) _a[i, 2] = true
} else if(pattern == RANDOM) {
_w = 80
_h = 15
_a = Field.new(_w, _h)
_b = Field.new(_w, _h)
for (i in 0...(_w * _h).floor / 2) {
_a[Rand.int(_w), Rand.int(_h)] = true
}
}
}
 
step() {
for (y in 0..._h) {
for (x in 0..._w) _b[x, y] = _a.next(x, y)
}
var t = _a
_a = _b
_b = t
}
 
toString {
var sb = ""
for (y in 0..._h) {
for (x in 0..._w) {
var c = _a.state(x, y) ? "#" : "."
sb = sb + c
}
sb = sb + "\n"
}
return sb
}
}
 
var lives = [
[Life.new(BLINKER), 3, "BLINKER"],
[Life.new(GLIDER), 4, "GLIDER" ],
[Life.new(RANDOM), 100, "RANDOM" ]
]
 
for (t in lives) {
var game = t[0]
var gens = t[1]
var title = t[2]
System.print("%(title):\n")
for (i in 0..gens) {
System.print("Generation: %(i)\n%(game)")
Timer.sleep(30)
game.step()
}
System.print()
}</syntaxhighlight>
 
{{out}}
Just shows generations 0 and 100 for RANDOM pattern:
<pre>
BLINKER:
 
Generation: 0
...
###
...
 
Generation: 1
.#.
.#.
.#.
 
Generation: 2
...
###
...
 
Generation: 3
.#.
.#.
.#.
 
 
GLIDER:
 
Generation: 0
.#..
..#.
###.
....
 
Generation: 1
....
#.#.
.##.
.#..
 
Generation: 2
....
..#.
#.#.
.##.
 
Generation: 3
....
.#..
..##
.##.
 
Generation: 4
....
..#.
...#
.###
 
 
RANDOM:
 
Generation: 0
#.#.###.#...#...#..##.....#......#....#...#.....#...#..#..#.....##.##....#..####
..#...#....#.##..#..#...##.#.....#....#..##.#.###..#.#.#.#..#.##..#.#.......#.#.
###.###..##...#......#.#.#............#.......##.#..#...###.##..#...###...#..#..
.#.....#.#.#.#.#..###.#.#.######...##..##.###.####....#....#####..##...####.#..#
..##.###.#..###...#..#..##....##...#..##.##.#..###.#..#..#.#...##..#..###.......
.####..###.##..#..#...#..#..#.##..#..........##.#..#.....#.###.#...######.#..#..
...##...#.....##.....##.##..#..#####...##.###.#.###..#..#.#.....##.#..##....##.#
##...##.#...#.#...##.##..#.#..##.#....###.##.#.....#.##..#..#.##..#....##......#
....#.#..##.#..####..#..##....#####.#....#.#...#.#.###.#.#.#.#.#.....#...#.....#
..#..####..###..###..##.####.#....#.....#.###.#.#.###.####..#...#...#...#.##....
#.........##..#..##...###...#..#....#.###...#.##.....###..###..##....###.#..#...
.#..#..#......#...##.###.#...#.#...##.#.....#...#......##..#.....###...##..#.#..
.#.#.....##..#.##.....#.#.#..#.#..######.#....#..##...##.##.....#..##...#.##.##.
.#......###..#...###..........................##......#....####.#...#..#...#..#.
#..#.#......#...#...#...#..#..##...#.##...#.####.##......#....#..#.##.....#####.
 
Generation: 100
...............####......#......................................................
...............#..#.....#.#...................#.................................
........................#.#.................##..................................
.........................#..................##............##....................
............................................#.....#.......##....................
.............................................#.###..............................
...................................##...###.....#####...........................
........................##........#..#..###........#............................
.......................#..#...........#....##...................................
.......................#....#.......#....###....................................
........................######.....##....##.....................................
...........................#.##.....#..#..........................##.##.........
...........................#.#.......##...........................##.##.........
......##...................##...................................................
......##........................................................................
</pre>
 
=={{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 13,881 ⟶ 18,055:
I:= NowGen; NowGen:= NewGen; NewGen:= I; \swap arrays
];
]</langsyntaxhighlight>
 
{{out}}
Line 13,900 ⟶ 18,074:
=={{header|XSLT}}==
So when the following templates
<langsyntaxhighlight lang="xml"><xsl:template match="/table">
<table>
<xsl:apply-templates />
Line 13,948 ⟶ 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}}==
{{works with|zmac|5nov2016}}
This code will run on an MSX computer if progammed on a cartride
or on an emulator (like openMSX) if loaded as a .rom file
 
The code below will show the Gosper glider gun, but
if INITLINES is set to 0 the code will show the blinker
 
<syntaxhighlight lang="z80">;MSX Bios calls
CHPUT equ 000A2H ;print character A
CHGET equ 0009FH ;wait for keyboard input
INITXT equ 0006CH ;init TEXT1 mode (40 x 24), based on TXTNAM,TXTCGP and LINL40
LDIRVM equ 0005CH ;write BC times MEM(HL++) to VRAM(DE++)
 
;MSX system variables
TXTNAM equ 0F3B3H ;pattern name table
TXTCGP equ 0F3B7H ;pattern generator table
LINL40 equ 0F3AEH ;line length
 
;defines
LIFE_CHAR equ 0xDB ;MSX all-pixels-on character
 
;variables
screen equ 0E000H ;40x24 bytes
scratch equ screen+(40*24) ;table for calculations
 
 
org 04000H
;*********************************************************************
HEADER ;first 16 bytes of the rom. (as specified by MSX standard)
;*********************************************************************
db "AB" ;id
dw Main ;init
dw 0 ;statement
dw 0 ;device
dw 0 ;text
dw 0 ;reserved
dw 0 ;reserved
dw 0 ;reserved
 
init_tab1 db 0x18
dc 7, 0x17
db " Conway's Game Of Life "
dc 8, 0x17
db 0x19
db 0x16
dc 38, " "
db 0x16, 0x1A
dc 38, 0x17
db 0x1B
init_tab2 dc 41, 0x80
dc 38, 0
dc 41, 0x80
 
INITLINES equ 10
init_tab3 db " "
db " X "
db " X X "
db " XX XX XX "
db " X X XX XX "
db " XX X X XX "
db " XX X X XX X X "
db " X X X "
db " X X "
db " XX "
 
Expand ld bc, 40
ldir ;copy top line
push de
ld bc, 40
ldir ;copy first middle line
ex (sp), hl
ld bc, 40*21
ldir ;repeat middle line
pop hl
ld bc, 40 ;copy bottom line
ldir
ret
 
InitGOL ;create empty screen
ld hl, init_tab1
ld de, screen
call Expand
;Now add intial pattern
if INITLINES
ld hl, init_tab3 ;glider gun start pattern
ld de, init_tab3 ;de=hl, so ldi does not change RAM
ld bc, 40*INITLINES
ld ix, screen+40
InitGOLl ld a, (hl)
cp 'X'
jr nz, InitGOLe
ld (ix), LIFE_CHAR
InitGOLe inc ix
ldi ;hl++ and bc-- (with flag!)
jp pe, InitGOLl
else
ld hl, screen+(4*40)+18
ld a, LIFE_CHAR ;blinker start pattern
ld (hl), a
inc hl
ld (hl), a
inc hl
ld (hl), a
endif
ret
DoGOL ld hl, init_tab2 ;initialize scratchpad (sums to zero, borders marked)
ld de, scratch
call Expand
;first loop: create sums in scratchpad
ld bc, 40*24
ld hl, screen
ld de, screen ;de=hl, so ldi does not change RAM
ld ix, scratch
DoGOLsuml ld a, (hl)
cp LIFE_CHAR ;if cell is alive increase sums of all surrounding cells
jr nz, DoGOLsume
inc (ix-41)
inc (ix-40)
inc (ix-39)
inc (ix-1)
inc (ix+1)
inc (ix+39)
inc (ix+40)
inc (ix+41)
DoGOLsume inc ix
ldi ;hl++, bc-- (with flag!)
jp pe, DoGOLsuml
;second loop: update cell based on current state and sum
ld bc, 40*24
ld hl, screen
ld de, screen ;de=hl, so ldi does not change RAM
ld ix, scratch
DoGOLupdl ld a, (ix)
cp 0x7f ;border -> keep the same
jr nc, DoGOLupde
cp 3 ;3 neighbors-> always live
jr z, DoGOLlive
cp 2
jr z, DoGOLupde ;2 -> stay the same
DoGOLdie ld (hl), 0x20 ;1,4,5,6,7,8 -> always die
jr DoGoLupde
DoGOLlive ld (hl), LIFE_CHAR
DoGOLupde inc ix
ldi ;hl++, bc-- (with flag!)
jp pe, DoGOLupdl
ret
 
;*********************************************************************
Main
;*********************************************************************
call INITXT
call InitGOL
Mainloop ld hl, screen
ld de, (TXTNAM)
ld bc, 40*24
call LDIRVM
;call CHGET
call DoGOL
jr Mainloop
;force 16k ROM size binary output
EndOfCode dc 0x8000 - EndOfCode, 0xFF
end</syntaxhighlight>
 
=={{header|Yabasic}}==
{{output?|Yabasic}}
{{trans|BASIC256}}
<langsyntaxhighlight Yabasiclang="yabasic">// Conway's_Game_of_Life
X = 59 : Y = 35 : H = 4
Line 14,034 ⟶ 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 14,071 ⟶ 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 14,089 ⟶ 18,429:
 
=={{header|ZPL}}==
<langsyntaxhighlight ZPLlang="zpl">program Life;
 
config var
Line 14,116 ⟶ 18,456:
TW := (TW & NN = 2) | ( NN = 3);
until !(|<< TW);
end;</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
Line 14,122 ⟶ 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 14,142 ⟶ 18,482:
190 PRINT AT 0,0;w$
200 LET w$=n$
210 GO TO 80</langsyntaxhighlight>
6

edits