% Author: Layla S. Mayboudi
% 2021-05-27
% This codes checks if the random walk is within the limits identified by
% the code testPropLimits.

% Note: 
% The code uses the function testPropLimits.m.

% The script displays a visual representation of a random walk.
% Script terminates when a boundary wall is hit or the maximum number 
% of steps is reached.


clear; clc; close all;
box_size = 100; %size of the square walk enclosure box in X and Y
steps_lim = 20;  %max number of steps allowed
textOffsetX = 3; %offset in X of step number label from the step point 
curr_step=[0 0]; 
% initialize walk coordinates; walk starts at origin
walk_point =zeros(steps_lim+1,2);
X=1;Y=2; % define indices for X and Y components
% Ask user for step size limit
max_step_size = testPropLimits('maximum step size','units',box_size*0.05,box_size);
% create figure to display random walk
figure(1);
plot_limit = 1.2*(box_size/2);
ylim([-plot_limit plot_limit]); xlim([-plot_limit plot_limit]);
plot((box_size/2)*[-1,1,1,-1,-1],(box_size/2)*[1,1,-1,-1,1],'Color','r','LineWidth',3)
grid on
axis padded equal
title('Random Walk Plot'); xlabel('X'); ylabel('Y');
lineID = animatedline('LineStyle',':','Color',[0.5 0.5 0.5],'LineWidth',1,'Marker','o',...
'MarkerSize',5,'MarkerEdgeColor','k','MarkerFaceColor',[0.5,0.5,0.5]);
% Initialize while loop variables
i=1; hitWall = false; iterLim = false;
while not(hitWall)&& not(iterLim)
    addpoints(lineID,walk_point(i,X),walk_point(i,Y));
    drawnow
    text(walk_point(i,X)+textOffsetX,walk_point(i,Y),num2str(i-1));
    curr_step(X)=randi([-max_step_size max_step_size]); % step X coordinate
    curr_step(Y)=randi([-max_step_size max_step_size]); % step Y coordinate
    next_point=walk_point(i,:)+curr_step;
    if any(abs(next_point)>= box_size/2)
        hitWall = true;
        hold on; plot(next_point(X),next_point(Y),'xr','MarkerSize',8);hold off
        text(next_point(X)+textOffsetX,next_point(Y),num2str(i));
    elseif (i-1 == steps_lim)
        iterLim = true;
    else
        i = i + 1;
        walk_point(i,:)=next_point;
    end
end

if hitWall 
    disp(['Hit the wall at step ', num2str(i),'.']);
    fprintf('Invalid position is (%d,%d). \n',next_point)
end
if iterLim 
    disp(['Reached the iteration limit of ', num2str(steps_lim),'.']);
end
fprintf('Final valid position is (%d,%d). \n',walk_point(i,:))   