How can I get the time of each game round? 【CCTime】【CCUserDefault】

Hi guys,

I’m trying to display the time of each game round. Can anyone told me how to use CCTime to get time and save via CCUserDefaut so that could be enquired later in the menu.

Thanks,

I’m going to do the same thing but was going to use time_t type (and store it somewhere else).
Should CCUserDefault be used for something like per level values?

Store the start time when the level starts - time(&startTime)

then in the level complete - time(&endTime)

Total Time would then be time = difftime(endTime, startTime).

The only problem… what if the level is paused?

The other thing I thought of… what about just storing the total of all milliseconds passed in to my update/tick function.
That is not called when the game is paused so should be correct?

Adam Reed wrote:

I’m going to do the same thing but was going to use time_t type (and store it somewhere else).
Should CCUserDefault be used for something like per level values?
>
Store the start time when the level starts - time(&startTime)
>
then in the level complete - time(&endTime)
>
Total Time would then be time = difftime(endTime, startTime).
>
The only problem… what if the level is paused?
>
The other thing I thought of… what about just storing the total of all milliseconds passed in to my update/tick function.
That is not called when the game is paused so should be correct?

Hi Adam,
I finally get the way to figure out the time. You can try CCTime::gettimeofdayCocos2d. It will help you to get the current time.
@ //When Game Over
struct cc_timeval now;
*endTime = CCTime::gettimeofdayCocos2d;
*endTime = (now.tv_sec * 1000 + now.tv_usec / 1000);
*realTime =*endTime - *startTime;
sprintf: %d", *realTime);
@
To take game pause into consideration, may you can cut the timeline:
//Pause happen, Get the pause time
*pauseTime = CCTime::gettimeofdayCocos2d;
*realTime = *pauseTime -*startTime;

//Restart
*startTime = CCTime::gettimeofdayCocos2d;
*realTime +=*endTime-*startTime

May this works.

You could do something like this: have a global variable (or static, or whatever) that holds the elapsed game time and in your update method increment it with the deltaTime:

float elapsedTime=0;

// at game start
elapsedTime=0;

void Game::update(float deltaTime)
{
     if (paused)
        return;

     //...
     elapsedTime+=deltaTime;
     //...
}

this will eliminate the game paused issue.

Also in my oppinion it’s ok to use CCUserDefault for scoring/timing level

Exactly what I was thinking.

I assume update/tick can be trusted to pass in the correct elapsed time, everytime?

From our experience yes, it’s stable.

See this post regarding the millisecond math of the now function:

http://www.cocos2d-x.org/boards/6/topics/23011?r=30547#message-30547