{ High score unit }

unit Hiscore;

interface

const
  { Max names }
  CMaxScores = 10;
  { Default score file }
  CHiScoreFile = 'NIBBLES.HIS';

type
  TPlayer = record
              Name: string[15];
              score: longint;
            end;

  { The first player is in index 1 and so on... }
  THiScoreTable = array[1..CMaxScores] of TPlayer;

  { Returned number is a player position in Hiscore table, or 0 if }
  { player score is so small.                                      }
  function CheckScore(var Table: THiScoreTable; AScore: longint): byte;
  { Update Hiscore table by player data to index <> 0, no hiscore check !!! }
  procedure UpDateScore(var Table: THiScoreTable; index: byte;
                        PlayerName: string; AScore: longint);
  { Load hiscore table from file }
  procedure LoadScore(var Table: THiScoreTable);
  { Save hiscore table to file }
  procedure SaveScore(var Table: THiScoreTable);

implementation


function CheckScore;
var
  i: byte;
begin
  i := 0;

  If AScore >= Table[CMaxScores].score then
  begin
    repeat
      Inc(i);
    until AScore >= Table[i].score;
    CheckScore := i;
  end else
    CheckScore := 0;
end;

procedure UpDateScore;
var
  i: byte;
begin
  If index <> 0 then
  begin
    For i := CMaxScores - 1 downto index do
      Table[i + 1] := Table[i];
    Table[index].name := PlayerName;
    Table[index].score := AScore;
  end;
end;

procedure LoadScore;
var
  i: longint;
  f: file of THiScoreTable;
  OldMode: byte;

begin
  { Read only }
  OldMode := FileMode;
  FileMode := 0;

  Assign(f, CHiScoreFile);
{$I-}
  Reset(f);
{$I+}
  If (IOResult <> 0) or (FileSize(f) <> 1) then
  for i := 1 to CMaxScores do
  begin
    table[i].name := 'Tomas Kruska';
    table[i].score := 110000 - i * 10000;
  end else
  begin
    Read(f, Table);
    Close(f);
  end;

  FileMode := OldMode;
end;

procedure SaveScore;
var
  f: file of THiScoreTable;
  OldMode: byte;
begin
  { Read/Write mode }
  OldMode := FileMode;
  FileMode := 2;

  Assign(f, CHiScoreFile);
{$I-}
  ReWrite(f);
{$I+}
  If IOResult = 0 then
  begin
    Write(f, Table);
    Close(f);
  end;

  FileMode := OldMode;
end;

end.

