Mega Code Archive

 
Categories / Delphi / Ide Indy
 

Bouncing balls...delphi TList

Title: bouncing balls...delphi TList Question: This example how to manipulate with objects in a TList. Answer: (* Delphi is object oriented so this article is about using the TList. It's something like standart TListBox - but non-visual and items are NOT "strings" but "Pointers" ! In this example we will generate 20 objects - TShapes with random shape and these objects will go down and up and left and right etc. 1.Create Timer named Timer1 and set interval 1, enabled = true. 2.Create Button named Button1. 3.Select mainform(probably form1) and set AutoScroll property to "false". *) (*================================================================*) unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Button1: TButton; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; L: TList; ObjNum, MaxSpeed: Integer; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin L := TList.Create; ObjNum := 20; // this you can change of course... MaxSpeed := 4; // maximal speed for each shape... end; procedure TForm1.Button1Click(Sender: TObject); Var I, R: Integer; begin L.Clear; For I := Form1.ComponentCount-1 downto 0 do begin if form1.Components[I] is TShape then TShape(form1.Components[I]).Free; end; For I := 0 to ObjNum do begin L.Add(TShape.Create(form1)); With TShape(L.Items[I]) do begin Parent := Form1; Tag := 1+Random(MaxSpeed); // X speed Hint := IntToStr(1+Random(MaxSpeed)); // Y speed Width := 25; Height := 25; Brush.Color := RGB(Random(255), Random(255), Random(255)); Randomize; R := Random(10); if (R = 0) and (R if (R = 5) and (R Left := 1+Random(form1.Width-Width-27); Top := Random(form1.Height div 2); Visible := True; end; end; end; procedure TForm1.Timer1Timer(Sender: TObject); Var I, XS, YS, X, Y: Integer; begin For I := 0 to L.Count-1 do begin X := TShape(L.Items[I]).Left; Y := TShape(L.Items[I]).Top; XS:= TShape(L.Items[I]).Tag; YS:= StrToInt(TShape(L.Items[I]).Hint); if X = form1.Width-25-XS then XS := -1*(XS); if X if Y = form1.Height-25-YS then YS := -1*(YS); if Y TShape(L.Items[I]).Tag := XS; TShape(L.Items[I]).Hint := IntToStr(YS); TShape(L.Items[I]).Left := TShape(L.Items[I]).Left+XS; TShape(L.Items[I]).Top := TShape(L.Items[I]).Top +YS; end; end; end. (*================================================================*) { PRESS F9 and click the Button1 :-)) } Ivan Sivak @Sizesoft