在 Java 中实施方形分区
Implementing a square partition in Java
我遇到了概念上的问题。我想实现一个 Android 游戏,其中一个功能是:每次我触摸一个正方形,它被分成 4 个相同大小的小正方形。每个下一个正方形都以相同的方式划分,直到达到限制,比方说,原始大小的 1/1024。这是一个小插图:
问题是,我不确定如何以最佳方式存储这些数据。我需要存储每一块的大小,以便它知道分割后应该缩小到什么大小。例如,如果在第一次触摸和第一次除法之后,我的数组(对于 16 个元素限制)将如下所示:
0 0 1 1
0 0 1 1
2 2 3 3
2 2 3 3
然后如果我触摸左上角的方块,下一个数组将是这样的:
[0,0] [0,1] 1 1
[0,2] [0,3] 1 1
2 2 3 3
2 2 3 3
或者至少我是这么想的。然而,这看起来实施起来很复杂,在每次下一次迭代中都会引入额外的维度,而且我不太确定如何正确地做到这一点。有什么想法吗?
如果是关于保存正方形坐标的最佳方式,我更喜欢定义一个自定义 class,它有 4 个属性,Xtopleft、Ytopleft、Xbottomright、Ybottomright(我们称之为 SquarePosition)并将所有集合中的正方形位置对象,例如 Set of SquarePosition
当然需要重写自定义的equals方法class
比如你有这样的方板:
1 2 3 3
4 5 3 3
6 6 7 7
6 6 7 7
您可以像这样设置集合:
{(1,1),(1,1)}, {(2,1),(2,1)}, {(3,1),(4,2)}, {(1,2),( 1,2)}, {(2,2),(2,2)}, {(1,3),(2,4)}, {(3,3),(4,4)}
使用四叉树。伪代码如下:
public class QuadTree {
private QuadTree[] children;
private double x;
private double y;
private double size;
public QuadTree(double x, double y, double size) {
this.x = x;
this.y = y;
this.size = size;
}
public void divide() {
if (children == null) {
children = new QuadTree[4];
double s = 0.5 * size;
children[0] = new QuadTree(x, y, s);
children[1] = new QuadTree(x + s, y, s);
children[2] = new QuadTree(x, y + s, s);
children[3] = new QuadTree(x + s, y + s, s);
}
}
public QuadTree getChild(int index) {
if (children == null)
return null;
else
return children[index];
}
我遇到了概念上的问题。我想实现一个 Android 游戏,其中一个功能是:每次我触摸一个正方形,它被分成 4 个相同大小的小正方形。每个下一个正方形都以相同的方式划分,直到达到限制,比方说,原始大小的 1/1024。这是一个小插图:
问题是,我不确定如何以最佳方式存储这些数据。我需要存储每一块的大小,以便它知道分割后应该缩小到什么大小。例如,如果在第一次触摸和第一次除法之后,我的数组(对于 16 个元素限制)将如下所示:
0 0 1 1
0 0 1 1
2 2 3 3
2 2 3 3
然后如果我触摸左上角的方块,下一个数组将是这样的:
[0,0] [0,1] 1 1
[0,2] [0,3] 1 1
2 2 3 3
2 2 3 3
或者至少我是这么想的。然而,这看起来实施起来很复杂,在每次下一次迭代中都会引入额外的维度,而且我不太确定如何正确地做到这一点。有什么想法吗?
如果是关于保存正方形坐标的最佳方式,我更喜欢定义一个自定义 class,它有 4 个属性,Xtopleft、Ytopleft、Xbottomright、Ybottomright(我们称之为 SquarePosition)并将所有集合中的正方形位置对象,例如 Set of SquarePosition
当然需要重写自定义的equals方法class
比如你有这样的方板:
1 2 3 3
4 5 3 3
6 6 7 7
6 6 7 7
您可以像这样设置集合: {(1,1),(1,1)}, {(2,1),(2,1)}, {(3,1),(4,2)}, {(1,2),( 1,2)}, {(2,2),(2,2)}, {(1,3),(2,4)}, {(3,3),(4,4)}
使用四叉树。伪代码如下:
public class QuadTree {
private QuadTree[] children;
private double x;
private double y;
private double size;
public QuadTree(double x, double y, double size) {
this.x = x;
this.y = y;
this.size = size;
}
public void divide() {
if (children == null) {
children = new QuadTree[4];
double s = 0.5 * size;
children[0] = new QuadTree(x, y, s);
children[1] = new QuadTree(x + s, y, s);
children[2] = new QuadTree(x, y + s, s);
children[3] = new QuadTree(x + s, y + s, s);
}
}
public QuadTree getChild(int index) {
if (children == null)
return null;
else
return children[index];
}