

% Program for farmer, wolf, goat, cabbage problem.

% representation state(farmer_loc, wolf_loc, goat_loc, cabbage_loc)

:- dynamic(state/4).

go(Start) :-
   assertz(Start),
   get_goal(Goal),
   write('Start is: '), write(Start), nl,
   write('Goal is:  '), write(Goal), nl,
   write('Continue? '), read(yes), nl,
   path(Start, Goal).

get_goal(state(w,w,w,w)) :-
   state(e,e,e,e).
get_goal(state(e,e,e,e)) :-
   state(w,w,w,w).

opp(e, w).
opp(w, e).

unsafe(state(X,Y,Y,C)) :-
   opp(X,Y).
unsafe(state(X,W,Y,Y)) :-
   opp(X,Y).

% Farmer takes the wolf over
move(state(X,X,G,C), state(Y,Y,G,C)) :-
   opp(X,Y),
   \+ (unsafe(state(Y,Y,G,C))).

% Farmer takes the goat over
move(state(X,W,X,C), state(Y,W,Y,C)) :-
   opp(X,Y),
   \+ (unsafe(state(Y,W,Y,C))).

% Farmer takes the cabbage over
move(state(X,W,G,X), state(Y,W,G,Y)) :-
   opp(X,Y),
   \+ (unsafe(state(Y,W,G,Y))).

% Farmer goes over alone
move(state(X,W,G,C), state(Y,W,G,C)) :-
   opp(X,Y),
   \+ (unsafe(state(Y,W,G,C))).

% Houston, we have a problem
move(State, State) :-
   write('no good, backtrack from '),
   write(State), nl,
   fail.

path(Goal, Goal) :-
   write('The Results Are:'), nl,
   get_all_steps.

path(State, Goal) :-
   move(State, NextState),
   \+ (NextState),
   assertz(NextState),
   path(NextState, Goal), !.

get_all_steps :-
   state(F,W,G,C),
   write(F), write('  '),
   write(W), write('  '),
   write(G), write('  '),
   write(C), nl,
   retract(state(F,W,G,C)),
   fail.

get_all_steps :-
   write('Done'), nl.


