unit mainArrayOfCards;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Forms, Controls, StdCtrls, contnrs, strutils, math;
type
{ TCard }
TCard = class(TObject)
private
FIntProp: Integer;
FStrProp: string;
procedure SetIntProp(aValue: Integer);
procedure SetStrProp(const aValue: string);
public
constructor Create(const aStr: string; anInt: Integer);
property StrProp: string read FStrProp write SetStrProp;
property IntProp: Integer read FIntProp write SetIntProp;
end;
{ TDeck }
TDeck = class(TObjectList)
public
function AddCard(aCard: TCard): Integer;
procedure SortByIntThenString;
end;
{ TForm1 }
TForm1 = class(TForm)
Memo: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FDeck: TDeck;
procedure CreateDeck;
procedure WriteDeck;
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TDeck }
function IntThenStrCompare(Item1, Item2: Pointer): Integer;
var
c1: TCard absolute Item1;
c2: TCard absolute Item2;
begin
if (c1.FIntProp < c2.FIntProp) then
Exit(-1)
else if (c1.FIntProp > c2.FIntProp) then
Exit(1)
else Exit(strcomp(PChar(c1.FStrProp), PChar(c2.FStrProp)));
end;
{ TForm1 }
procedure TForm1.CreateDeck;
var
i: Byte;
j: Integer;
s: string;
intSet: set of byte = [];
begin
Randomize;
FDeck:=TDeck.Create(True);
for j:=1 to 30 do begin
i:=RandomRange(10, 50);
Str(i, s);
if (i in intSet) then
s:=ReverseString(s);
Include(intSet, i);
FDeck.AddCard(TCard.Create(Format('Card ''%s'', int#%d',[s, i]),i));
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
CreateDeck;
FDeck.SortByIntThenString;
Memo.Align:=alClient;
Memo.Clear;
Memo.ScrollBars:=ssAutoBoth;
WriteDeck;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FDeck.Free;
end;
procedure TForm1.WriteDeck;
var
o: Pointer;
card: TCard absolute o;
begin
Memo.Lines.Add('Contents of FDeck, sorted');
for o in FDeck do
Memo.Lines.Add(card.StrProp);
end;
function TDeck.AddCard(aCard: TCard): Integer;
begin
Assert(Assigned(aCard),'TDeck.AddCard: card is nil');
Exit(Add(aCard));
end;
procedure TDeck.SortByIntThenString;
begin
Sort(@IntThenStrCompare);
end;
{ TCard }
constructor TCard.Create(const aStr: string; anInt: Integer);
begin
Assert(aStr<>'','TCard.Create: invalid parameter');
inherited Create;
FStrProp:=aStr;
FIntProp:=anInt;
end;
procedure TCard.SetIntProp(aValue: Integer);
begin
if (FIntProp <> aValue) then begin
FIntProp:=aValue;
// other processing here
end;
end;
procedure TCard.SetStrProp(const aValue: string);
begin
if (FStrProp <> aValue) then begin
FStrProp:=aValue;
// other processing here
end;
end;
end.