Paul Mel Paul Mel - 3 years ago 230
C# Question

C# console game space invader

Hey there, im writting a code with an Space ship but i cant move it to the left or right, and i wanted to ask if maybe somebody could help me because i dont understand it. And i tried some things like to write it in a other way but it dont works, im new to programming probably u can see it by the way i wrote my code.

string player = @"
^
o
| o |
/\\\o///\
</o\>";
char laser = '|';
int moves = 0;
int xlaser = rnd.Next(width), ylaser = rnd.Next(hight);
WriteHere(xlaser, ylaser, laser);
WriteHere(x, y, player);
// game loop
do
{

Console.SetCursorPosition(0, 0);

if (Console.KeyAvailable)
{
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.UpArrow:
{
if (y > 0)
{
//y -= 1;
y--; // ist //y = y - 1;
}
moves++;
}
break;

case ConsoleKey.DownArrow:
{
if (y < hight - 1)
{
y++; // ist y = y + 1;
}
moves++;
}
break;

case ConsoleKey.LeftArrow:
{
if (x > 0)
{
x--;
}
moves++;
}
break;

case ConsoleKey.RightArrow:
{
if (x < width - 1)
{
x++;
}
moves++;
}
break;
}

Console.Clear();
Writehere(x, y, player);

Answer Source

If you define your player string without whitespace and write it to the console line by line it works. I'm sure there are better solutions but as a quick resolve this might be ok.

Replace WriteHere with this code

static void WriteHere(int x, int y, string s)
{
    foreach (var line in s.Split('\n'))
    {
        Console.SetCursorPosition(x, y);
        Console.Write(line);
        y++;
    }
}

And for the player, instead of

            string player = @"
                            ^
                            o
                          | o |
                        /\\\o///\
                          </o\>";

Do it like this (note the difference in whitespace on the left).

            string player = @"
    ^
    o
  | o |
/\\\o///\
  </o\>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download