% dog catching mailman problem
% discrete time event simulation
% cda 6530 
% project 5
% PID: j2966213
% name: Jun Ye


iter = 100;

maxIter = 500;% maximum iteration
timeStep = 0.2;% time step

finalCatchTime = 0;
finalCatchPos=0;

halfCatchDog_x=0;
halfCatchDog_y=0;

halfCatchMan_x = 0;

while iter>0
    
    %type 1 mailman
    dog_x = zeros(maxIter);
    dog_y = 20*ones(maxIter);
    mailman_x = 10* ones(maxIter);
    mailman_y = zeros(maxIter);% it is constant, actually not useful
    %type 2 dog and type 1 mailman
    %main loop

    stepCnt = 0;
    tRun = timeStep;
    for i=2:maxIter
        stepCnt = stepCnt+1;
        curTime = timeStep*(i-1); % current time
        slip = DogSlip(tRun);
        if slip == 1 % slip happens
            dog_speed = 0;
            tRun = 0;
        else         % slip does not happen
            if tRun < 4
                dog_speed = 3*tRun;
            else
                dog_speed = 12;
            end
            % tRun increases
            tRun = tRun+ timeStep;
        end


            mailman_speed = 2.5; % stand still to tie shoe lance



        % type 1 mailman
        distance = sqrt((abs(dog_x(i-1) - mailman_x(i-1)))^2 +(dog_y(i-1))^2);
        delta_dog_x = dog_speed*(mailman_x(i-1)-dog_x(i-1))/distance*timeStep;
        delta_dog_y = dog_speed*dog_y(i-1)/distance*timeStep;
        delta_mailman_x = mailman_speed*timeStep;

        %update the new position after the iteration
        dog_x(i) = dog_x(i-1) + delta_dog_x;
        dog_y(i) = dog_y(i-1) - delta_dog_y;

        if dog_y(i) < 0  % cross the x-axis
            dog_y(i) = 0;
            dog_x(i) = mailman_x(i-1);
        end
        mailman_x(i) = mailman_x(i-1) + delta_mailman_x;

        if (dog_y(i) == 0) && (dog_x(i)>= mailman_x(i))
            dog_x(i) = mailman_x(i);
            break;
        end

    end
    finalCatchTime = finalCatchTime + stepCnt*timeStep;
    finalCatchPos = finalCatchPos + dog_x(stepCnt+1);
    
    mid=(stepCnt+1)/2;
    if mid - floor(mid) < 0.00001  
        
        halfCatchDog_x = halfCatchDog_x +dog_x(floor(mid));
        halfCatchDog_y = halfCatchDog_y +dog_y(floor(mid));
        halfCatchMan_x = halfCatchMan_x +mailman_x(floor(mid));
    else
        halfCatchDog_x = halfCatchDog_x +(dog_x(floor(mid))+dog_x(ceil(mid)))/2;
        halfCatchDog_y = halfCatchDog_y +(dog_y(floor(mid))+dog_y(ceil(mid)))/2;
        halfCatchMan_x = halfCatchMan_x +(mailman_x(floor(mid))+mailman_x(ceil(mid)))/2;     
    end
    iter = iter - 1;
end 
finalCatchTime = finalCatchTime/100;
finalCatchPos = finalCatchPos/100;
halfCatchDog_x = halfCatchDog_x/100;
halfCatchDog_y = halfCatchDog_y/100;
halfCatchMan_x = halfCatchMan_x/100;

