Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ElmerCSC
GitHub Repository: ElmerCSC/elmerfem
Path: blob/devel/contrib/lua-5.1.5/test/life.lua
3203 views
1
-- life.lua
2
-- original by Dave Bollinger <[email protected]> posted to lua-l
3
-- modified to use ANSI terminal escape sequences
4
-- modified to use for instead of while
5
6
local write=io.write
7
8
ALIVE="�" DEAD="�"
9
ALIVE="O" DEAD="-"
10
11
function delay() -- NOTE: SYSTEM-DEPENDENT, adjust as necessary
12
for i=1,10000 do end
13
-- local i=os.clock()+1 while(os.clock()<i) do end
14
end
15
16
function ARRAY2D(w,h)
17
local t = {w=w,h=h}
18
for y=1,h do
19
t[y] = {}
20
for x=1,w do
21
t[y][x]=0
22
end
23
end
24
return t
25
end
26
27
_CELLS = {}
28
29
-- give birth to a "shape" within the cell array
30
function _CELLS:spawn(shape,left,top)
31
for y=0,shape.h-1 do
32
for x=0,shape.w-1 do
33
self[top+y][left+x] = shape[y*shape.w+x+1]
34
end
35
end
36
end
37
38
-- run the CA and produce the next generation
39
function _CELLS:evolve(next)
40
local ym1,y,yp1,yi=self.h-1,self.h,1,self.h
41
while yi > 0 do
42
local xm1,x,xp1,xi=self.w-1,self.w,1,self.w
43
while xi > 0 do
44
local sum = self[ym1][xm1] + self[ym1][x] + self[ym1][xp1] +
45
self[y][xm1] + self[y][xp1] +
46
self[yp1][xm1] + self[yp1][x] + self[yp1][xp1]
47
next[y][x] = ((sum==2) and self[y][x]) or ((sum==3) and 1) or 0
48
xm1,x,xp1,xi = x,xp1,xp1+1,xi-1
49
end
50
ym1,y,yp1,yi = y,yp1,yp1+1,yi-1
51
end
52
end
53
54
-- output the array to screen
55
function _CELLS:draw()
56
local out="" -- accumulate to reduce flicker
57
for y=1,self.h do
58
for x=1,self.w do
59
out=out..(((self[y][x]>0) and ALIVE) or DEAD)
60
end
61
out=out.."\n"
62
end
63
write(out)
64
end
65
66
-- constructor
67
function CELLS(w,h)
68
local c = ARRAY2D(w,h)
69
c.spawn = _CELLS.spawn
70
c.evolve = _CELLS.evolve
71
c.draw = _CELLS.draw
72
return c
73
end
74
75
--
76
-- shapes suitable for use with spawn() above
77
--
78
HEART = { 1,0,1,1,0,1,1,1,1; w=3,h=3 }
79
GLIDER = { 0,0,1,1,0,1,0,1,1; w=3,h=3 }
80
EXPLODE = { 0,1,0,1,1,1,1,0,1,0,1,0; w=3,h=4 }
81
FISH = { 0,1,1,1,1,1,0,0,0,1,0,0,0,0,1,1,0,0,1,0; w=5,h=4 }
82
BUTTERFLY = { 1,0,0,0,1,0,1,1,1,0,1,0,0,0,1,1,0,1,0,1,1,0,0,0,1; w=5,h=5 }
83
84
-- the main routine
85
function LIFE(w,h)
86
-- create two arrays
87
local thisgen = CELLS(w,h)
88
local nextgen = CELLS(w,h)
89
90
-- create some life
91
-- about 1000 generations of fun, then a glider steady-state
92
thisgen:spawn(GLIDER,5,4)
93
thisgen:spawn(EXPLODE,25,10)
94
thisgen:spawn(FISH,4,12)
95
96
-- run until break
97
local gen=1
98
write("\027[2J") -- ANSI clear screen
99
while 1 do
100
thisgen:evolve(nextgen)
101
thisgen,nextgen = nextgen,thisgen
102
write("\027[H") -- ANSI home cursor
103
thisgen:draw()
104
write("Life - generation ",gen,"\n")
105
gen=gen+1
106
if gen>2000 then break end
107
--delay() -- no delay
108
end
109
end
110
111
LIFE(40,20)
112
113