如何在一个二维数组中同时创建/移动多个对象?

o2gm4chl  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(228)

我们正在尝试创建一个形状,并将其放置在基于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;
}
nxagd54h

nxagd54h1#

每次打印时都要定义新的网格 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

相关问题