program chessboard;

//---------------------- LIBRARES ----------------------------------------------

uses crt, graph, sysutils;

//---------------------- TYPES       -------------------------------------------

type TChessman = array[0..56] of byte;

//---------------------- CONSTANS    -------------------------------------------
  
const
{$i pieces.inc}
  
//---------------------- GLOBAL VARIABLES --------------------------------------

var
  bmpAdr, tmpBmpAdr     : word;
  color                 : byte;
  start, stop, total    : cardinal; // mesure rutine time

//---------------------- PROCEDURES --------------------------------------------


procedure renderChessman(chessman: word; x, y, invert: byte);
var i0b                 : byte;
begin
  tmpBmpAdr := bmpAdr + 1 + (x * 3) + (y * 760) + 40;
  for i0b := 0 to 18 do begin
    poke(tmpBmpAdr, peek(chessman) xor invert);
    Inc(chessman);
    poke(tmpBmpAdr + 1, peek(chessman) xor invert);
    Inc(chessman);
    poke(tmpBmpAdr + 2, peek(chessman) xor invert);
    Inc(chessman);
    Inc(tmpBmpAdr, 40);
  end; 
end;

procedure drawRectangle;
var i0b                 : byte;
    y                   : word ;
begin
  y := 0;
  tmpBmpAdr := bmpAdr + 25;
  for i0b := 0 to 153 do begin
    poke(bmpAdr + y, %00000001);
    poke(tmpBmpAdr + y, %10000000);
    Inc(y, 40);
  end;
  tmpBmpAdr := bmpAdr + 6120; // 19*8*40 + 40
  for i0b := 1 to 24 do begin
    poke(bmpAdr + i0b, $ff);
    poke(tmpBmpAdr + i0b, $ff);
  end;  
end;

procedure drawBoard;
var i0b, i1b            : byte;
    invert, chessman    : byte;
begin
  drawRectangle;
  chessman := 1;
  for i1b := 0 to 7 do begin  
    for i0b := 0 to 7 do begin
      if (odd(i0b + i1b)) then invert := 0 else invert := $ff;
      if ((i1b > 1) and (i1b < 6)) then begin 
        renderChessman(CHESSBOARD[0], i0b, i1b, not invert);
      end else begin
        renderChessman(CHESSBOARD[chessman], i0b, i1b, invert);
        Inc(chessman);      
      end;
    end;
  end; 
end;

//---------------------- MAIN PROGRAM ------------------------------------------

begin
  // There are 192 rows of 320 dots in the full screen mode.
  InitGraph(8);
  bmpAdr := dpeek(88);
  
  SetColor(1);
  // colors: 2, 4, 80, 82, 96, 98, 112, 130, 132, 144, 146, 148, 150
  color := 2;
  SetBKColor(color);
  TextBackground(color);
  
  start := GetTickCount;
  drawBoard;
  stop := GetTickCount;
  writeln('drawing time: ', stop - start);
  
  ReadKey;
end.
