【问题标题】:Resize a 2D map调整 2D 地图的大小
【发布时间】:2016-03-03 17:50:56
【问题描述】:

我正在为游戏开发 2D 地图编辑器,我需要一种方法来在各个方向上统一增加或减少网格/地图的大小。

假设你有一个 3x3 的地图,上面有一种“十字”符号。

(数组是零索引的。它们从 0 开始)

像这样:

0,1,0
1,1,1
0,1,0

数组看起来像这样:

map = [0,1,0,1,1,1,0,1,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,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0]

有什么好的方法吗?

【问题讨论】:

    标签: arrays matrix grid 2d


    【解决方案1】:

    这里是增加和减少的两个函数。参数 arr 是您的一维地图,xWidth 是网格的宽度(当然还有高度)。 我有一个与 here on Stackoverflow 相似背景的问题,非常感谢 willywonka_dailyblah 在 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;
    }
    

    我有这个打印功能:

    public void print_arr(int[] a, int xWidth)
    {
       for(int i=0;i<xWidth;i++)
       {
          for(int j=0;j<xWidth;j++)
          {
             System.out.print(a[i * xWidth + j]+" "); 
          }
          System.out.println();
       }
       System.out.println();
    }
    

    您将这些函数称为:

      int[] map = new int[]{0,1,0,1,1,1,0,1,0};
      print_arr(map, 3);
      map = increase_grid(map, 3);
      print_arr(map, 5);
    
      map = increase_grid(map, 5);
      print_arr(map, 7);
    
      map = decrease_grid(map, 7);
      print_arr(map, 5);
    

    因此,您必须传递地图的当前大小并调用增加或减少。请注意,这些函数包含一个嵌套的 for 循环。因此,它们在较大的网格尺寸上的可扩展性较差。我认为可能有一个解决方案可以将它包装成一个循环序列,它可以在没有嵌套的情况下运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-07
      • 2010-12-21
      • 2014-10-05
      • 1970-01-01
      • 2014-08-16
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多