Ich hatte etwas Langeweile heute abend:
Deshalb habe ich mal eine Klasse gebastelt:
Delphi-Quellcode:
type
THighScoreElement = record
score : Integer;
end;
THighScore = class(TList)
private
maxCount: Integer;
procedure free;
public
procedure add(element:THighScoreElement);
function getIndex(index:Integer):THighScoreElement;
procedure loadFromFile(fileName:TFileName);
procedure saveToFile(fileName:TFileName);
constructor create(maxList:Integer);
end;
Der Typ THighScoreElement kann den eigenen Bedürfnissen
noch angepasst werden.
Nur das Feld score sollte enthalten bleiben,
da in der add Methode darauf zugegriffen wird.
Delphi-Quellcode:
constructor THighScore.create(maxList:Integer);
begin
inherited create;
maxCount := maxList;
end;
procedure THighScore.add(element:THighScoreElement);
var
i : Integer;
inserted : Boolean;
PHighScoreElement : ^THighScoreElement;
begin
i:=0;
inserted := false;
while (i <= self.Count -1) and not inserted do
begin
PHighScoreElement := self.Items[i];
if PHighScoreElement^.score < element.score then
begin
new(PHighScoreElement);
PHighScoreElement^:=element;
self.Insert(i,PHighScoreElement);
inserted := true;
end;
inc(i);
end;
if not inserted then
begin
new(PHighScoreElement);
PHighScoreElement^:=element;
inherited add(PHighScoreElement);
end;
if self.count > maxCount then
begin
PHighScoreElement := self.Items[self.count-1];
dispose(PHighScoreElement);
self.Delete(self.count -1);
end
end;
function THighScore.getIndex(index:Integer):THighScoreElement;
var
PHighScoreElement: ^THighScoreElement;
begin
PHighScoreElement:=self.Items[index];
result := PHighScoreElement^;
end;
procedure THighScore.loadFromFile(fileName:TFileName);
var
mStream : TMemoryStream;
PHighScoreElement : ^THighScoreElement;
begin
mStream := TMemoryStream.Create;
mStream.LoadFromFile(fileName);
while mStream.Position < mStream.Size do
begin
new(PHighScoreElement);
mStream.Read(PHighScoreElement^,sizeOf(THighScoreElement));
inherited add(PHighScoreElement);
end;
mStream.Free;
end;
procedure THighScore.saveToFile(fileName:TFileName);
var
mStream : TMemoryStream;
PHighScoreElement : ^THighScoreElement;
i : Integer;
begin
mStream := TMemoryStream.Create;
for i:=0 to self.Count -1 do
begin
PHighScoreElement := self.Items[i];
mStream.Write(PHighScoreElement^,sizeOf(THighScoreElement))
end;
mStream.SaveToFile(fileName);
mStream.Free;
end;
procedure THighScore.free;
var
i : Integer;
PHighScoreElement : ^THighScoreElement;
begin
for i:=self.Count -1 downto 0 do
begin
PHighScoreElement := self.Items[i];
dispose(PHighScoreElement);
self.Delete(i);
end;
inherited free;
end;
.. noch einen schönen Abend.
Grüße
Klaus