Search code examples
c#user-inputincrementdecrement

C# My code has a problem taking input and will not start incrementing or decrementing until a button is hit twice nor are my ><= statements working


Here is what is happening.

First issue is:

I need to press a directional button twice to start incrementing and/or decrementing the x and y variables.

If I change directions for an ex.

From Right to Left, the x variable will increment once more before it'll start decrementing.

The Second Issue:

I have time based on current x and y of player.

However when I go above 2000 the time does not change until 2001.

If I go back down to 1999 the time doesn't change until 1998...

This was the same thing even when my code said

if(y>=0 && y< 2000) It was the same issue, I thought taking 2000 and making it 1999 would fix that and it did not.

I do not know what is causing either of these issues and I have tried to figure it out... If anyone knows why it is happening like that, I would love to know.

int x = 1995;
int y = 0;
int time = 0;

Console.WriteLine("X: 0Y: 0Time: 0");

while(true){
   ConsoleKey key = Console.ReadKey().Key;
   Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop -1);
   Console.WriteLine($"X: {x,6} Y:{y,6} Time: {time,3}");
   Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop +1);
   //Change Timezones
   if (x >=0 && x< 1999){
      time=0;
   }
   else if (x>=2000 && x< 3999){
      time=1;
   }
   ....
   //Movement   
   if (key == ConsoleKey.LeftArrow){
      x=x-1;
   }
   else if (key == ConsoleKey.RightArrow){
      x=x+1;
   }

   ....
}

Solution

  • Problem 1 "From Right to Left, the x variable will increment once more before it'll start decrementing."

    That's because you print out the value of the previous iteration rather than the new value. Move your Console.WriteLine to the end of the script and it'll show you the updated value

    Problem 2 "However when I go above 2000 the time does not change until 2001."

    This is caused by the same thing as problem 1 most likely. It could also be caused by the fact you might be changing the value of x after running the change timezone codeblock. Be sure the ordering of your logic is correct.

    Problem 3 "If I go back down to 1999 the time doesn't change until 1998"

    There's a gap between the values in your logic. You have x < 1999 in your first timezone codeblock, and x >= 2000 in your second timezone codeblock. That means if you start at 2003 for example and go down in value, the time will only change when you reach 1998 because of the x < 1999 part. There's a value that won't trigger a change when decrementing nor incrementing, 1999.