Skip to content

Instantly share code, notes, and snippets.

@anzfactory
Last active August 29, 2015 13:57
Show Gist options
  • Save anzfactory/9498352 to your computer and use it in GitHub Desktop.
Save anzfactory/9498352 to your computer and use it in GitHub Desktop.

Stopwatch

放置ゲーとかでつかえるかもしれない…経過時間管理クラス
気晴らしに書いてみた(笑)

#include "Stopwatch.h"
USING_NS_CC;
using namespace std;
#define StopwatchUDKeyStart "start-time"
#define StopwatchUDKeyElapsed "elapsed-time"
static Stopwatch *s_instande;
Stopwatch* Stopwatch::getInstance()
{
if (! s_instande) {
s_instande = new Stopwatch();
s_instande->init();
}
return s_instande;
}
bool Stopwatch::init()
{
m_startTime = UserDefault::getInstance()->getIntegerForKey(StopwatchUDKeyStart, 0);
m_elapsedTime = UserDefault::getInstance()->getIntegerForKey(StopwatchUDKeyElapsed, 0);
// 設定されていたらチェッカー再開
if (m_startTime > 0 && m_elapsedTime > 0) {
Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(Stopwatch::checker), this, 1.f, false);
}
return true;
}
void Stopwatch::start()
{
startWithElapsedTime(0);
}
void Stopwatch::startWithElapsedTime(int elapsedTime)
{
CCASSERT(! inProgress(), "計測中だよ!一旦stop()して!!");
m_startTime = (int)time(NULL);
m_elapsedTime = elapsedTime;
saveUD();
if (m_elapsedTime > 0) {
Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(Stopwatch::checker), this, 1.f, false);
}
}
int Stopwatch::diff()
{
CCASSERT(inProgress(), "計測開始が記録されていないよ!");
return (int)time(NULL) - m_startTime;
}
int Stopwatch::stop()
{
Director::getInstance()->getScheduler()->unscheduleSelector(schedule_selector(Stopwatch::checker), this);
int dif = diff();
m_startTime = 0;
m_elapsedTime = 0;
saveUD();
return dif;
}
bool Stopwatch::inProgress()
{
return m_startTime > 0;
}
void Stopwatch::saveUD()
{
UserDefault::getInstance()->setIntegerForKey(StopwatchUDKeyStart, m_startTime);
UserDefault::getInstance()->setIntegerForKey(StopwatchUDKeyElapsed, m_elapsedTime);
UserDefault::getInstance()->flush();
}
void Stopwatch::checker(float dt)
{
if (m_elapsedTime > diff()) {
return;
}
log("Stopwatch : call stop");
NotificationCenter::getInstance()->postNotification(StopwatchNotificationPost);
}
#include "cocos2d.h"
#define StopwatchNotificationPost "stopwatch-alerm" // 通知名
class Stopwatch : public cocos2d::Object
{
public:
Stopwatch() {}
virtual ~Stopwatch() {}
virtual bool init();
static Stopwatch* getInstance();
CC_SYNTHESIZE(int, m_startTime, StartTime); // 計測開始のタイムスタンプ
CC_SYNTHESIZE(int, m_elapsedTime, ElapsedTime); // 経過秒数(通知条件指定)
void start(); // 計測開始
void startWithElapsedTime(int elapsedTime); // 計測開始(通知条件セット)
int diff(); // 現時点での経過秒数
int stop(); // 計測終了
bool inProgress(); // 計測中?
protected:
private:
void saveUD(); // UserDefault保存処理
void checker(float dt); // schedulerによる経過秒数チェック&通知
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment