程序入口main.cpp
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
...
// create the application instance
AppDelegate app;
...
return CCApplication::sharedApplication()->run();
}
以上两行是关键代码
(1)代码AppDelegate app;调用了AppDelegate的构造函数,而它的父类是CCApplication,所以CCApplication的构造函数也被调用了
CCApplication::CCApplication()
: m_hInstance(NULL)
, m_hAccelTable(NULL)
{
m_hInstance = GetModuleHandle(NULL);
m_nAnimationInterval.QuadPart = 0;
CC_ASSERT(! sm_pSharedApplication);
sm_pSharedApplication = this;
}
这里完成了AppDelegate和CCApplication之间的联系,由于AppDelegate是CCApplication的子类,故CCApplication里面的静态单例指针指的便是AppDelegate的实例。之后调用CCApplication::sharedApplication()的相关操作是基于AppDelegate的实现。
(2)代码CCApplication::sharedApplication()->run();调用了下面的代码
int CCApplication::run()
{
...
// Initialize instance and cocos2d.
if (!applicationDidFinishLaunching())
{
return 0;
}
..
while (1)
{
if (! PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// Get current time tick.
QueryPerformanceCounter(&nNow);
// If it's the time to draw next frame, draw it, else sleep a while.
if (nNow.QuadPart - nLast.QuadPart > m_nAnimationInterval.QuadPart)
{
nLast.QuadPart = nNow.QuadPart;
CCDirector::sharedDirector()->mainLoop();
}
else
{
Sleep(0);
}
continue;
}
if (WM_QUIT == msg.message)
{
// Quit message loop.
break;
}
// Deal with windows message.
if (! m_hAccelTable || ! TranslateAccelerator(msg.hwnd, m_hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
在这里,run()函数里面是一个while死循环,不过里面有判断条件 if (WM_QUIT == msg.message)可以跳出循环,终止程序。循环里面每隔一段时间m_nAnimationInterval就调用CCDirector::sharedDirector()->mainLoop(),完成游戏的刷新。