Arrays 调整二维地图的大小
我正在为一个游戏开发一个2D地图编辑器,我需要一种方法来在所有方向上均匀地增加或减少网格/地图的大小 假设你有一张3x3的地图,上面有一个十字符号 (数组的索引为零。它们以0开头) 像这样:Arrays 调整二维地图的大小,arrays,matrix,grid,2d,Arrays,Matrix,Grid,2d,我正在为一个游戏开发一个2D地图编辑器,我需要一种方法来在所有方向上均匀地增加或减少网格/地图的大小 假设你有一张3x3的地图,上面有一个十字符号 (数组的索引为零。它们以0开头) 像这样: 0,1,0 1,1,1 0,1,0 该阵列将如下所示: map = [0,1,0,1,1,1,0,1,0] map = [0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0] 因此,平铺索引4将是地图的中心 例如,我想把尺寸从3x3增加到5x5。因此,我最终
0,1,0
1,1,1
0,1,0
该阵列将如下所示:
map = [0,1,0,1,1,1,0,1,0]
map = [0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0]
因此,平铺索引4将是地图的中心
例如,我想把尺寸从3x3增加到5x5。因此,我最终得出以下结论:
0,0,0,0,0
0,0,1,0,0
0,1,1,1,0
0,0,1,0,0
0,0,0,0,0
新的映射数组应以如下方式结束:
map = [0,1,0,1,1,1,0,1,0]
map = [0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0]
做这件事的好方法是什么?这里有两个增加和减少功能。参数arr是一维贴图,xWidth是网格的宽度(当然还有高度)。 我有一个背景相似的问题,非常感谢在j和I指数上帮助我的人
public int[] increase_grid(int[] arr, int xWidth)
{
int newWidth = (xWidth+2);
int[] result = new int[newWidth * newWidth];
int count=0;
while(count<newWidth)
{
result[count++] = 0;
}
for (int i=0;i<xWidth;i++)
{
result[count++] = 0;
for (int j=0;j<xWidth;j++)
{
result[count++] = arr[i * xWidth + j];
}
result[count++] = 0;
}
while(count<(newWidth*newWidth))
{
result[count++] = 0;
}
return result;
}
public int[] decrease_grid(int[] arr, int xWidth)
{
int newWidth = (xWidth-2);
int[] result = new int[newWidth*newWidth];
for(int i=0; i< newWidth;i++)
{
for (int j=0;j< newWidth;j++)
{
result[i* newWidth + j] = arr[(i+1) * xWidth + (j+1)];
}
}
return result;
}
因此,您必须传递地图的当前大小,然后调用“增大”或“减小”。注意,这些函数包含嵌套的for循环。因此,它们在更大的网格大小上的可伸缩性较差。我认为可能有一种解决方案可以将其包装成一个循环序列,该序列不嵌套运行