Yet another WRAPPED implementation of game of live.
See a live demo here;
-
Define a
pattern
as:var pat = { data: "bo$2bo$3o!", rule: "23/3" };
The
data
field is Run Length Encoded (RLE) (see lifewiki:rle). Therule
field is the evolution rule, in the format ofS/B
, whereS
stands for stays alive andB
for born (see lifewiki:rule). The above is a small glider using Conway's life rule. -
Define a canvas size:
var param = { width: 32, height: 16, startx: 3, starty: 3 };
Since this is a wrapped implementation, i.e. the right-most column is adjacent to the left-most one, first row to the last row, we need to know the size (
width
andheight
field) of the entire canvas where the automaton evolves. And also the upper-left position to put the initial pattern (startx
andstarty
field). -
Initialize the
life
as:var gol = life.wrapped(); var next = gol.reset(pat, param);
The
.reset
method returns the same structure as.next
where theborn
field contains all the living cells in the initial pattern, see below. -
Get the next generation:
next = gol.next();
The
next
is in the format:{ dead: [[x0, y0], [x1, y1], ...], born: [[c0, r0], [c1, r1], ...] }
The
dead
array contains all the cells that are DEAD in this generation. And theborn
array contains all the cells that are BORN in this generation;
-
life.wrapped()
Create a
life
object. -
.reset(pat, param)
Set the initial pattern for evolution. Returns the same structure as
.next
. -
.next()
Get the next generation. See the above How to use section for more on the returned values.
This implementation used the concept of ghost cell, the cells that are 1) not live, 2) adjacent to a live cell. Only the ghost cells might be born the next generation.
I maintain an array of live cells and an array of ghost cells for each generation. With the help of ghost cells, I don't need to scan the whole canvas.