I have worked for a few days in my cellular automata path algorithm and an easy fill algorithm, but sometimes I get some weird fall in my FPS.
function createGrid()
{
// Create Grid
for(var y = 0; y < yTotal; y++)
{
grid[y] = [];
for(var x = 0; x < xTotal; x++)
{
grid[y][x] = RandomRange(0, 1);
}
}
// 6 loops, why? just to make the path more straight
for(var i = 0; i < 6; i++)
{
for(var y = 0; y < yTotal; y++)
{
for(var x = 0; x < xTotal; x++)
{
var total = 0;
// All neighbour values added to the current one
for(var h = -1; h <= 1; h++)
{
for(var w = -1; w <= 1; w++)
{
var yw = Math.max(0, Math.min(xTotal - 1, y + h)),
xw = Math.max(0, Math.min(yTotal - 1, x + w));
total += grid[yw][xw];
}
}
// Make current to wall or air
grid[y][x] = Math.round(total / 3) & 1;
}
}
}
// If current Cell has value of 0, it will be air elsed wall
for(var y = 0; y < yTotal; y++)
{
for(var x = 0; x < xTotal; x++)
{
grid[y][x] = grid[y][x] == 0 ? new Air("white") : new Wall("black");
}
}
}
Draw and fill algorithm:
setInterval(function(){
ctx.clearRect(0, 0, wCanvas, hCanvas);
for(var y = 0; y < yTotal; y++)
{
for(var x = 0; x < xTotal; x++)
{
var celd = grid[y][x];
// Fill Algorithm
if(celd instanceof Fill)
{
// Just to make a delay
if(celd.TotalCooldown-- === 0)
{
var xLeft = Math.max(0 , x - 1),
xRight = Math.min(xTotal - 1 , x + 1),
yTop = Math.max(0 , y - 1),
yBottom = Math.min(yTotal - 1 , y + 1);
if(grid[y][xRight] instanceof Air) grid[y][xRight] = new Fill("red");
if(grid[y][xLeft] instanceof Air) grid[y][xLeft] = new Fill("red");
if(grid[yBottom][x] instanceof Air) grid[yBottom][x] = new Fill("red");
if(grid[yTop][x] instanceof Air) grid[yTop][x] = new Fill("red");
}
}
// Draw Map
ctx.beginPath();
ctx.fillStyle = celd.Color;
ctx.rect(x * celdSize, y * celdSize, celdSize, celdSize);
ctx.fill();
ctx.closePath();
}
}
}, 1000 / 60);