How do I do this ? Please help . Thanks alots ! lazarus / 13-General ---------------------------------------------------------------------- GoDxNero · 2009-10-12 20:53 Hallo everyone, first of all I just started delphi 2 week ago and this is my first post . Alright this is what I planned to do. I want to create a simple game. The contents is as follow :  There are 25 yellow colored circle-shaped which is show as 5x5. ( Done )  Each half second one random of those 25 circle should turn to green for 2 seconds then afterwards turn back to yellow (I tried to use TTimer and give var a := random(25) but i dont know if I did the right way or what to do next . ) Can anyone tell me how to do it the right way please ? Thanks alots in advance ! ---------------------------------------------------------------------- theo · 2009-10-12 21:10 Quote from: GoDxNero on October 12, 2009, 10:53:48 pmbut i dont know if I did the right way or what to do next . ) If it works, you probably did it the right way. ;-) If not: What doesn't work? ---------------------------------------------------------------------- Martin_fr · 2009-10-12 21:15 Maybe you can post a few more lines of the code you tried, and explain what exactly did not work? Did you get an error, a crash, or did simply nothing happen? Did you enable the timer? TTime.enabled := true; Otherwise it will not fire Since they turn green every 0.5 sec, and stay green for 2 sec => you have 4 green disk at any time (except the first 1.5 seconds), so you need a list which ones this are. The list can either include the disk-number and the time-to-turn-back yellow; or just the number. The time can be derrived from the position in the list, if you push new disks at the end, and take of the first list element every 0.5 secs to turn it yellow( you must shift all other list members one down). With a list of 4 elements, the stay green for 2 secs. random(25) is wrong: http://www.delphibasics.co.uk/RTL.asp?Name=Random "random(24)" or "random(24)+1" depending if you want 0 or 1 based Also since there are only 21 one yellow discs )or should green ones juts keep green for longer?): random(20) ---------------------------------------------------------------------- idog · 2009-10-12 22:31 Martin, you got me scared there for a minute!  I thought maybe FPC's Random isn't the same as Delphi's... so a small correction, if you will: He should be using "Random(25)" for 0-based array or "Random(25)+1" for 1-based, not 24 as you wrote. Random(25) returns values from 0 to 24 inclusive = 25 values overall. Now, GoDxNero, it will indeed be useful if you told us what, if anything, doesn't work as expected... What I would do, if I understand your plan correctly, is fisrt set a TTimer to 500 (that's 1/2s). I think the simplest way to manage the circles will be indeed to have an array of 25 "activation counters" - simply integers, like Martin suggested. Have them all 0 at the beginning. At the Timer Event code, choose a random "activation counter" from this array and make sure its value is 0 (this is important for later). If it isn't, pick another one by random until you find one that's 0. Now set it to 1 and paint the matching circle green. Also in that Timer Event code, go over the other counters and if they're greater than 0, increase them by 1. Check if any of them reaches 5: it means it's been active for 2 seconds, so you should redraw it in yellow and reset the counter to 0. ---------------------------------------------------------------------- Martin_fr · 2009-10-12 23:11 Quote from: idog on October 13, 2009, 12:31:36 amMartin, you got me scared there for a minute!  I thought maybe FPC's Random isn't the same as Delphi's... so a small correction, if you will: He should be using "Random(25)" for 0-based array or "Random(25)+1" for 1-based, not 24 as you wrote. Random(25) returns values from 0 to 24 inclusive = 25 values overall. upd, yes. I misread the page I linked. 0 < x < LimitPlusOne And I didnt look at the top, I expected it to be Random(Limit) => which it wasn't. ouch ---------------------------------------------------------------------- Martin_fr · 2009-10-12 23:20 Quote from: idog on October 13, 2009, 12:31:36 amI think the simplest way to manage the circles will be indeed to have an array of 25 "activation counters" - simply integers, like Martin suggested. Have them all 0 at the beginning. At the Timer Event code, choose a random "activation counter" from this array and make sure its value is 0 (this is important for later). If it isn't, pick another one by random until you find one that's 0. Now set it to 1 and paint the matching circle green. With 4 out of 25, that will still work reasonable, but it will waste time.   a := random(21);   b := a;   for i = 0 to a do     if circle > 0 then // circle[] is 0 based        inc(b);    if b > 24 then DoError('more than 4 circles are green')    circle := 1; it is more economic to have an array [0..3] of integer just to store 4 numbers of 4 circles, but an array with 25 entries will be easier to code   a := random(21); actually the first three lops it is random(24) random (23) random (22), so you need a counter, how many green disks you have already random(24 - GreenCnt) ---------------------------------------------------------------------- idog · 2009-10-12 23:55 True, saving just the four active indexes is more economic. Personally, in programs of this scale and importance I'd go for the easiest solution - but that's entirely a matter of preference (or of creating bad habits  ). In this case, I also suspect he might need more from these circles than just painting them green and yellow, and so he'll probably use a 25-item array anyway. About this Random limit thing, I remember that when I just started programming, this behavior really made me angry. What's the point of sending the value 25 to the function when 25 is the only value that will NEVER be returned? ---------------------------------------------------------------------- GoDxNero · 2009-10-13 07:59 Thanks alots for helping me guys  . Well first I though to create a TTimer with Interval = 500 so that every half second one of the 25 yellow circle will turn to green. var a : Integer begin    a := random(25);    Shape1 := Shape + IntToStr(a);    Shape1.Brush.Color := clGreen; I tried to have Shape(random) color = green but i really dont understand how to put it so I kinda tried some random lines  . Or perhaps the way I solve this probleem is wrong aswell  . I have never worked with array before ( just started weeks ago ) but I will take a look at how I can solve things with array if that is indeed the best way. But then afterwards if I manage to have some of them green. How will I turn them back to yellow after 2 seconds ? I am glad to hear more of your suggestion . ---------------------------------------------------------------------- idog · 2009-10-13 11:42 If you're new to Arrays, what I'll show you now is probably a bit too advanced, but you're welcomed to ask questions. Always remember this is just one of many, many possible ways of getting the same final result. First, we're NOT going to add TShapes from the toolbar, but to create them at runtime. So we'll add the ExtCtrls unit to the Uses clause at the top, and in the form definition we'll add: --------------------------------- MyCircle : Array[1..25] of TShape; --------------------------------- (this could be private or public, doesn't matter now). This is the array of shapes that we'll use for maintaining the circles. Now we'll enter the FormCreate event and write this code in order to initialize the circles and arrange them nicely in a 5x5 pattern: --------------------------------- procedure TForm1.FormCreate(Sender: TObject); var   x, y, Index : Integer; begin   for x := 1 to 5 do    for y := 1 to 5 do     begin       Index := (y - 1) * 5 + x;       MyCircle[Index] := TShape.Create(Self);       with MyCircle[Index] do        begin          Parent := Self;          Shape  := stCircle;          Tag    := 0; // This is the "activation counter"          Left   := (x - 1) * 40 + 10;          Width  := 36;          Top    := (y - 1) * 40 + 10;          Height := 36;          Brush.Color := clYellow;        end;     end;     end; --------------------------------- Of course, the 40/36/10 numbers are just makeshift suggestions. Now the circles are created "in principle, but the form itself is not painted yet. We'll have to draw them when it does, so in the FormShow event we'll write: --------------------------------- UPDATED: THIS PART IS NOT NEEDED, PLEASE IGNORE! -Ido --------------------------------- procedure TForm1.FormShow(Sender: TObject); var   Index : Integer; begin   for Index := 1 to 25 do MyCircle[Index].Paint; end;   --------------------------------- Run this and, hopefully, you'll see the 25 circles in Yellow. Now we'll move on to the timer thing. Add a timer to the form from the toolbar, set it to 500 and in its event write: --------------------------------- procedure TForm1.Timer1Timer(Sender: TObject); var   Current, j : Integer; begin   for j := 1 to 25 do // Go over all circles    with MyCircle[j] do     if Tag > 0 then // is it active? (green)      begin        Inc(Tag);        if Tag = 5 then // Two seconds have passed         begin           Tag := 0; // Reset counter           Brush.Color := clYellow; // change color back to yellow         end;      end;   // Find a yellow circle to activate   repeat Current := Random(25) + 1 until MyCircle[Current].Tag = 0;   // Activate it   with MyCircle[Current] do    begin      Tag := 1;      Brush.Color := clGreen;    end; end; --------------------------------- To make this perfect, don't forget to add a "Randomize" command to the initialization section of the unit, or somewhere else, to make sure you don't get the same pattern of randomness on each run... Also, note that sometimes it looks like a certain circle is green for more than 2 seconds - that's because it might get chosen again for activation immediately after its time was up. ---------------------------------------------------------------------- Martin_fr · 2009-10-13 12:25 @idog: Quote from: idog on October 13, 2009, 01:42:23 pmprocedure TForm1.FormShow(Sender: TObject); var   Index : Integer; begin   for Index := 1 to 25 do MyCircle[Index].Paint; end;    You don't need the explicit Paint. That's all done automatically. Actually you should never call paint directly, unless you know exactly why. The above calls Paint outside the PaintEvent, on some WidgetSets  that would do nothing at all. So assuming you had tocall it at all, you should do it in OnPaint. @GoDxNero: First except for the small correction The solution by idol is absolutely correct and preferred. You should go to the compiler options and enable RangeChecks (on the code-page/tab). This way, all access to the array wil be checked, and you will get a proper error if you try:   a:=26; MyCircle[a] := 1; There is no 26th element, so this can't work. With rangecheck, your app will create an exception, and the debugger will show you where it happened. Without RangeChecks, your will either just behave weird, or crash at random. Also node the Line   Parent := self It is forgotten quite often, and without nothing works. Second. If you need to access a component by it's name SomeComponent.FindComponent(AName); Best is Form1.FindComponent() or self.FindComponent(); (where self would be the Form1. But that will need more understanding of Object Orientation. FindComponent() can return TShapes, or TLabels, or .... so you need to tell what it did return (and you must tell correctly or you will crash again) Shape1 := (Form1.FindComponent("Shape1") as TShape); You may also see code like Shape1 := TShape(Form1.FindComponent("Shape1")); It is almost the same. The first does check if it is realy a TShape and will create an exception telling you. The 2nd is going to crash if it is not a TShape and is not telling you why. ---------------------------------------------------------------------- idog · 2009-10-13 12:48 True, the Paint loop is a leftover from some experimentation I made earlier and it shouldn't be in the code. Thanks! ---------------------------------------------------------------------- theo · 2009-10-13 17:15 You don't absolutely need a TShape. Canvas.Ellipse is an option too. I wrote this code yesterday. Not sure if it does exactly what is expected, but it is simple: Quoteunit Unit1; {$mode objfpc}{$H+} interface uses   Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,   ExtCtrls; type   { TForm1 }   TForm1 = class(TForm)     Timer1: TTimer;     procedure FormPaint(Sender: TObject);     procedure Timer1Timer(Sender: TObject);   private     { private declarations }   public     { public declarations }   end; var   Form1: TForm1;   Selected:integer; implementation { TForm1 } procedure TForm1.FormPaint(Sender: TObject); const dims=30; var i,tp,lft:integer; begin lft:=0; tp:=0; Canvas.Brush.Color:=clYellow; Canvas.Pen.Color:=clYellow; for i:=1 to 25 do  begin   if i=Selected then   begin    Canvas.Brush.Color:=clGreen;    Canvas.Pen.Color:=clGreen;   end;   Canvas.Ellipse(lft,tp,lft+dims,tp+dims);   if i=Selected then   begin    Canvas.Brush.Color:=clYellow;    Canvas.Pen.Color:=clYellow;   end;   inc(lft, dims);   if i mod 5=0 then   begin     lft:=0;     inc(tp,dims);   end;  end; end; procedure TForm1.Timer1Timer(Sender: TObject); begin   if Timer1.Interval<2000 then   begin    Selected:=Random(25)+1;    Timer1.Interval:=2000;   end else   begin    Selected:=-1;    Timer1.Interval:=500;   end;    Invalidate;    Application.ProcessMessages; end; initialization   {$I unit1.lrs} end. ---------------------------------------------------------------------- GoDxNero · 2009-10-18 18:53 Sorry for not reply early, I was away for few days. @idog Yep , this is exactly what i want !!! Thanks alots ! Is it possible to implant an onclick procedure ? I want to make some effect when a green one is clicked . @theo There is always only one green circle =( ---------------------------------------------------------------------- idog · 2009-10-18 20:10 No problem. You can change the size and position of the circles using their Top, Left, Width and Height properties. The changes you make will reflect in real time. Warning: This is not the kind of programming I usually do, so the experts here will probably have some corrections or better suggestions! Click events are relatively advanced stuff, in terms of theory, but they're not hard to implement. Most (all?) visual components have an "OnClick" pointer that can point to an event procedure. Whenever the operating system detects a mouse click on a component, it runs the procedure that its OnClick points to. You can add such an event procedure to your form. First, put the declaration     procedure CircleClick(Sender: TObject);   inside the form class definition (e.g. under the "MyCircles" definition). The Sender parameter is how the operating system tells you what component was clicked, so it uses the most general class - TObject. Now, write down the actual procedure in your unit. The following is an example that shrinks/expands a circle when it is clicked:   procedure TForm1.CircleClick(Sender: TObject);   begin     with Sender as TShape do      if Height = 36 then Height := 18 else Height := 36;   end; We know that this procedure is meant for circles only, and they are of TShape type, so we cast that TObject parameter to a TShape using the "as" keyword. Now we direct the OnClick pointer of each circle to this new procedure. This is done in the same place where the shape's other values are defined:    OnClick := @CircleClick; (the "@" means "address of") Try it out and if it works, change the event procedure code to do whatever you want. ---------------------------------------------------------------------- GoDxNero · 2009-10-21 17:32 the program run smothly but its not working :/ . perhaps I did somethings wrong. btw would you mind explain me what this code means ? MyCircle[Index] := TShape.Create(Self); Does this mean that [Index] = array 1..25 as we got var MyCircle : Array[1..25] of TShape; and then Create(Self) = all of them get to create on the same time or first Tshape1 then forward or how it exactly works ? stCircle   what does the st stand for ? Sorry if its a noob question as i am xD ---------------------------------------------------------------------- idog · 2009-10-21 18:05 When you declare an array, e.g. var a : Array [1..10] of Integer; You can think of it as declaring 10 consecutive integers all named "a", so to speak (this is not technically accurate, just for the explanation). The way to access each one of them individually is to use brackets with an index between them, e.g. a[1] := 999; // 1st "a" a[1+1] := 9999; // 2nd "a" MyVar := 3; a[MyVar] := 99; // 3rd "a" etc. So when we write MyCircle[Index] := TShape.Create(Self); we actually access a single element in MyCircle, whose index in the array is the value of the variable Index. Notice that this assignment takes place within loops ("for ..."), where Index gets a different value each time - that's how we fill up the entire array. the "TShape.Create(self)" is a command that creates a new instance of the class TShape. This instance is assigned to MyCircle[Index], and that's how we can access it from now on. We create 25 separate instances overall. stCircle is one of several values a TShape's Shape property can take (stRectangle, stDiamond etc.), and the "st" part is a naming convention derived from the type of this variable - TShapeType.  In essence, stCircle is just a simple constant number - the TShape class does all the complex computations to become an actual circle. ---------------------------------------------------------------------- GoDxNero · 2009-10-22 09:36 Thanks alots ! your answers are always easy to understand