Search code examples
c#roguelike

X and Y Axis Indices in List<string> for Roguelike


After analyzing a snippet of code from this link (the C# portion), I tried doing this on my own for some practice.
However, I'm confused about how the portion below translates to an X,Y index in the string list, and why the if() statement has the Y index before the X.

if (Map[playerY][playerX] == ' ')

Here's what the list looks like:

List<string> Map = new List<string>()
        {
            "##########",
            "#        #",
            "#   >    #",
            "#   >    #",
            "#        #",
            "##########"
        };

Any help would be appreciated, thank you in advance!


Solution

  • Because strings are arrays themselves, calling an indexer function such as: string[n] will get the character at position n.

    So when you are trying to get the character the player is on, you get the Y coordinate by indexing the array of strings, because the first string in the array is the top row of the map.

     Y |
    ------------------
     0 | ##########
     1 | #        #
     2 | #   >    #
     3 | #   >    #
     4 | #        #
     5 | ##########
    

    We then pick out the X by matching it to the character at the X position in the string:

     X | 0123456789
    ------------------
       | ##########
       | #        #
       | #   >    #
       | #   >    #
       | #        #
       | ##########
    

    So [Y,X] will get the appropriate character.