%------------------------------------------------------------------------------
:-compile('MazeController').
%------------------------------------------------------------------------------
maze(FileName,ForwardsPath):-
    controller:read_maze(FileName,Entrance,_Exit),
    controller:draw_maze([]),
    find_path([Entrance],Path),
    reverse_list(Path,[],ForwardsPath),
    write('------------------------------------------------------'),
    nl,
    controller:draw_maze(ForwardsPath),
    controller:exit(ForwardsPath).
%------------------------------------------------------------------------------
find_path([square(_,_,exit)|RestOfPath],[square(_,_,exit)|RestOfPath]):-
    !.
    
find_path(PathSorFar,Path):-
    controller:my_state(CurrentSquare,_),
    controller:sense(N,S,W,E),
    choose_where_to_move(N,S,W,E,MoveToHere),
    make_move(MoveToHere),
    onbacktrack(make_move(CurrentSquare)),
    find_path([MoveToHere|PathSorFar],Path),
    !.
%------------------------------------------------------------------------------
choose_where_to_move(N,S,W,E,square(X,Y,Status)):-
    member(square(X,Y,Status),[N,S,W,E]),
    member(Status,[exit,unknown]).
%------------------------------------------------------------------------------
make_move(ToSquare):-
    controller:move(ToSquare).
%DEBUG show_move.
%------------------------------------------------------------------------------
show_move:-
    write('------------------------------------------------------'),
    nl,
    controller:draw_maze([]),
    controller:my_state(_,MovesMade),
    write(MovesMade),
    write(' moves made'),
    nl.
%------------------------------------------------------------------------------
onbacktrack(_).

onbacktrack(Goal):-
    Goal,
    fail.
%------------------------------------------------------------------------------
reverse_list([],List,List).

reverse_list([H|T],ReversedSoFar,Reversed):-
    reverse_list(T,[H|ReversedSoFar],Reversed).
%------------------------------------------------------------------------------
