3

我需要为我正在创建的游戏生成棋盘图案。我想出了以下(伪)代码,但觉得必须有一种更紧凑的方法来做到这一点。欢迎所有建议!

for (int i = 1; i < 9; i++){
    for (int j = 1; j < 9; j++){
        if (i % 2 == 1){
            if (j % 2 ==1){
                color = white
            }
            if (j % 2 ==0){
                color = black
            }
        }

        if (i % 2 == 0){
            if (j % 2 ==1){ 
                color = black
            }
            if (j % 2 ==0){
                color = white
            }
        }
        id = (i-1)*8+j
    }//end inner for
}//end outer for

谢谢。

4

6 回答 6

9
for (int i = 1; i < 9; i++){
    for (int j = 1; j < 9; j++){
        if ( i+j % 2 == 0 ) {
            color = white;
        } else {
            color = black;
        }
    }
}
于 2013-06-25T12:53:25.580 回答
0

我认为如果你在每次画完东西后交换颜色,那应该可以做到这一点。例如。

Start with black
Outer loop i
   Inner loop j
      Print colour square at position i,j
      Swap colours

然后应该去,例如奇数板。3x3

bwb
wbw
bwb
于 2013-06-24T23:40:31.653 回答
0

我会使用带有后继方法的枚举。然后你可以初始化如下:

  • position(col = 0, row = 0) 的颜色是 Colour.Black 或 Colour.White,具体取决于您定义原点的位置。
  • position(col = 0, row = n) 的颜色是 position(col = 0, row = n-1) 的继承者。
  • 在每一行中,位置(col = m,row = n)的颜色是位置(col = m-1,row = n)的后继。

这是颜色枚举:

public enum Colour {
    BLACK, WHITE;
    public Colour successor() {
        // Bulky general implementation.
        //return values()[(ordinal() + 1) % values().length];

        // Simpler version for our binary case.
        return equals( BLACK ) ? WHITE : BLACK;
    } 
}
于 2013-06-25T13:22:16.817 回答
0

一种通用解决方案,您可以在其中选择正方形边的像素数以及棋盘边上的正方形总数。

int dimSq = 10;         // in pixels
int dimBoard = 8;       // in squares
int pixels = dimSq * dimBoard;
for (int x = 0; x < pixels; x++)
    for (int y = 0; y < pixels; y++)
        boolean black = (x / dimSq) + (y / dimSq) % 2 == 0;
于 2015-12-10T13:47:51.833 回答
-1
for (int i = 1; i < 9; i++){
    for (int j = 1; j < 9; j++){
        if (i % 2 == j % 2){
            color = white
        } else {
            color = black
        }
        id = (i-1)*8+j
    }//end inner for
}//end outer for

通过所有的瓷砖,如果它们都是偶数或都是奇数(即(1,1),(1,3)......和(2,2)(2,4)(2,6)。 .. 和 (3,1) (3,3) (3,5) ... etc) 然后将其设为一种颜色,否则使用另一种颜色

例子:

B W B W B W
W B W B W B
B W B W B W
W B W B W B
B W B W B W
W B W B W B

您查看此处颜色全为黑色的索引,您会发现在所有这些索引中,X 和 Y 要么都是奇数,要么都是偶数。

另外,不确定您的id = (i-1)*8+j线路到底应该做什么

于 2013-06-24T23:40:56.037 回答
-1

单线

int dim = 10;
for (int i = 0; i < dim * dim; i++) System.out.print((i % dim == 0 ? "\n" : "") + ((i / dim) % 2 == 0 ? i % 2 == 0 ? 'B' : 'W' : i % 2 == 0 ? 'W' : 'B') + " ");

输出

B W B W B W B W B W 
W B W B W B W B W B 
B W B W B W B W B W 
W B W B W B W B W B 
B W B W B W B W B W 
W B W B W B W B W B 
B W B W B W B W B W 
W B W B W B W B W B 
B W B W B W B W B W 
W B W B W B W B W B
于 2013-06-25T00:26:49.190 回答