我正在尝试创建的程序使用Delphi TStringGrid
组件。基本上,我正在尝试这样做,所以我可以使用4个按钮将值P
移动到网格中:向上,向下,向左< / kbd>和右。
我可以向上,向下或向左移动P
的值。但是,出于某种原因,当我尝试向右移动时,它会用0
而不是仅仅1个元素填充整行。我无法弄清楚原因。
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;
这是程序的外观:
P
位于(7,7)
按右:
时会发生这种情况 P
位于(3,6),按下右后,它将整行更改为0
。
答案 0 :(得分:4)
正如Tom Brunberg在评论中所建议的那样,如果你跟踪P
的当前位置并完全删除循环,它将更有效,更容易管理。例如:
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;