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?
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();
}
}
}
}