Question

I use the TDrawGrid component to paint a grid. 46Y x 70X

enter image description here

If i select a cell it will be coloured with clGrey and if i select it again it will be coloured in White again. I want to count all clGrey couloured Cells.

My following code is what i tried, but didnt worked.

procedure TForm2.RasterDrawGridSelectCell(Sender: TObject; ACol, ARow: Integer;
  var CanSelect: Boolean);
begin
  UniversumsMatrix[ACol, ARow] := not UniversumsMatrix[ACol, ARow];

    begin
    if RasterDrawGrid.Brush.Color = clGrey then begin
      Zellenstand := Zellenstand - 1
    end
    else
      Zellenstand := Zellenstand +1 ;
  end;
end;

procedure TForm2.RasterDrawGridDrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
begin
  if UniversumsMatrix[ACol, ARow] then
    RasterDrawGrid.Canvas.Brush.Color := clGray // Grauer der lebendigen Hintergrund
  else
    RasterDrawGrid.Canvas.Brush.Color := clWhite; // Weißer Hintergrund
    RasterDrawGrid.Canvas.FillRect(Rect);
end;
Was it helpful?

Solution

A more efficent way of handling the counter would be wrapping the array in a class with according setter and getter, and accessing the array only via setters and getters.

Type
  TUniverseClass = Class
  Private
    FArray: Array [0 .. 71, 0 .. 45] of Boolean;
    FLivingCount: Integer;
    function GetXY(X, Y: Integer): Boolean;
    procedure SetXY(X, Y: Integer; const Value: Boolean);
  Public
    Property XYValue[X, Y: Integer]: Boolean Read GetXY Write SetXY;
    Property LivingCount: Integer Read FLivingCount;

  End;

var
  UniverseClass: TUniverseClass;

  { UniverseClass }

function TUniverseClass.GetXY(X, Y: Integer): Boolean;
begin
  Result := FArray[X, Y];
end;

procedure TUniverseClass.SetXY(X, Y: Integer; const Value: Boolean);
begin
  if FArray[X, Y] <> Value then
    if Value then
      Inc(FLivingCount)
    else
      Dec(FLivingCount);
  FArray[X, Y] := Value;
end;
// example call
procedure TForm1.Button1Click(Sender: TObject);
begin
  UniverseClass.XYValue[0, 0] := true;
  Memo1.Lines.Add(IntToStr(UniverseClass.LivingCount));
  UniverseClass.XYValue[1, 1] := true;
  Memo1.Lines.Add(IntToStr(UniverseClass.LivingCount));
  UniverseClass.XYValue[0, 0] := false;
  Memo1.Lines.Add(IntToStr(UniverseClass.LivingCount));

end;

initialization

UniverseClass := TUniverseClass.Create;

finalization

UniverseClass.Free;

OTHER TIPS

It looks that in UniversumsMatrix you already have Boolean values. Just calculate True or False values.

UniversumsMatrix is filled by you. Why don't you have a Sum variable which is increased when you set a value to TRUE? You wouldn't even have to bother counting cells in a drawgrid?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top