Is there a way to shorten my code?

The new C # er is here. I am doing a text adventure through a console application. I made a map command where, when you enter a "map", it displays a map with an X symbol indicating your current location. The xCoordinate and yCoordinate int variables are used to indicate the location of the symbol on the map and change to 1 when you enter "go north" or "go south", etc. The map is 13x10, so there are 130 possible places for your character. I made 130 different if statements, and this works fine. My question is is there a more efficient / easy way to do this. This is what my code looks like:

public static void Map() { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("\n" + xCoordinate + ", " + yCoordinate); Console.WriteLine("\nTowns are represented by a \"T\". Current location is shown as an \"X\".\n"); Console.ForegroundColor = ConsoleColor.DarkGray; if ((xCoordinate == -7) && (yCoordinate == -4)) { Console.Write("[ ][ ][ ][ ][ ][ ][ ][T][ ][ ][ ][ ][ ] 5\n"); Console.Write("[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] 4\n"); Console.Write("[ ][ ][ ][ ][T][ ][ ][ ][ ][T][ ][ ][ ] 3\n"); Console.Write("[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] 2\n"); Console.Write("[ ][ ][T][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] 1\n"); Console.Write("[T][ ][ ][ ][ ][ ][ ][T][ ][ ][ ][T][ ] 0\n"); Console.Write("[ ][ ][ ][ ][T][ ][ ][ ][ ][ ][ ][ ][ ]-1\n"); Console.Write("[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]-2\n"); Console.Write("[ ][ ][T][ ][ ][ ][T][ ][ ][ ][T][ ][ ]-3\n"); Console.Write("[X][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]-4\n"); Console.Write("-7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5\n\n"); } Console.ForegroundColor = ConsoleColor.White; } 

Again, I have a card printed 130 times in 130 different if operations, each time X is somewhere else. I would have thought that there would be a better way to do this, but I have no idea.

+4
source share
2 answers

You should read and learn about cycles such as for .

Something along the lines

 for(var xCoordinate = -10; xCoordinate <=10; xCoordinate ++) { for(var yCoordinate = 5; yCoordinate >= 5; yCoordinate --) { if (xCoordinate == ... && yCoordinate == ..) { Console.Write("[X]"); } else { Console.Write("[ ]"); } } Console.WriteLine(); } 
+10
source
  public static void Map() { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("\n" + xCoordinate + ", " + yCoordinate); Console.WriteLine("\nTowns are represented by a \"T\". Current location is shown as an \"X\".\n"); Console.ForegroundColor = ConsoleColor.DarkGray; for (int y = 5; y >= -4; y--) { for (int x = -7; x <= 5; x++) { Console.Write(yCoordinate == y && xCoordinate == x ? "[X]" : "[ ]"); } Console.WriteLine(" {0}", y); } Console.Write("-7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5\n\n"); Console.ForegroundColor = ConsoleColor.White; } 
+1
source

Source: https://habr.com/ru/post/1469313/


All Articles