我正在尝试创建一个使用四叉树的游戏。。如图所示,块是树的元素,它们可以有 0 个或 4 个孩子。最大的块在 0 级,它的子块在 1 级,依此类推。对于每个游戏,都有一个 maxLevel,您不能在该 maxLevel 上进一步细分块。让我们称不可分割的块为unit cells。只有叶子有颜色,而非叶子元素的颜色等于 null.
此外,块的子块按此顺序存储在数组中 [upperRight,upperLeft,lowerLeft,lowerRight]。我的目标是将树展平为二维颜色数组(arr[i] 代表行,arr[i][j] 代表棋盘上相应位置的 unit cell 的颜色)。例如,arr[0][0] 处的元素应该具有最大块左上角的 unit cell 的颜色。
这是我到目前为止得到的:
private Color[][] flatten(Color[][] arr) {
//base case
if(this.children.length != 0 && this.level == maxDepth - 1) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
//I don't know which indices to use. I tried doing some calculations to convert the coordinates into indices but I coudn't do it.
arr[?][?] = this.children[j].color;
}
}
}
//if the current block doesn't have children and it is at maxLevel-1
else if(this.children.length==0 && this.level == maxDepth - 1){
for(int i = 0; i < arr.length ; i++){
for(int j = 0; j < arr.length; j++){
//same indices problem here
arr[?][?] = this.color;
}
}
}
//recursive step
//I'm doing the recursive call in the order 1,0,2,3 because of the way the children are ordered
else if(this.children.length != 0 && this.level != maxDepth - 1){
this.children[1].flatten(arr);
this.children[0].flatten(arr);
this.children[2].flatten(arr);
this.children[3].flatten(arr);
}
return arr;
}