ban can
ban can

Reputation: 77

Moving Values through a TStringGrid's Cells

The program I'm trying to create uses the Delphi TStringGrid component. Basically, I'm trying to make it so I can move the value P through the grid using 4 buttons: Up, Down, Left, and Right.

I can move the value of P up, down, or left. But, for some reason, when I try to move it right, it fills the entire row with 0 instead of just the 1 element. I can't figure out why.

procedure TForm2.Button4Click(Sender: TObject);//pressing the "right" button
var
  i, j: Integer;
begin
  for i :=  0 to Form2.StringGrid1.ColCount do
    for j := 0 to Form2.StringGrid1.RowCount do
      if StringGrid1.Cells[i, j] = 'P' then
      begin
        StringGrid1.Cells[i, j] := '0';
        StringGrid1.Cells[i+1, j] := 'P';
        { I have done the same for up, left and down (down would be j+1, left would be i-1, etc}
        break;
      end;
end;

This is how the program looks:

image

P is located at (7,7)

This is what happens when I press Right:

image

P was located at (3,6) and after pressing right, it changed the entire row to 0.

Upvotes: 0

Views: 503

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596256

As Tom Brunberg suggested in comments, it would be much more efficient and easier to manage if you keep track of the current position of P and remove the loops altogether. For example:

private
  PColumn: Integer;
  PRow: Integer;

procedure TForm2.FormCreate(Sender: TObject);
begin
  // populate the grid as needed...
  // place 'P' somewhere on the grid and keep track of it...
  PColumn := ...;
  PRow := ...;
end;

// pressing the "up" button
procedure TForm2.Button1Click(Sender: TObject);
begin
  if PRow > 0 then
  begin
    Dec(PRow);
    StringGrid1.Cells[PColumn, PRow+1] := '0';
    StringGrid1.Cells[PColumn, PRow  ] := 'P';
  end;
end;

// pressing the "left" button
procedure TForm2.Button2Click(Sender: TObject);
begin
  if PColumn > 0 then
  begin
    Dec(PColumn);
    StringGrid1.Cells[PColumn+1, PRow] := '0';
    StringGrid1.Cells[PColumn,   PRow] := 'P';
  end;
end;

// pressing the "down" button
procedure TForm2.Button3Click(Sender: TObject);
begin
  if PRow < (StringGrid1.RowCount-1) then
  begin
    Inc(PRow);
    StringGrid1.Cells[PColumn, PRow-1] := '0';
    StringGrid1.Cells[PColumn, PRow  ] := 'P';
  end;
end;

// pressing the "right" button
procedure TForm2.Button4Click(Sender: TObject);
begin
  if PColumn < (StringGrid1.ColCount-1) then
  begin
    Inc(PColumn);
    StringGrid1.Cells[PColumn-1, PRow] := '0';
    StringGrid1.Cells[PColumn,   PRow] := 'P';
  end;
end;

Upvotes: 4

Related Questions