我正在研究GUI。我有一个使用TableLayoutPanel显示的游戏板。它有 6 列和 7 行。平方数的顺序正确,它们应该在某些行上从右到左。例如;
- 23-22-21-20-19-18
- 12-13-14-15-16-17
- 11-10-9-8-7-6
- 开始-1-2-3-4-5
但是在我的代码中,方格数字总是从左到右。你能帮忙吗?
private void SetupGameBoard() {
int counter = 0;
for (int row = NUM_OF_ROWS-1; row > -1; row--) {
for (int column = 0; column < NUM_OF_COLUMNS; column++) {
SquareControl squareControl = new SquareControl
(hareAndTortoiseGame.Board.Squares[counter], hareAndTortoiseGame.Players);
if ((row == 6 && column == 0) || (row == 0 && column == 5)){
squareControl.BackColor = Color.BurlyWood;
}
GameTableLayout.Controls.Add(squareControl, column, row);
counter++;
}
}
}
你只是在一个方向上迭代,那就是从左到右。您的第一个 for 循环需要在向上和向下迭代列之间交替。
你想要一个沿着行呈锯齿形排列的游戏板。向下迭代行的逻辑很好,从最高的行开始向下移动。现在您只需要处理列。您指出列中的值在现在出现时始终是从左到右的。也就是说,我假设它们看起来像:
- 23-22-21-20-19-18
- 17-16-15-14-13-12
- 11-10-9-8-7-6-5
- 4-3-2-1-启动
这是因为您的列值始终从 0 到>max,但尚未涵盖 max->0。
一些 peusdo 代码:
for number of rows
if row % 2 == 0 //if we are on an even row
iterate up
else
iterate down
一些未经测试的实际代码:
private void SetupGameBoard() {
int counter = 0;
for (int row = NUM_OF_ROWS-1; row > -1; row--) {
if(row % 2 == 0){
for (int column = NUM_OF_COLUMNS; column > -1; column--) {
SquareControl squareControl = new SquareControl
(hareAndTortoiseGame.Board.Squares[counter], hareAndTortoiseGame.Players);
if ((row == 6 && column == 0) || (row == 0 && column == 5)){
squareControl.BackColor = Color.BurlyWood;
}
GameTableLayout.Controls.Add(squareControl, column, row);
counter++;
}
}
else{
for (int column = 0; column < NUM_OF_COLUMNS; column++) {
SquareControl squareControl = new SquareControl
(hareAndTortoiseGame.Board.Squares[counter], hareAndTortoiseGame.Players);
if ((row == 6 && column == 0) || (row == 0 && column == 5)){
squareControl.BackColor = Color.BurlyWood;
}
GameTableLayout.Controls.Add(squareControl, column, row);
counter++;
}
}
}
你显然可以将其中的一些分解为其他方法,因为有很多重复的东西。这个想法是,您根据您是在奇数行还是偶数行上完成锯齿形。
你只需要做一些数学运算。 这是遍历所有单元格(按单元格编号)并获取行和列的数学方法。 剩下的就交给你了。 注意:我没有测试...可能是拼写错误或语法错误。
const int maxCols = 6;
const int maxRows = 4;
int numberCells = maxCols * maxRows; // zero based in main array.
for (int cellNumber = 0; cellNumber < numberCells; cellNumber)
{
int row;
int col;
row = maxRows - floor(cellNumber / maxRows);
bool oddRow = (row % 2) == 1;
col = oddRow ? (cellNumber % maxCols) + 1 : maxCols - (cellNumber % maxCols);
// I believe the following is what you want to do in your proc.
SquareControl squareControl = new SquareControl(hareAndTortoiseGame.Board.Squares[cellNumber], hareAndTortoiseGame.Players);
if ((row == 6 && col == 0) || (row == 0 && col == 5))
// if ((cellNumber == 0) || (cellNumber == (numberCells-1)))
{
squareControl.BackColor = Color.BurlyWood;
}
GameTableLayout.Controls.Add(squareControl, col, row);
}