/*---------------------------------------------------------------------------- The game of Peggly. Parke Godfrey, 2004 Works in SWI-Prolog. Installed on YORK CSE machines. Run by the command 'pl'. ----------------------------------------------------------------------------*/ % Here are the legal moves. move(C, N) :- C >= 1, N is C - 1. move(C, N) :- C >= 2, N is C - 2. move(C, N) :- C >= 3, N is C - 3. :- dynamic won/1, lost/1. % Check for cached proofs first. win(C) :- won(C), !. win(C) :- lost(C), !, fail. % See whether you win. Cache if you do. win(C) :- move(C, N), \+ win(N), !, record(won(C)). win(0) :- !. % Otherwise, cache that you lost. win(C) :- !, record(lost(C)), fail. record(A) :- \+ A, assert(A). /*---------------------------------------------------------------------------- EXPLAIN ----------------------------------------------------------------------------*/ :- dynamic explained/1. explain(C) :- win(C), fail. explain(C) :- explainer(C, ''), !, retractall(explained(_)). explainer(C, I) :- won(C), explained(C), !, write(I), write('state('), write(C), write(') has been shown to win.'), nl. explainer(C, I) :- lost(C), explained(C), !, write(I), write('state('), write(C), write(') has been shown to lose.'), nl. explainer(C, I) :- won(C), !, record(explained(C)), write(I), write('state('), write(C), write(') wins because '), move(C, N), lost(N), !, write('state('), write(N), write(') loses.'), nl, explainer(N, I). explainer(C, I) :- lost(C), !, record(explained(C)), write(I), write('state('), write(C), write(') loses because'), nl, concat(I, ' ', J), explain_all(C, J). explain_all(C, I) :- move(C, N), won(N), write(I), write('state('), write(N), write(') wins'), nl, explainer(N, I), write(I), write('AND'), nl, fail. explain_all(_, I) :- write(I), write('that is all.'), nl.