variablesintegerconsole.readkey

How do I add to my int variables when I press a key?


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.


Solution

  • 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; 
    
    while (true)
    {
        Console.WriteLine("X:" + x + "Y:" + y);
        ConsoleKey key = Console.ReadKey().Key;
        Console.Clear();
        if (key == ConsoleKey.UpArrow)
        {
            y += 1;
        }
        else if (key == ConsoleKey.DownArrow)
        {
            y -= 1;
        }
        else if (key == ConsoleKey.RightArrow)
        {
            x += 1;
        }
        else if (key == ConsoleKey.LeftArrow)
        {
            x -= 1;
        }
    }
    

    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.