0

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. timer running

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
  • 2
    This may help, [how-can-i-update-the-current-line-in-a-c-sharp-windows-console-app](https://stackoverflow.com/questions/888533/how-can-i-update-the-current-line-in-a-c-sharp-windows-console-app), but I would suggest creating a different application for this, such as a WPF application or web page so you can utilize some of the native UI elements. – Ryan Wilson Feb 03 '22 at 04:43
  • Hey @RyanWilson. I have already put /r at the beginning of the `Console.Write()`. – SabBab Feb 04 '22 at 01:27

0 Answers0