
% The starting tree
init(root - tree(mouse - X, 'Does it have fur?', lizard - Y)).

% The main program loop
go:-
  init(T), 
  loop('yes', T).

loop('no', _).
loop('yes', T):-
  identify(T), 
  nl, write('Play again? '), 
  read(Ans), nl, 
  loop(Ans, T).

% When the end of a branch is reached, try to guess the animal
identify(Animal - X):-
  var(X), 
  nl, write('Is it a '), write(Animal), write('? '), 
  read(Ans), nl, 
  process(Ans, Animal, X).
% Walk the tree asking about the attributes of the animal
identify(_ - tree(YES, Q, NO)):-
  nl, write(Q), tab(1), read(Ans), nl, 
  (Ans = 'yes', identify(YES); identify(NO)).

% Do nothing if the guess is correct
process('yes', _, _).
% Add a new subtree if the guess is wrong
process('no', Animal, X):-
  nl, write('What animal were you thinking of? '), 
  nl, read(Ans), nl, nl, 
  write('What is a yes/no question that distinguishes them?'), nl, 
  read(Q), nl, 
  nl, write('For a '), write(Ans), write(' the answer is: '), 
  read(YN), nl, 
  (YN = 'yes', X = tree(Ans-Y, Q, Animal-Z);
               X = tree(Animal-Y, Q, Ans-Z)).
