Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way of shortening my code? [closed]

Tags:

c#

console

new C#er here. I'm making a text based adventure through a console app. I made a map command where when you type "map" it shows you a map with an X indicating your current location. Int variables xCoordinate and yCoordinate are used to represent character location on the map and change by 1 whenever you type "go north" or "go south" etc. The map is 13x10, so there are 130 possible places for your character to be. I made 130 different if statements and it works just fine. My question is if there is a more efficient/easier way of doing this. Here 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 the map typed out 130 times in 130 different if statements, each time the X is somewhere else. I would think there would be a better way to do this, but I have no idea.

like image 201
Jared Price Avatar asked Dec 20 '22 08:12

Jared Price


1 Answers

You should read and learn about loops like for.

Something along 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();
}
like image 157
Alexei Levenkov Avatar answered Jan 08 '23 05:01

Alexei Levenkov