% treasureHunt:  Move across an island from (1,1) to (15,15).
% This script implements your treasure hunt.

% GLOBAL makes map, current coordinates, and history of moves accessible
% to all specified files
global map xCoordinate yCoordinate xMoves yMoves direction lifelines

% Start from (1, 1)
xCoordinate= 1;
yCoordinate= 1;

% Clear map and set history of x and y moves to initial position
map= [];
close all;
xMoves= xCoordinate;
yMoves= yCoordinate;

% Start with 3 lifelines
lifelines= 3;

% You start by facing North
% n = north, s = south, e = east, w = west
direction= 'n';

% Calls the function loadMap, which loads the treasure map1
% change this function name to loadMap2 to load the 2nd map
loadMap3();

% ----------------------------------------------------------------------
% Intelligent decision making logic
% YOUR CODE GOES BELOW

while (lifelines >0 && ((xCoordinate ~= 15) || (yCoordinate ~= 15)))
    
    % Left-hand-obstacble-following algorithm: always keep left hand on obstacle 
    if (~obstacleOnLeft())  % Space on the left, so turn left to keep 
                            % following the LHS obstacle
        turnLeft();
        moveForward();
    else  % LHS is an obstacle
        if (~obstacleInFront())
            moveForward();
        else  % obstacle in front and on LHS
            turnRight();
        end
    end
end

  

  
  
% YOUR CODE GOES ABOVE
% ----------------------------------------------------------------------

% Display treasure map
drawMap;

% Display moves
numMoves= size(xMoves, 2);
for index= 1:numMoves
    
    % get move coordinate
    x= xMoves(index);
    y= yMoves(index);
    
    if (x<1 || x>15 || y<1 || y>15)  % in water!
        error('...Drowning...')
    elseif (map(x,y)==0)  % going through mountain!
        error('...Cannot walk through a mountain...')
    else  % make a step in the maze
        % draw red box to identify you on map, pause, and then delete
        fill ([x+0.2 x+0.2 x+0.8 x+0.8 x+0.2], ...
              [y+0.2 y+0.8 y+0.8 y+0.2 y+0.2], 'r'), hold on;
        pause(1);
        fill ([x x x+1 x+1 x], [y y+1 y+1 y y], 'g'), hold on;
    end

end
    
fill ([x+0.2 x+0.2 x+0.8 x+0.8 x+0.2], ...
      [y+0.2 y+0.8 y+0.8 y+0.2 y+0.2], 'r'), hold on;
  
% Display the number of lifelines you have
fprintf('You have %d lifelines remaining\n',lifelines);