c# 如何将二维数组拆分为较小的二维数组(块)列表?

c# How do i split a 2D array into a list of smaller 2D arrays (chunks)?

所以基本上,我目前正在制作游戏,我决定为大地图添加块,这样它就不会滞后。我的想法是有一个主二维数组,其中包含我的地图的所有图块(整数)和一个块列表(其他二维数组)。

static int[,] map;
static List<int[,]> chunks;

假设我的地图是 9x9 的图块,每个块是 3x3 的图块。我的块列表中应该总共有 9 个块。 我已经考虑了一个多星期了,但我还没有想出解决方案。

即使是一点点帮助也会有很大帮助。

首先,封装是你的朋友。不要在你的游戏代码中直接使用 multi-dimentional 数组,使用 classes。地图的 class 可以让您围绕地图编写游戏代码,而无需考虑如何存储块的内部细节。对块使用 class 可以让您轻松处理块。

然后,您可以为您的块分配 ID。将块存储在 Dictionary 中,其中 ID 是键。 Map 应该存储块 ID。当您的地图被询问某个位置 (x0,y0) 的图块时,您可以计算该图块属于哪个块,为您的块找到一个 ID,从您的块字典中获取该块并询问该图块。

您可以使用 Buffer.BlockCopy 和少量逻辑来实现此目的。 检查下面的代码

static void Main(string[] args)
        {
            int p = 1;
            int[,] array = new int[9, 9];
            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    array[i, j] = p++;
                }
            }
            GetChunkUsingBlockCopy(array, 3, 3);
        }

   static List<int[,]> GetChunkUsingBlockCopy(int[,] array, int row, int column)
        {
            int chunkcount = (array.GetLength(0) * array.GetLength(1)) / (row * column);
            List<int[,]> chunkList = new List<int[,]>();
            int[,] chunk = new int[row, column];

            var byteLength = sizeof(int) * chunk.Length;
            for (int i = 0; i < chunkcount; i++)
            {
                chunk = new int[row, column];
                Buffer.BlockCopy(array, byteLength * i, chunk, 0, byteLength);

                chunkList.Add(chunk);
            }

            return chunkList;
        }

希望对您有所帮助! 如果合适,请不要忘记将其标记为答案。