PROGRAM TICTACTOE (Input,Output);

CONST
   Blank = ' ';

TYPE
   BoardType = ARRAY[1..3,1..3] OF Char;

VAR
   Board : BoardType;



(*****************************************************************)
PROCEDURE InitBoard (Var Board : BoardType);

Var
   I, J : Integer;
Begin
   FOR I := 1 TO 3 DO
      FOR J := 1 TO 3 DO
         Board[I,J] := Blank;
End;




(******************************************************************)
PROCEDURE DisplayBoard (Board : BoardType);

Var
   I, J : Integer;

Begin
   Writeln('-----------');
   Writeln('| ',Board[1,1],'  ',Board[1,2],'  ',Board[1,3],' |');
   Writeln('| ',Board[2,1],'  ',Board[2,2],'  ',Board[2,3],' |');
   Writeln('| ',Board[3,1],'  ',Board[3,2],'  ',Board[3,3],' |');
   Writeln('-----------');
End;




(****************************************************************)
PROCEDURE MakeMove (Turn : Char; Var Board : BoardType);

Var
   Row, Column : Integer;

Begin
   Write(Turn,' to make a move: ');
   Readln(Row,Column);

   WHILE Board[Row,Column] <> Blank DO
     Begin
      Writeln(Row:2,Column:2,' Already occupied.  Again please.');
      Write(Turn,' to make a move again: ');
      Readln(Row,Column);
     End;

   Board[Row,Column] := Turn;
End;




(******************************************************************)
FUNCTION Winner (B : BoardType;  Mark : Char) : Boolean;

Begin
   IF ((B[1,1]=Mark) AND (B[1,2]=MArk) AND (B[1,3]=Mark)) OR
      ((B[2,1]=Mark) AND (B[2,2]=MArk) AND (B[2,3]=Mark)) OR
      ((B[3,1]=Mark) AND (B[3,2]=MArk) AND (B[3,3]=Mark)) OR
      ((B[1,1]=Mark) AND (B[2,1]=MArk) AND (B[3,1]=Mark)) OR
      ((B[1,2]=Mark) AND (B[2,2]=MArk) AND (B[3,2]=Mark)) OR
      ((B[1,3]=Mark) AND (B[2,3]=MArk) AND (B[3,3]=Mark)) OR
      ((B[1,1]=Mark) AND (B[2,2]=MArk) AND (B[3,3]=Mark)) OR
      ((B[3,1]=Mark) AND (B[2,2]=MArk) AND (B[1,3]=Mark)) THEN
         Winner := True
   ELSE
      Winner := False;
End;




(*****************************************************************)
PROCEDURE PlayGame (Board : BoardType);

Var
   Turn : Char;
   Plays : Integer;

Begin
   Plays := 0;
   Turn := 'X';
   REPEAT
      IF Turn = 'O' THEN    (* Other player's turn *)
         Turn := 'X'
      ELSE
         Turn := 'O';
      MakeMove(Turn,Board);
      DisplayBoard(Board);
      Plays := Plays + 1;
   UNTIL Winner(Board,Turn) OR (Plays = 9);

   IF Winner(Board,Turn) THEN
      Writeln(Turn,' wins!!!!!!')
   ELSE
      Writeln('No one wins.')
End;




(**************************************************************)
FUNCTION Continue : Boolean;

Var
   Ch : Char;

Begin
   Writeln;
   Write('Another game? (Y or N) ');
   Readln(Ch);
   IF (Ch='Y') OR (Ch='y') THEN
      Continue := True
   ELSE
      Continue := False;
End;




BEGIN
   Randomize;

   REPEAT
      Writeln;
      Writeln('O starts');
      InitBoard(Board);
      PlayGame(Board);
   UNTIL NOT Continue;
END.
