Java棋盘游戏

时间:2014-01-24 22:07:01

标签: java arrays multidimensional-array

基本上我在java中创建一个棋盘游戏,并设法使用数组创建一个看起来像10x10网格的单元格。现在我把它们编号为从左到右从上到下(如图) 我正在创造一个类似于蛇和梯子游戏的游戏,但它有自己的转折。

问题是:如何制作类似于蛇和蛇的锯齿形板梯板?

目前的情况如下:enter image description here

下面的代码是创建数组并打印并编号的必要条件。


名为Game的对象:

private Cell[][] cell =  new Cell[10][10];

public Game(String nameIt)
{
     super(nameIt);
     JPanel x = new JPanel(); 

 x.setLayout(new GridLayout(10, 10, 2, 2)); 
 for (int r = 0; ir< 10; r++) 
  for (int c= 0; c < 10; c++) 

  x.add(cell[r][c] = new Cell(r, c, this));

}

对象命名为单元格:

private int row;
private int col;
private int cellNum;
static int count = 0;


public Cell(int row, int column, Game guy) 
{

    this.ro = row;
    this.col = column;
    this.parent = guy;

    count = count+1;
    cellNum = count;

    setBorder(new LineBorder(Color.BLUE, 1));   // Set cell's border
}

protected void paintComponent(Graphics p) 
{
    super.paintComponent(p);

    p.drawString(String.valueOf(" " + cellNo), 24, 24);

}

1 个答案:

答案 0 :(得分:5)

好的,所以我不会为您编写确切的代码,但我会向您展示如何使用常规2D数组执行此操作的示例。我现在只有一个C ++编译器可用,但它应该足够清楚:

所以基本上你需要循环遍历行从头到尾。这就是为什么第一个外部循环从9变为0.这将从底行开始并在顶行完成,从而反转。

for (int i = 9; i >= 0; i--) {

    // now the trick to making a "zig-zag" is to alternate between two ways
    // of printing out each row. if i is even, you print out from right to left

    if (i % 2)
        for (int j = 9; j >= 0; j--)
            cout << numbers[i][j] << "\t";

    // and if i is odd, you print it out from left to right
    else
        for (int j = 0; j < 10; j++)
            cout << numbers[i][j] << "\t";

    cout << endl;

}

结果:enter image description here

相关问题