% Prolog Challenge 2 Part 2 - Kaitlyn Jesmonth
%	Improving heuristic by prefering a movement which results in the direction of the end of the maze.

% Row 1
wall([X,1]) :- X =\= 2.
% Row 2
wall([X,2]) :- X = 1; X = 4; X = 6.
% Row 3
wall([X,3]) :- X = 1; X = 2; X = 6.
% Row 4
wall([X,4]) :- X =\= 3,X =\= 5.
% Row 5
wall([X,5]) :- X = 1; X = 4; X = 6.
% Row 6
wall([X,6]) :- X =\= 2.
% Start / end
start([2,1]).
end([2,6]).
% Maze Size
mazeSize([6,6]).
% Direction
dir(up).
dir(down).
dir(left).
dir(right).

% Position compared to the end
leftSpot([X,Y]) :- X < 2; X == 2.
rightSpot([X,Y]) :- X > 2.

badSpot([X,Y]) :- wall([X,Y]).
badSpot([X,Y]) :- X < 1; Y < 1.
badSpot([X,Y]) :- mazeSize([W, H]), (X > W; Y > H).

%up
move([CurrX, CurrY], [CurrX, NextY], up) :- NextY is CurrY - 1.
%down
move([CurrX, CurrY], [NextX, NextY], down) :- NextY is CurrY + 1, NextX = CurrX.
%left
move([CurrX, CurrY], [NextX, NextY], left) :- NextY = CurrY, NextX is CurrX - 1.
%right
move([CurrX, CurrY], [NextX, NextY], right) :- NextY = CurrY, NextX is CurrX + 1.

% select direction to move
select(CurrentLocation, NewLocation, A, _, _, _, A) :- move(CurrentLocation, NewLocation, A),
	\+badSpot(NewLocation).
select(CurrentLocation, NewLocation, _, B, _, _, B) :- move(CurrentLocation, NewLocation, B),
	\+badSpot(NewLocation).

% A solution of the maze from our current location is [] if our current location is the end.
solve(CurrentLocation, _, Path) :- end(CurrentLocation), Path = [CurrentLocation].
		
% Convenience rule
solve(Path) :- start(Start), solve(Start, [Start], Path).


% solve based on position compared to the end
solve(CurrentLocation, _, Path) :- rightSpot(CurrentLocation), select(CurrentLocation, NewLocation, down, left, up, right, Dir), solve(NewLocation, _, NewPath), Path = [CurrentLocation | NewPath].
solve(CurrentLocation, _, Path) :- leftSpot(CurrentLocation), select(CurrentLocation, NewLocation, down, right, up, left, Dir), solve(NewLocation, _, NewPath), Path = [CurrentLocation | NewPath].