0

I'm creating a maze game in a 2d array but i can't figure out how to make walls/doors/etc to work. I'm thinking that when i press 'W' it will change the position of the character only if the next position isnt a wall. How do i check that? Here's my code for the map and the movement:

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
Yaman Jain
  • 1,254
  • 11
  • 16
anek05
  • 19
  • 5

1 Answers1

2

You could check the type in two different ways:

1st option:

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

2nd option:

if (map[column, row].GetType() == typeof(Wall))
{
    // Do something
}
Alex Sanséau
  • 8,250
  • 5
  • 20
  • 25
  • Correctly answered by @Alex, as you need to check the type of next block at runtime and then take action acc. – Ipsit Gaur Sep 28 '17 at 09:56
  • I later wanna add rooms to the map with doors. So how do i implement this when the map is not only an empty rectangle? – anek05 Sep 28 '17 at 09:58
  • That sounds like a different question now.... and I'm sorry but I won't be able to tell you how to write the game. – Alex Sanséau Sep 29 '17 at 10:31