How to create a simple time counter?
Hi!
How can I create a simple clock (hh:mm:ss format) just to count the elapsed time since the beginning of each level of my game?
Thanks!
PS.: I'm using Visual C++ 6 and SDL.
Record the time at the start of your level using time(NULL), and then every frame get the current time. Subtract the start time from the current time, and format it.
Here's some source:
Here's some source:
// At the start of your level, save this value somewhere (global or preferably a member varaible):time_t m_timeStart = time(NULL);// Every frame get the current time:time_t timeCurr = time(NULL);time_t timeTaken = timeCurr-m_timeStart;// Format the time into a string:int nHours = timeTaken/(60*60);timeTaken -= (nHours*60*60);int nMins = timeTaken/60;timeTaken -= (nMins*60);char szTime[16];sprintf("%02d:%02d:%02d",nHours,nMins,timeTaken);// Display szTime somehow (However you display text in SDL)
#include <ctime>class Timer{public: Timer() { StartTime = clock(); } int getHours() { return getMinutes()/60; } int getMinutes() { return getSeconds()/60; } int getSeconds() { return (clock()-StartTime)/1000; } private: clock_t StartTime};
Thats just a rogh outline. I only just wrote it and I hven't tested it, but it should be enough to give you the general idea.
Sorry. Wasn't really thinking.
class Timer{private: clock_t StartTime; enum TimeValues { MillisecsPerSec = 1000, SecsPerMin = 60, MinsPerHour = 60, MillisecsPerMin = MillisecsPerSec*SecsPerMinute, MillisecsPerHour= MillisecsPerMin*MinsPerHour };public: Timer() { StartTime = clock(); } int getHours() { return (clock()-StartTime)/MillisecsPerHour; } int getMinutes() { return (clock()-StartTime)/MillisecsPerMin; } int getSeconds() { return (clock()-StartTime)/MillisecsPerSec; }
I love you all!
Here is my class:
timer.hpp
timer.cpp
Thanks a lot!!!
Here is my class:
timer.hpp
#ifndef TIMER_HPP#define TIMER_HPP#include <time.h>class C_Timer {private: clock_t startTime; const unsigned int millisecsPerSec; const unsigned int secsPerMin; const unsigned int minsPerHour; const unsigned int millisecsPerMin; const unsigned int millisecsPerHour;public: C_Timer(); unsigned int getHours() const; unsigned int getMinutes() const; unsigned int getSeconds() const;};#endif
timer.cpp
#ifndef TIMER_HPP #include "timer.hpp"#endifC_Timer::C_Timer() : millisecsPerSec( 1000 ), secsPerMin( 60 ), minsPerHour( 60 ), millisecsPerMin( millisecsPerSec * secsPerMin ), millisecsPerHour( millisecsPerMin * minsPerHour ) { startTime = clock(); } unsigned int C_Timer::getHours() const { return (clock() - startTime) / millisecsPerHour;}unsigned int C_Timer::getMinutes() const { return (clock() - startTime) / millisecsPerMin;}unsigned int C_Timer::getSeconds() const { return (clock() - startTime) / millisecsPerSec;}
Thanks a lot!!!
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement