2

I am creating a quiz with a timer. After asking for the number of questions they want to answer and the time for answering the questions, I would like to show a timer that keeps counting down on the same line. Below the timer I would like to show all the quiz questions.

However every time a question is asked, the timer appears on the new line.

I have already tried following this question, but it doesn't fix my problem. How can I update the current line in a C# Windows Console App?

enter image description here

public class GamePlay
{
    private static int _secondPassed;
    private static int _timeForAnswering;
    private static bool _isTimerFinished;

    private static void Timing()
    {
        Timer timer = new Timer(TimerCallback, null, 0, 1000);
        Console.ReadKey();
    }

    private static void TimerCallback(Object o)
    {
        if (_secondPassed >= _timeForAnswering)
        {
            _isTimerFinished = true;
        }
        else
        {
            _isTimerFinished = false;
            _secondPassed++;
            Console.Write($"\rYou have {_timeForAnswering - _secondPassed} seconds left.");
        }
    }

    public static async Task PlayGame(int numberOfQuestions, int timeForAnswering)
    {
        _timeForAnswering = timeForAnswering;
        Random random = new Random();
        await Task.Run(() => Timing());
        for (int q = 1; q < numberOfQuestions + 1; q++)
        {
            if (_isTimerFinished)
            {
                Console.WriteLine();
                Console.WriteLine("Game Over!");
                break;
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine(/* Ask Question */);
                // Get Answer
                double usersAnswer = Console.ReadLine();
            }
        }
    }
}
SabBab
  • 41
  • 3

1 Answers1

0

Console.SetCursorPosition is the way to go. With that you can modify any line in the Console.

https://learn.microsoft.com/de-de/dotnet/api/system.console.setcursorposition?view=net-6.0

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Michi
  • 1
  • 1
  • 1
    and heres the English version https://learn.microsoft.com/en-us/dotnet/api/system.console.setcursorposition?view=net-6.0 – pm100 Feb 07 '22 at 02:09
  • I have already tried that, but is there a way to reset the cursor so the cursor appears on the last line? – SabBab Feb 08 '22 at 02:40