如果下一个位置是特定对象,我如何签入二维数组?

时间:2017-09-28 09:42:30

标签: c# arrays c#-4.0 maze

我正在创建一个二维阵列的迷宫游戏,但我无法弄清楚如何使墙/门/等工作。我想当我按'W'时,只有当下一个位置不是墙时才会改变角色的位置。我该如何检查? 这是我的地图和运动代码:

const int ROWS = 16, COLUMNS = 24;
        Blocks[,] map = new Blocks[COLUMNS, ROWS];
        int playerRow = 3, playerColumn = 11;
        Character gubbe = new Character();


        // Create map
        for (int row = 0; row < ROWS; row++)
        {
            for (int column = 0; column < COLUMNS; column++)
            {

                if (row == 0 || row == ROWS - 1 || column == 0 || column == COLUMNS - 1)
                    map[column, row] = new Wall();

                else
                    map[column, row] = new EmptySpace();

            }
        }

        while (true)  // TODO: add a goal that ends the loop
        {
            // Draw map
            string buffer = "";
            for (int row = 0; row < ROWS; row++)
            {
                string line = "";
                for (int column = 0; column < COLUMNS; column++)
                {
                    if (column == playerColumn && row == playerRow)
                        line += gubbe.printBlock();

                    else
                        line += map[column, row].printBlock();
                }
                //Console.WriteLine(line);
                buffer += line + "\n";
            }
            Console.CursorLeft = 0;
            Console.CursorTop = 0;
            Console.Write(buffer);

            var key = Console.ReadKey();
            if (key.Key == ConsoleKey.W)
                playerRow--;
            else if (key.Key == ConsoleKey.A)
                playerColumn--;
            else if (key.Key == ConsoleKey.S)
                playerRow++;
            else if (key.Key == ConsoleKey.D)
                playerColumn++;
        }//while
    }//Map

1 个答案:

答案 0 :(得分:2)

您可以通过两种不同的方式检查类型:

第一个选项:

if (map[column, row] is Wall)
{
    // Do something
}

第二个选项:

if (map[column, row].GetType() == typeof(Wall))
{
    // Do something
}