0

Trying to make snake game. I am using Console.SetCursorPosition(int x, int y) to draw body parts("O"), 2D array to store "O" previous locations and Console.KeyAvailable to detect direction changes. When a key is pressed that is not in the switch statement, drawing stops for one iteration. When a key is pressed that is in the switch statement, Console erases oldest body part.

Debugger doesn't show the reason. Can anyone help me to understand why is that happening?

static void Main(string[] args)
{
    Console.CursorVisible = false;

    while (true)
    {
        ConsoleKey key = Console.ReadKey().Key;
        switch (key)
        {
            case ConsoleKey.RightArrow:
                direction = "RIGHT";
                break;
            case ConsoleKey.LeftArrow:
                direction = "LEFT";
                break;
            case ConsoleKey.DownArrow:
                direction = "DOWN";
                break;
            case ConsoleKey.UpArrow:
                direction = "UP";
                break;
        }

        breakOut = false;

        switch (direction)
        {
            case "RIGHT":
                for (int i = x; i <= 100; i++)
                {
                    Iterator(i, y);
                    x = i;
                    if (breakOut)
                        break;
                };
                break;
            case "LEFT":
                break;
            case "DOWN":
                for (int i = y; i <= 100; i++)
                {
                    Iterator(x, i);
                    y = i;
                    if (breakOut)
                        break;
                }
                break;
            case "UP":
                break;
        }
    }
}

static void Iterator(int x, int y)
{
    Draw(x, y);

    xSlot = x;
    ySlot = y;

    histPoints[slotCounter, (int)place.x] = xSlot;
    histPoints[slotCounter, (int)place.y] = ySlot;

    if (slotCounter >= length)
    {
        Erase(histPoints[slotCounter - length, (int)place.x], histPoints[slotCounter - length, (int)place.y]);
    }

    slotCounter += 1;

    if (Console.KeyAvailable)
    {
        breakOut = true;
        return;
    }

    Sleep();
}
hasanovs
  • 33
  • 2
  • Hard to tell without seeing the full code. The double switch statement is redundant by the way, you could just put it into one. – Innat3 Sep 27 '19 at 09:39
  • @Innat3 Missing parts just consists of Console.SetCursorPosition() and Console.Write(). Oh, and Sleep() is Thread.Sleep(500). – hasanovs Sep 27 '19 at 09:59
  • set a default value for `direction` – Stefan Sep 27 '19 at 10:02

0 Answers0