tags:

views:

144

answers:

3

I am currently having problems with screating a scoreboard in Delphi.

I have a series of forms which are individual questions. If the questions are answered correctly, then the score is 1. Otherwise the score is -1.

On my scoreboard at the moment, I have 12 labels and 11 of them contain the score for each of the forms. What I would like to do is add up the numbers in each of the labels and output the final score into the 12th label.

Is there a way of doing this? Any help will be greatly appreciated.

+3  A: 
  1. Neat solution: Keep scores as integers in Integer fields
  2. Not so neat solution:

    SumLabel.Caption := IntToStr( StrToIntDef( Label1.Caption, 0 ) + StrToIntDef( Label2.Caption, 0 ) + ... );

Ritsaert Hornstra
+8  A: 

You should use the UI purely for displaying your values.

For working with your data you should use appropriate data structures: array, lists, etc.

Example using an Array:

var
  Scores[0..10]: Integer;
  Sum: Integer;

procedure CollectData;
var
  i: Integer;
begin
   Scores[0] := ...;
   //...
   Scores[10] := ...;

   Sum := 0;
   for i := Low(Scores) to High(Scores) do
     Sum := Sum + Scores[i];
end;

procedure DisplayData;
begin
  Label1.Caption := IntToStr(Scores[0]);
  //...
  Label11.Caption := IntToStr(Scores[10]);
  Label12.Caption := IntToStr(Sum);
end;
DR
Why not add the Labels to a TList, then you don't need the repeated "Label<X>.Caption := IntToStr(Scores[x])".
Warren P
In that case TComponentList would be even better.
DR
+2  A: 

Although I think @DR's answer is spot-on, and @Ritsaert's is helpful, here's another option.

Your label components will have a 'TAG' property - you can use this for your own purposes and in your case I'd just set the TAG property at the same time as you set the Caption.

The advantage behind this is that you can format your caption to contain more than a simple number (if you wish), and also you are just summing up tags (which are already integers and don't need you to do the extra work behind a StrToIntDef call). Really, you're following @DR's point about keeping values out of the GUI (in a sense), you're using a storage field in each label instead.

eg;

when setting a score;-

Label1.Caption:=Format('%d point',[FScore]);
Label1.Tag:=FScore;

and when summing them;-

FSum:=Label1.Tag + Label2.Tag + Label3.Tag (etc)
robsoft