Question

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!

Was it helpful?

Solution 2

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.

OTHER TIPS

The first [ ] picks one string from the array. The second [ ] picks a character from the string.

The Y index selects which string, as you would expect from a List. The X index actually picks a character from that string. This wouldn't work on a List of, say, ints, because this example is actually using the [] operator on the List and then using it again on the String the List returns.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top