% 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]).

badSpot([X,Y]) :- wall([X,Y]).
badSpot([X,Y]) :- X < 1; Y < 1.
badSpot([X,Y]) :- mazeSize([W, H]), (X > W; Y > H).
%move south
move([CurrX,CurrY],[CurrX,NextY],Direction):- Direction = south,NextY is CurrY + 1.
%move notrh
move([CurrX,CurrY],[CurrX,NextY],Direction):- Direction = north,NextY is CurrY - 1.
%move east
move([CurrX,CurrY],[NextX,CurrY],Direction):- Direction = east,NextX is CurrX + 1.
%move west
move([CurrX,CurrY],[NextX,CurrY],Direction):- Direction = west,NextX is CurrX - 1.

turn(Direction,NewDirection):- Direction = north, NewDirection = west.
turn(Direction,NewDirection):- Direction = west, NewDirection = south.
turn(Direction,NewDirection):- Direction = south, NewDirection = east.
turn(Direction,NewDirection):- Direction = east, NewDirection = north.


% A solution of the maze from our current location is [] if our current location is the end.
solve(CurrentLocation, _, Path,_) :- end(CurrentLocation), Path = [CurrentLocation].

%if it is possible to stay in the same direction move in that direction
solve(CurrentLocation,BeenThere,Path,Direction):- move(CurrentLocation,NextLocation,Direction),\+badSpot(NextLocation),
    \+member(NextLocation,BeenThere),solve(NextLocation,[CurrentLocation|BeenThere],RestOfPath,Direction),Path = [CurrentLocation|RestOfPath].
%If it is not possible to go there turn left and try again
solve(CurrentLocation,BeenThere,Path,Direction):-turn(Direction,NewDirection),solve(CurrentLocation,BeenThere,Path,NewDirection).

% Convenience rule
solve(Path) :- start(Start), solve(Start, [Start], Path,south).