Search code examples
c#timer

How do I fix my timer so it counts in seconds?


I want my game's screen to have a timer on screen that shows how many seconds have passed (representing the player's point score). I am able to get the timer on screen, however, the counter freaks out and my console doesn't print the result correctly either. Any ideas?

I've tried to use timer.Elapsed however SplashKit (what i must use) does not seem to recognise that.

Sorry if this is a repeated question, I am new to programming and have searched around but couldn't find anything I could comprehend/assist.

    public void Timer()
        {
            //begin timer and print results
            timer.Start();

            //write to console how many milliseconds have passed, and divide by 1000 for seconds.
            Console.WriteLine($":{timer.Ticks} milliseconds have passed");
            Console.WriteLine($"which is {timer.Ticks /1000} seconds");

            //covert timer.Ticks to string and store into string 'score
            score = Convert.ToString(timer.Ticks);

            //assign font 
            Font Quicksand = SplashKit.LoadFont("Quicksand", "Resources\\fonts\\Quicksand-Regular.otf");
            //use SplashKit to print to screen.. 
            SplashKit.DrawText(score, Color.Black, Quicksand, 70, 700, 900);
        }

Solution

  • +1 to Eric j's comment- all the Timer types the framework that I know of are not for providing stopwatch style "the game has been running 5 minutes" type functions directly themselves. They're classes that raise an event at some predefined interval. The actual timing of the game, if using a Timer, would be done by you by recording the start time and differencing the time now to it upon the timer elapsing it's interval:

    public class Whatever{
      private Timer _t = new Timer();
      private DateTime _start;
    
      public Whatever(){ //constructor
        _t.Elapsed += TimerElapsed; //elapsed event handled by TimerElapsed method
        _t.Interval = 1000; //fire every second 
      }
    
      public void StartGame(){
        _start = DateTime.UtcNow;
        _t.Start();
      }
    
      private void TimerElapsed(){
    
        Console.WriteLine("Game has been running for " + (DateTime.UtcNow - _start));
    
      }
    

    The timer interval merely controls how often the clock will update on screen. If you're offering game times of 10.1,10.2 seconds etc then make the timer interval less than 100 (updates more than once every 0.1 seconds) for example