我只是想知道是否有更简单的方法:
for (int i = 0; i < 1; i++)
{
for (int j = 0; i < 8; j+2)
{
board[ i, j ] = 2;
board[( i + 1 ), j ] = 2;
board[( i + 2 ), j ] = 2;
}
}
我要做的是将棋子放在实际的棋盘上。所以这是将黑色部分放在顶部。
P.S。如果你也可以给我一些关于底部件(白色)的帮助。
答案 0 :(得分:4)
除了修复循环外,您还可以明确地放置碎片,使其更具可读性
int[,] board = new[,]{{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1}};
答案 1 :(得分:0)
您错过了告诉我们您想要实现的目标。我在你的代码中看到了几个大的错误,所以我假设你没有完全掌握循环的工作原理。我希望我在这里解释它并不是太冒昧
For循环
For循环用于多次执行相同部分的代码。执行次数取决于您设置的条件。通常,您会以这种格式看到它:
for (int i = 0; i < n; i++)
{
// Some code
}
这个for循环执行代码在括号内{
和}
)n
次。这不仅是定义循环的方法。循环的更全面定义如下:
for (<initialization>; <condition>; <afterthought>)
true
,则执行循环。执行循环并执行 afterterthought 后,将一次又一次地评估条件,直到它评估为false
。条件也是可选的。如果你把它放在外面,在C#循环中将再次执行,直到你以不同的方式打破循环。修复代码
我假设您想在棋盘格中标记8x8矩阵中的字段,尽管您的问题中没有说明这一点。你可以这样做:
// For each row in a board (start with 0, go until 7, increase by 1)
for (int i = 0; i < 8; i++)
{
// start coloring the row. Determine which field within the row needs
// to be black. In first row, first field is black, in second second
// field is black, in third row first field is black again and so on.
// So, even rows have black field in first blace, odd rows have black
// on second place.
// We calculate this by determining division remained when dividing by 2.
int firstBlack = i % 2;
// Starting with calculated field, and until last field color fields black.
// Skip every second field. (start with firstBlack, go until 7, increase by 2)
for (int j = firstBlack; j < 8; j += 2)
{
// Color the field black (set to 2)
board[i][j] = 2;
}
}
您可以在线查看我的评论。
代码中的大错误
// This loop would be executed only once. It goes from 0 to less than 1 and is increased
// after first execution. You might as well done it without the loop.
for (int i = 0; i < 1; i++)
{
// This doesn't make sense, because you use i in condition, and initialize
// and update j.
// Also, you are trying to update j, but you are not doing so. You are not
// assigning anything to you. You should do j+=2 to increase by two. Or you
// can do j = j + 2
for (int j = 0; i < 8; j+2)
{
// I didn't really understand what you were trying to achieve here
board[ i, j ] = 2;
board[( i + 1 ), j ] = 2;
board[( i + 2 ), j ] = 2;
}
}
答案 2 :(得分:0)
Modulo可以做到这一点,但我认为TonyS的anwser是我的第一反应,我宁愿把它放在下面显示的那个。
char[,] board = new char[8,8];
private void InitializeBoard()
{
string BoardRepresentation = "";
//for every board cell
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
//initialize board cell
board[i, j] = '0';
if (j <= 2)//black top
{
//Modulo is the trick
if ((j - i) == 0 || ((j - i) % 2) == 0)
{
board[i, j] = 'B';
}
}
else if (j >= 5) //white bot
{
if ((j - i) == 0 || ((j - i) % 2) == 0)
{
board[i, j] = 'W';
}
}
}
}
for (int j = 0; j < 8; j++)
{
for (int i = 0; i < 8; i++)
{
BoardRepresentation += board[i, j] + " ";
}
BoardRepresentation += Environment.NewLine;
}
}