【问题标题】:C# - switch array elements by 90°C# - 将数组元素切换 90°
【发布时间】:2015-10-17 20:14:08
【问题描述】:

我正在尝试制作俄罗斯方块游戏。到目前为止,我完成了一切,除了旋转功能。所以,总结一下。计划是将以下数组元素旋转 90°:(在本例中为 bool 数组)

. . . . .                 . . . . .
. . x . .                 . . . . .
. . x x .     ====== >    . . x x .
. . . x .                 . x x . .
. . . . .                 . . . . .

为此,我编写了以下代码:

private bool[,] rotateGrid(bool[,] _grid)
    {
        bool[,] g = new bool[5, 5];

        for(int i=0; i<5; i++)
        {
            bool[] row = new bool[5];

            for(int j=4; j>=0; j--)
            {
                int jInvert = 4 - j;

                row[jInvert] = grid[j, i];
            }

            for(int j=0; j<5; j++)
            {
                grid[i, j] = row[j];
            }
        }

        return g;
    }

不知何故,如果我用一个完整的数组调用这个函数,它会重新调整一个空数组。

为什么?

【问题讨论】:

  • 你从来没有给g分配任何东西......这就是为什么
  • This post 总结得很好

标签: c# arrays multidimensional-array tetris


【解决方案1】:

我的 Java 代码,只需将其转换为 c#。 如果您想做得更好,请使用 lambda 表达式。 使用 lambda 表达式,您可以在一行代码中做到这一点:)

/*rotates a block 90* right*/
    private static boolean[][] rotateBlock(boolean[][] block){
        boolean [][] temp;
        int longestRow = longestRow(block);
        temp = new boolean[longestRow][block.length];
        int counter = 0;
        for(int i = 0; i < longestRow;i++){
            for(int j = 0; j < block.length;j++){
                if(i < block[j].length){
                    if(block[j][i]){
                        temp[i][counter] = true;
                        counter++;
                    }
                }
                else{
                    //null = false
                    temp[i][counter] = false;
                    counter++;
                }
            }
            counter = 0;
        }
        return temp;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多