
uses
  SysUtils, Classes, ChessGame, ChessTypes, PgnWrite;

const
  CMaxMoveNumber = 300;
  //CStartPosition = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
  CStartPosition = 'rn1qk2r/5ppp/2p2n2/p1bPp3/Pp4b1/1B4Q1/NPPPNPPP/R1B1K2R b HAha - 2 10';
  CChess960 = TRUE;
  
var
  LStop: boolean;
  LMove, LSanMove: string;
  LMoveCount: integer;
  LTime: TTime;
  LPgnData: TStringList;
  
begin
  Randomize;
  LTime := Time;
  LPgnData := TStringList.Create;
  
  with TChessGame.Create(CStartPosition) do
  try
    LPgnData.Append('?'); // White name
    LPgnData.Append('?'); // Black name
    LPgnData.Append(CStartPosition);
    LStop := FALSE;
    LMoveCount := 0;
    repeat
      Write(GetFen(CChess960), ', ');
      
      LMove := RandomMove;
      if LMove = EmptyStr then
      begin
        WriteLn('No legal move available. Exit.');
        LStop := TRUE;
      end else
        if IsLegal(LMove) then
        begin
          LSanMove := GetSan(LMove);
          DoMove(LMove);
          Inc(LMoveCount);
          
          if Check then
            if State = gsCheckmate then
              LSanMove := LSanMove + '#'
            else
              LSanMove := LSanMove + '+';
          { There are no special markings used for drawing moves. }
          
          LPgnData.Append(LSanMove);
          
          WriteLn(LMove, ', ', LSanMove);

          if State = gsProgress then
          begin
            if LMoveCount = CMaxMoveNumber then
            begin
              WriteLn(CMaxMoveNumber, ' moves. Exit.');
              LPgnData.Append('*');
              LStop := TRUE;
            end;
          end else
          begin
            WriteLn('Game over (State=', State,'). Exit.');
            case State of
              gsCheckmate: if ActiveColor = pcBlack then LPgnData.Append('1-0') else LPgnData.Append('0-1');
              gsStalemate, gsDraw: LPgnData.Append('1/2-1/2');
            end;
            LStop := TRUE;
          end;
        end else
        begin
          WriteLn('Illegal move (', LMove, '). Exit.');
          LStop := TRUE;
        end;
    until LStop;
    WriteLn;
    WriteLn(CurrPosToStr);
  finally
    Free;
  end;
  WriteLn('Time elapsed ', FormatDateTime('s,zzz "s"', Time - LTime));
  WritePgnFile('chessgamedemo.pgn', LPgnData, CChess960);
  LPgnData.Free;
end.
