The title summed up what I am trying to figure out.
I am trying to get my int variables to increase and/or decrease depending on what directional key I press.
int x;
int y;
x = 0;
y = 0;
Console.WriteLine("X:" x "Y:" y);
while (Console.Readkey().Key == ConsoleKey.UpArrow)
{
y = 1;
}
If I press the Up arrow nothing happens, if I press any other directional keys it will exit the Console. I fell that I am on the right track because of that alone.
Any help is awesome.
CodePudding user response:
Brackets {}
should appear after a while statement, and the k in "Readkey" should be capitalized (e.g. "ReadKey")
while (Console.ReadKey().Key == ConsoleKey.UpArrow)
{
y = 1;
}
Edit: There was as semi-colon after the while statement, making the loop null. This version should work.
CodePudding user response:
Here you go. I've written this in a way that I'm assuming does what you want it to do.
int x = 0;
int y = 0;
Console.WriteLine("X:" x "Y:" y);
while (true)
{
ConsoleKey key = Console.ReadKey().Key;
Console.Clear();
if (key == ConsoleKey.UpArrow)
{
y = 1;
Console.WriteLine("X:" x "Y:" y);
}
else if (key == ConsoleKey.DownArrow)
{
y -= 1;
Console.WriteLine("X:" x "Y:" y);
}
else if (key == ConsoleKey.RightArrow)
{
x = 1;
Console.WriteLine("X:" x "Y:" y);
}
else if (key == ConsoleKey.LeftArrow)
{
x -= 1;
Console.WriteLine("X:" x "Y:" y);
}
}
It saves the current key in ConsoleKey key
and then checks which direction was pressed, and modifies x or y as necessary.
Note that I also added a Console.Clear()
so everything prints neatly instead of repeatedly one after another.