%% DEFINES
% constants
width     = 256*8;
height    = 128*8;
start     = [32*8, 64*8];
speed     = 10*8;
play_time = 30;
show      = true;
gif       = true;

% playable area
area                     = false(height, width);
area(start(2), start(1)) = true;

% walls
walls                                                   = true(height, width);
walls(64*8:(64+32)*8, 16*8:width-16*8)                  = false; % long strip
walls((64-8)*8:(64+32+8)*8, 16*8:(16+48)*8)             = false; % starting area
walls((64-8)*8:(64+32+8)*8, width-(16+48)*8:width-16*8) = false; % ending area
walls((64-16)*8:64*8, width/2-8*8:width/2+8*8)          = false; % divit

% obstacle
obstacle                                                = false(height, width);
obstacle(64*8:(64+32)*8, (16+48)*8+1:width-(16+48)*8+1) = true;

% movement kernel
%[x,y]    = meshgrid(1:speed*2+1, 1:speed*2+1);
%movement = (x - (speed+1)).^2 + (y - (speed+1)).^2 <= (speed+0.25)^2;
movement = fspecial('gaussian', [1, speed*2+1]', 10);


%% PLAY
% loop until finished
tic
for i=1:play_time
    
    % move
    %area = imdilate(area, movement, 'same');
    %area = conv2(single(area), single(movement), 'same') > 0;
    areaY = conv2(single(area), movement, 'same')';
    area = conv2(areaY, movement, 'same')' > 1e-16;
    
    % mask walls
    area = area & ~walls;
    
    % mask obstacle
    obs = false(height, width);
    if mod(i, 7) == 0
        area = area & ~obstacle;
        obs = obstacle;
    end
    
    % setup output image
    output         = zeros(height, width, 'uint8');
    output(~walls) = 170;
    output(area)   = 255;
    output(obs)    = 80;
    
    % show current image
    if show
        imshow(output);
        pause(0.1);
    end
    
    % write to gif
    if i == 1 && gif
        imwrite(output,'Bound2.gif','gif','Loopcount',inf,'DelayTime',0.2);
    elseif gif
        imwrite(output,'Bound2.gif','gif','Writemode','append','DelayTime',0.2);
    end
    
    % finished
    if sum(sum(area((64-8)*8:(64+32+8)*8, width-(16+48)*8:width-16*8))) == ...
            numel(area((64-8)*8:(64+32+8)*8, width-(16+48)*8:width-16*8))
        break
    end
    
end
fprintf('Finished in %d loops in %f seconds\n', i, toc)