Problems with cellular automata

So I was reading this artcle on what the author calls “History Dependent Cellular Automata” which I found interesting and wanted to replicate in Roblox.
The gist is you generate each layer, stacking them on top of each other. However, each cell on each layer not only checks for its immediate neighbours but also the neighbours of the previous layer where the cell would be located, as well as the previous cell sitting right below the current cell. Giving a possibility of 17 neighbours to determine whether this current cell will be dead (invisible) or alive (black block).

local function Start()
	for i=1, StacksAmount do
		SetUp()
		for i=1, StepAmount do
			DoSimStep(Grid) -- CountNeighbours method is called
		end
		ShowGrid(i)
		GridPrev = Grid -- Save the grid to GridPrev
	end
end

function module:CountNeighbours(Grid, SizeX, SizeY, GridPrev)
	local neighbours = 0
	
	for x=-1, 1 do
		for y=-1, 1 do
			if self.x + x < 1 or self.x + x > SizeX or self.y + y < 1 or self.y + y > SizeY then
				neighbours += 1
			else
				local neighbour = Grid[self.x + x][self.y + y]
				if neighbour.Alive == true or neighbour == nil then
					neighbours += 1
				end

				if #GridPrev > 0 then	-- get neighbours from previous grid
					local neighbour = GridPrev[self.x + x][self.y + y]
					if neighbour.Alive == true or neighbour == nil then
						neighbours += 1
					end
				end
			end
		end
	end
	
	return neighbours
end

However, when printing out the total neighbours, I’m getting cells which supposedly have 18 live neighbours cells.
This should be impossible as the max is 17, so obviously there must be a problem with my code.
Not to mention that every layer after the first layer is just completely full of live cells.


Dead cells are invisible, hence the gaps in the working first layer and no gaps in the second layer.

Sorry, don’t have time to examine your code in detail.

But here’s an idea: did you remember to not count the cell itself when counting neighbors? E.g.

for x=-1, 1 do
    for y=-1, 1 do
        --Skip the cell itself
        if x == 0 and y == 0 then continue end
1 Like
if self.x + x < 1 or self.x + x > SizeX or self.y + y < 1 or self.y + y > SizeY then

This line already ensures I’m only counting the current layers neighbouring cells. Besides, I know that the code works, it’s just when I introduced the checking of neighbours from the previous layer is where it screws up.

Self bump