{ 05_play_unplay.pas -- playing and retracting moves, and game
  history. Pascal translation of ../examples/05_play_unplay.c.

  Functions demonstrated:
    SANPlayMove()   -- play a legal move (updates board, history,
                       hash, active color, move counters...)
    SANUnplayMove() -- undo the most recently played move
    hn              -- global count of moves currently on the
                       history stack (sankit.pas) }

program play_unplay;

uses
  SanKit;

procedure PascalToSanBuf(const s: string; var buf: TSanBuf);
var
  i, n: Integer;
begin
  FillChar(buf, SizeOf(buf), 0);
  n := Length(s);
  if n > sanL - 1 then
    n := sanL - 1;
  for i := 1 to n do
    buf[i - 1] := s[i];
end;

procedure Play(const text: string);
var
  buf: TSanBuf;
  mptr: PMove;
begin
  PascalToSanBuf(text, buf);
  mptr := SANDecodeAux(SanBufPtr(buf));
  if mptr = nil then
    begin
      WriteLn(ErrOutput, 'not a legal move: ', text);
      Halt(1);
    end;
  SANPlayMove(mptr);
end;

begin
  SANInit;
  optnv[optn_nabd] := 1;
  optnv[optn_namd] := 1;

  WriteLn('moves on history stack: ', hn);

  Play('e4');
  Play('e5');
  Play('Nf3');
  WriteLn('after 1.e4 e5 2.Nf3   : ', SANFENGen, '  (history: ', hn, ')');

  SANUnplayMove;
  WriteLn('after retracting 2.Nf3: ', SANFENGen, '  (history: ', hn, ')');

  SANUnplayMove;
  SANUnplayMove;
  WriteLn('after retracting all  : ', SANFENGen, '  (history: ', hn, ')');
end.
