2 回答

TA貢獻1848條經驗 獲得超6個贊
我也想讓你學習,因為這似乎是一個為教學設計的入門級項目。
因此,與其直接提供答案,不如通過解釋您當前的程序當前正在做什么來向您展示您的錯誤所在。
// size is the pixel width/height of a square.
// multiples is the number of black/white pairs to draw.
// x,y are the screen position of the top left corner.
// offset is the amount to offset by.
public static void grid(Graphics g, int size, int multiples, int x, int y, int offset) {
for (int i = 0; i < multiples * 2; i++) {
row(g, size, multiples, x + (offset * i), y + (size * i) + (2 * i));
}
}
這里的代碼相對簡單。
它當前從 0 增量循環 1,對于您要繪制的黑白方塊的總數。(在倍數之前停止*2,從0開始是正確的)
每次循環時,它都會調用 row.
它大致相當于
row(g, size, 2, x + (offset * 0), y + (size * 0) + (2 * 0));
row(g, size, 2, x + (offset * 1), y + (size * 1) + (2 * 1));
row(g, size, 2, x + (offset * 2), y + (size * 2) + (2 * 2));
row(g, size, 2, x + (offset * 3), y + (size * 3) + (2 * 3));
(它創建的行數是黑色列的兩倍)
您遇到的問題是您的偏移量總是在增長,而不是來回曲折。
where x = 0, and offset = 10
rowoffset = x + (offset * 0) = 0
rowoffset = x + (offset * 1) = 10
rowoffset = x + (offset * 2) = 20
rowoffset = x + (offset * 3) = 30
但你想要的是
where x = 0, and offset = 10
rowoffset = 0; // where i == 0
rowoffset = 10 // where i == 1
rowoffset = 0 // where i == 2
rowoffset = 10 // where i == 3
實現分支行為的常用方法(取決于要做出的決定)是使用 if 語句。
因此x+offset*i,您可以在那里引入一個變量,而不是傳遞給 row,這取決于 i 是奇數還是偶數。
計算整數是奇數還是偶數的常用方法是使用余數運算符 ( %),傳入數字 2。(但在任一側使用負值時必須小心)
0%2 == 0
1%2 == 1
2%2 == 0
3%2 == 1
~~~
8%2 == 0
9%2 == 1
因此,您現在可以使用數學或 if 語句來使您的鋸齒形圖案看起來像圖案。

TA貢獻1831條經驗 獲得超10個贊
您不斷在網格方法中添加 x 參數。
如果只想每隔一行移動一次,可以使用如下模運算:
public static void grid(Graphics g, int size, int multiples, int x, int y, int offset) {
for (int i = 0; i < multiples * 2; i++) {
row(g, size, multiples, x + offset * (i % 2), y + (size * i) + (2 * i));
}
}
添加回答
舉報