如何一次在二维数组上创建/移动多个对象?

时间:2014-03-11 14:00:24

标签: java arrays object console 2d

我们正在尝试创建一个形状并将其放置在基于控制台的2d控制台上。形状将由2d阵列上的多个点组成。因此,例如三角形看起来像用户输入4x3x3 ...

   1
 1 1 1
1 1 1 1

形状将能够移动和增长/收缩。我们的形状已经能够显示它们的尺寸,以及板材本身。但实际上将它们放在板上并移动它们(所有点作为一个整体)证明是困难的。有什么建议?这是我们到目前为止的代码......

董事会代码......

public class Board {

private int size;

public Board(int boardSize){
    this.size = boardSize;
}

public String toString() {

    Playable[][] grid = new Playable [getSize()][getSize()];

    int k = 1;
    while (k <= (grid.length+2)) {
        System.out.print('-');
        k++;
    }

    System.out.println();

    for (Playable[] row : grid) {
        System.out.print("|");
        for (Playable item : row) {
            System.out.print((item == null ? " " : item));
        } System.out.print("| \n");
    }

    k = 1;
    while (k <= (grid.length+2)) {
        System.out.print('-');
        k++;
    }
    return "";
}

public int getSize() {
    return size;
}

public void setSize(int size) {
    this.size = size;
}
 }

形状代码......

 public class Rectangle extends Quads implements Playable {

public Rectangle(int numberOfSides, int numberOfDimensions) {
    super(4, 2);
    // TODO Auto-generated constructor stub
}

public double calcPerimeter() {
    return ((this.getDimensions()[0] + this.getDimensions()[1]) * 2);
}

public double calcArea() {
    double area;
    area = this.getDimensions()[0] * this.getDimensions()[1];
    return area;
}

public String showDimensions() {
    String display = "";
    display += "For this " + this.getColor() + " "
            + this.getClass().getSimpleName() + ": \n";

    display += this.getDIMENSION_LABELS()[0] + ": "
            + this.getDimensions()[0] + "\n";
    display += this.getDIMENSION_LABELS()[1] + ": "
            + this.getDimensions()[1] + "\n";
    display += this.getDIMENSION_LABELS()[2] + ": "
            + this.getDimensions()[0] + "\n";
    display += this.getDIMENSION_LABELS()[3] + ": "
            + this.getDimensions()[1] + "\n";
    display += "The perimeter is " + this.calcPerimeter() + ", \n";
    display += "The area is " + this.calcArea() + ", \n";
    display += "And the seniority is " + this.getSeniority() + "\n";
    return display;
}

1 个答案:

答案 0 :(得分:0)

每次打印时都定义新网格,将Playable[][] grid作为字段,这样你就可以存储状态然后这样做

grid[0][0] = new Playable(){...};//create
grid[1][0] = grid[0][0];//copy to new location
grid[0][0] = null; //remove from old location