nParticles = 10000;
maxX = 50;
maxY = 50;
nNewParticlesPerFrame = 10;

A = zeros(maxX, maxY);
B = rand(maxX, maxY);

A(:,maxY) = 1;

yBuffer = 5;
yStart = maxY-yBuffer;
f = 0;
for i = 1:nParticles
    x  = 1+floor(maxX*rand);
    y  = yStart;
    
    while 1
        xOld = x; %store current x and y values
        yOld = y;
        
        r = rand();
        if r <= .1
            x = x-1; %% Move LEFT
        elseif r <= .2
            x = x+1; %% Move RIGHT
        else
            y = y+1; %% Move UP
        end
        
        if x < 1
            x = maxX;
        end
        if x > maxX
            x = 1;
        end
        
        
        if (y < yStart)
            y = yStart;
        end
        
        if (A(x,y)>0)
            x=xOld;
            y=yOld;
            continue;
        end
        
        xR = x+1;
        xL = x-1;
        yU = y+1;
        yD = y-1;
        
        if xL < 1
            xL = maxX;
        end
        if xR > maxX
            xR = 1;
        end
        
        
        if (A(xR,y) > 0 | A(xL,y) > 0 | A(x,yU) > 0 | A(x,yD) > 0)
            A(x,y) = 1;
            if (y-yBuffer<yStart && y-yBuffer>0)
                yStart = y-yBuffer;
            end
            break;
            
        end
    end
    
    for i = 1:maxX
        for j = 1:maxY
            if i < maxX/2
                A(i,j) = A(i,j)*B(i,j);
            else
            end
            
        end
        
    end
    
    
    if (i==nParticles | mod(i,nNewParticlesPerFrame)==0 | yStart-1==0)
        imagesc(A');
        set(gca,'YDir','normal');
        colormap(hot);
        axis equal;
        axis tight;
        drawnow
        
    end
    if (yStart-1==0)
        break;
    end
end
