void OTClientConnection::ProcessBuffer() { if (!m_bHaveHeader) { int err = 0, nread = 0; union u_header theCMD; // clear the header object. memset((void *)theCMD.buf, 0, OT_CMD_HEADER_SIZE); // Read the header for (nread = 0; nread < OT_CMD_HEADER_SIZE; nread += err) { err = SFSocketRead(m_pSocket, theCMD.buf + nread, OT_CMD_HEADER_SIZE - nread); #ifdef _WIN32 if (0 == err || SOCKET_ERROR == err) // 0 is a disconnect. error is error. otherwise err contains bytes read. #else if (err <= 0) #endif { break; } else { OTLog::Output(2, "Reading input from socket...\n"); } } if (nread == OT_CMD_HEADER_SIZE) { uint32_t lOldSize = theCMD.fields.size; uint32_t lSize = ntohl(lOldSize); // think this might be causing some problems... maybe not. theCMD.fields.size = lSize; // fix the byte order. m_CMD = theCMD; // grab a copy of the header m_bHaveHeader = true; // We need to remember that we are now in "header mode" int nChecksum = theCMD.fields.checksum; OTLog::vOutput(2, "\n************************************************************\n===> Reading header from client message.\n" "First 9 bytes are: %d %d %d %d %d %d %d %d %d.\nSize is: %d...\n", theCMD.buf[0],theCMD.buf[1],theCMD.buf[2],theCMD.buf[3],theCMD.buf[4], theCMD.buf[5], theCMD.buf[6], theCMD.buf[7], theCMD.buf[8], lSize); OTLog::vOutput(2, "\nCMD HEADER: CMD TYPE: %d -- CMD NUM: %d\n" "PAYLOAD SIZE: %d -- CHECKSUM: %d\n", theCMD.fields.type_id, theCMD.fields.command_id, lSize, nChecksum); ReadBytesIntoBuffer(); // When the server knows for SURE it is receiving a message, // then wait for 1 second to make sure we have the entire payload // at once. // TODO: rewrite socket code so that if a complete command has not yet // come in, to buffer the data and wait until next time around the loop. // Because right now, if you have a partial command, it reads it as an error // and returns, discarding what had already been read. Obviously that will // not work for a real server. // In the meantime, this sleep allows me to do testing by insuring that, // with a second's wait, the server will have time to read the entire message. // sleep(1); // ProcessMessage(theCMD); } } else { // If we've finally read enough into our buffer to process the entire mesage, then process it. if (m_Buffer.GetSize() >= m_CMD.fields.size) { ProcessMessage(m_CMD); m_bHaveHeader = false; } // otherwise if we haven't read enough, just read a bit more and wait until next time. else ReadBytesIntoBuffer(); } }
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { ChangeWindowMode(TRUE); //SetMouseDispFlag(TRUE); SetDrawMode(DX_DRAWMODE_BILINEAR); SetScreenMemToVramFlag(FALSE); SetAlwaysRunFlag(TRUE); SetDrawScreen( DX_SCREEN_BACK); if(DxLib_Init()==-1) // DXライブラリ初期化処理 { return -1 ; // エラーが起きたら直ちに終了 } //デバック用にコンソールを出現させる /* AllocConsole(); freopen("CONOUT$","w",stdout); freopen("CONIN$","r",stdin);z */ Mode gamemode=OPENING; AI_T ai[AI_NUM]; int death[AI_NUM]={0}; Tagger tagger[TAGGER_NUM]; int tagger_num = 0; int STAGE[WIDTH][HEIGHT]={0}; int round=0; int start=0; int end=0; int StartTime,TimeLimit; for(int i=0;i<AI_NUM;i++){ ai[i].entry=1; } ai[0].entry=0; while(ProcessMessage()!=-1){ int speed=0; switch(gamemode){ case OPENING: start=intro(ai); if(start==1)gamemode=SETTING; break; case SETTING: make_Stage(STAGE);//マップ構成 tagger_num = init_Tagger(tagger,STAGE);//鬼の初期化 //tagger_numは鬼の要素番号 init_Ai(ai,STAGE); round++; TimeLimit=TIME_LIMIT*60*79;//ゲーム開始時の時刻に合わせる gamemode=RUNNING; break; case RUNNING: TimeLimit-=79; if(TimeLimit<0)TimeLimit=0; if(tagger[tagger_num].step==0){ //tagger[tagger_num].act=next_Tagger(tagger[tagger_num],STAGE,ai); tagger[tagger_num].act=tagger[tagger_num].moveFunc(tagger[tagger_num].x,tagger[tagger_num].y,STAGE); //AIと一緒で、moveFunc使う } for(int i=0;i<AI_NUM;i++){ if(ai[i].step==0 && ai[i].entry==1){ setview_Ai(&ai[i],STAGE); //ai[i].act=next_Ai(ai[i].view); //henteko : 下のmoveFunc()を使うためコメントアウト ai[i].act = ai[i].moveFunc(ai[i].view); } } if(TimeLimit>TIME_LIMIT*45*79)speed=0; else if(TimeLimit>TIME_LIMIT*30*79)speed=1; else if(TimeLimit>TIME_LIMIT*15*79)speed=1; else speed=3; update_Tagger(&tagger[tagger_num],STAGE,speed); for(int i=0;i<AI_NUM;i++){ if(ai[i].entry==1) update_Ai(&ai[i],STAGE); } update_stage(STAGE,ai,tagger[tagger_num]); ClearDrawScreen(); draw(STAGE,ai,tagger[tagger_num]); DrawFormatString(30,30,GetColor(0,255,255),"ROUND%d",round); DrawFormatString(500,15,GetColor(0,255,0),"TIME %d",TimeLimit); if(1){ for(int i=0;i<AI_NUM;i++){ if(death_Ai(ai[i],tagger[tagger_num])==1 && ai[i].entry==1){ death[i]++; DrawBox(0,230,640,260,GetColor(0,0,0),1); DrawBox(-1,230,642,260,GetColor(255,0,0),0); DrawFormatString(100,240,GetColor(255,0,0),"%sがつかまりました",ai[i].name);// 8/3 zero追記:AI捕獲の宣言をまとめた。 WaitTimer(3000); if(round>=ROUND_MAX){ gamemode=ENDING; } else{ gamemode=SETTING; } break; } } } if(TimeLimit<=0){// 8/3 zero追記:タイムアップを設定 round--; DrawString(100,240,"時間切れです",GetColor(255,0,0)); WaitTimer(3000); if(round>=ROUND_MAX){ gamemode=ENDING; } else{ gamemode=SETTING; } break; } if(CheckHitKey(KEY_INPUT_R)==1){ gamemode=SETTING; } break; case ENDING: end=ranking(ai,death); break; default: break; } if(end==1 || CheckHitKey(KEY_INPUT_ESCAPE))break; ScreenFlip(); } DxLib_End() ; // DXライブラリ使用の終了処理 return 0 ; // ソフトの終了 }
int globalwindowhandler::GetKey(truth EmptyBuffer) { SDL_Event Event; if(EmptyBuffer) { while(SDL_PollEvent(&Event)) ProcessMessage(&Event); KeyBuffer.clear(); } for(;;) if(!KeyBuffer.empty()) { int Key = KeyBuffer[0]; KeyBuffer.erase(KeyBuffer.begin()); if(Key > 0xE000) return Key - 0xE000; if(Key && Key < 0x81) return Key; } else { if(SDL_PollEvent(&Event)) ProcessMessage(&Event); else { #if SDL_MAJOR_VERSION == 1 if(SDL_GetAppState() & SDL_APPACTIVE #else if(SDL_GetWindowFlags(graphics::Window) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS) #endif && Controls && ControlLoopsEnabled) { static ulong LastTick = 0; UpdateTick(); if(LastTick != Tick) { LastTick = Tick; truth Draw = false; for(int c = 0; c < Controls; ++c) if(ControlLoop[c]()) Draw = true; if(Draw) graphics::BlitDBToScreen(); } SDL_Delay(10); } else { SDL_WaitEvent(&Event); ProcessMessage(&Event); } } } }
void GetSecondaryFileList(HWND hwndLV, int *items, BOOL changed) { DWINFO *ptr; MSG msg; MsgWait(ewSem, INFINITE); ptr = editWindows; while (ptr) { ptr->deferClose = TRUE; ptr = ptr->next; } SetEvent(ewSem); ptr = editWindows; while (ptr) { if (!ptr->inSaveDialog) { int rv = FALSE; if (changed) { FILETIME time; int a = FileAttributes(ptr->dwName); rv = FALSE; if (a == - 1) a = 0; if (FileTime(&time, ptr->dwName)) { rv = (time.dwHighDateTime != ptr->time.dwHighDateTime || time.dwLowDateTime != ptr->time.dwLowDateTime); ptr->time = time; } if (a &FILE_ATTRIBUTE_READONLY) SendMessage(ptr->dwHandle, EM_SETREADONLY, 1, 0); else SendMessage(ptr->dwHandle, EM_SETREADONLY, 0, 0); } else { rv = SendMessage(ptr->dwHandle, EM_GETMODIFY, 0, 0); } if (rv) { int v; LV_ITEM item; struct saveData *sd = calloc(1, sizeof(struct saveData)); if (sd) { sd->asProject = FALSE; sd->data = ptr; memset(&item, 0, sizeof(item)); item.iItem = (*items)++; item.iSubItem = 0; item.mask = LVIF_PARAM; item.lParam = (LPARAM)sd; item.pszText = ""; // LPSTR_TEXTCALLBACK ; v = ListView_InsertItem(hwndLV, &item); ListView_SetCheckState(hwndLV, v, TRUE); } } } ptr = ptr->next; } ptr = editWindows; while (ptr) { HWND xx = ptr->self; ptr = ptr->next; PostMessage(xx, WM_DEFERREDCLOSE, 0, 0); } while (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) ProcessMessage(&msg); }
void tTVPApplication::ProcessMessages() { MSG msg = {0}; while(ProcessMessage(msg)); }
SInt64 EasyCMSSession::Run() { OSMutexLocker locker(&fMutex); OS_Error theErr = OS_NoErr; EventFlags events = this->GetEvents(); if ((events & Task::kTimeoutEvent) || (events & Task::kKillEvent)) fLiveSession = false; while (fLiveSession) { switch (fState) { case kIdle: { //根据事件类型执行不同的动作 if (events & Task::kStartEvent) { switch (fEasyMsgType) { case MSG_CS_FREE_STREAM_REQ: { CSFreeStream(); break; } default: break; } } if (events & Task::kReadEvent) { // 已连接,有新消息需要读取(数据或者断开) fState = kReadingMessage; } // 如果有消息需要发送则进入发送流程 if (fOutputStream.GetBytesWritten() > 0) { fState = kSendingMessage; } //当前状态没有进行数据发送,则等待下一次事件触发 if (kIdle == fState) { return 0; } break; } case kReadingMessage: { // 网络请求报文存储在fInputStream中 if ((theErr = fInputStream.ReadRequest()) == QTSS_NoErr) { //如果RequestStream返回QTSS_NoErr,就表示已经读取了目前所到达的网络数据 //但!还不能构成一个整体报文Header部分,还要继续等待读取... fSocket->GetSocket()->SetTask(this); fSocket->GetSocket()->RequestEvent(EV_RE); fState = kIdle; return 0; } if ((theErr != QTSS_RequestArrived) && (theErr != E2BIG) && (theErr != QTSS_BadArgument)) { //Any other error implies that the input connection has gone away. // We should only kill the whole session if we aren't doing HTTP. // (If we are doing HTTP, the POST connection can go away) Assert(theErr > 0); // If we've gotten here, this must be an HTTP session with // a dead input connection. If that's the case, we should // clean up immediately so as to not have an open socket // needlessly lingering around, taking up space. Assert(!fSocket->GetSocket()->IsConnected()); //this->ResetClientSocket(); //return 0; //读取数据失败,直接进入析构 } // 网络请求超过了缓冲区,返回Bad Request if ((theErr == E2BIG) || (theErr == QTSS_BadArgument)) { //返回HTTP报文,错误码408 //(void)QTSSModuleUtils::SendErrorResponse(fRequest, qtssClientBadRequest, qtssMsgBadBase64); fState = kCleaningUp; } else { fState = kProcessingMessage; } break; } case kProcessingMessage: { // 处理网络报文 Assert(fInputStream.GetRequestBuffer()); Assert(fRequest == NULL); // 根据具体请求报文构造HTTPRequest请求类 fRequest = NEW HTTPRequest(&QTSServerInterface::GetServerHeader(), fInputStream.GetRequestBuffer()); // 清空发送缓冲区 fOutputStream.ResetBytesWritten(); Assert(theErr == QTSS_RequestArrived); // 处理收到的具体报文 ProcessMessage(); // 每一步都检测响应报文是否已完成,完成则直接进行回复响应 if (fOutputStream.GetBytesWritten() > 0) { fState = kSendingMessage; } else { fState = kCleaningUp; } break; } case kSendingMessage: { //发送响应报文 theErr = fOutputStream.Flush(); if (theErr == 115) { fSocket->GetSocket()->SetTask(this); fSocket->GetSocket()->RequestEvent(EV_WR); this->ForceSameThread(); return 0; } if (theErr == EAGAIN || theErr == EINPROGRESS) { // If we get this error, we are currently flow-controlled and should // wait for the socket to become writeable again // 如果收到Socket EAGAIN错误,那么我们需要等Socket再次可写的时候再调用发送 fSocket->GetSocket()->SetTask(this); fSocket->GetSocket()->RequestEvent(fSocket->GetEventMask()); this->ForceSameThread(); // We are holding mutexes, so we need to force // the same thread to be used for next Run() return 0; } else if (theErr != QTSS_NoErr) { // Any other error means that the client has disconnected, right? Assert(!this->IsConnected()); //向服务器发送数据失败,直接进入析构 //ResetClientSocket(); return -1; } fState = kCleaningUp; break; } case kCleaningUp: { // 一次请求的读取、处理、响应过程完整,等待下一次网络报文! this->CleanupRequest(); fState = kIdle; if (IsConnected()) { fSocket->GetSocket()->SetTask(this); fSocket->GetSocket()->RequestEvent(EV_RE | EV_WR);//网络事件监听 } return 0; } } } return -1; }
bool _LoopProc() { return ScreenFlip() == 0 && ProcessMessage() == 0 && ClearDrawScreen() == 0; }
int BaseScene::processLoop(){ if(ProcessMessage() != 0) return -1; //プロセス処理がエラーなら-1を返す if(ClearDrawScreen() != 0) return -1; //画面クリア処理がエラーなら-1を返す if(Keyboard::update() != 0) return -1; //キーのアップデート処理がエラーなら-1を返す return 0; }
static HRESULT RunApplication( __in BURN_ENGINE_STATE* pEngineState, __out BOOL* pfReloadApp ) { HRESULT hr = S_OK; DWORD dwThreadId = 0; IBootstrapperEngine* pEngineForApplication = NULL; BOOL fStartupCalled = FALSE; BOOL fRet = FALSE; MSG msg = { }; ::PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); dwThreadId = ::GetCurrentThreadId(); // Load the bootstrapper application. hr = EngineForApplicationCreate(pEngineState, dwThreadId, &pEngineForApplication); ExitOnFailure(hr, "Failed to create engine for UX."); hr = UserExperienceLoad(&pEngineState->userExperience, pEngineForApplication, &pEngineState->command); ExitOnFailure(hr, "Failed to load UX."); fStartupCalled = TRUE; hr = pEngineState->userExperience.pUserExperience->OnStartup(); ExitOnFailure(hr, "Failed to start bootstrapper application."); // Enter the message pump. while (0 != (fRet = ::GetMessageW(&msg, NULL, 0, 0))) { if (-1 == fRet) { hr = E_UNEXPECTED; ExitOnRootFailure(hr, "Unexpected return value from message pump."); } else { ProcessMessage(pEngineState, &msg); } } // get exit code pEngineState->userExperience.dwExitCode = (DWORD)msg.wParam; LExit: if (fStartupCalled) { int nResult = pEngineState->userExperience.pUserExperience->OnShutdown(); if (IDRESTART == nResult) { LogId(REPORT_STANDARD, MSG_BA_REQUESTED_RESTART, LoggingBoolToString(pEngineState->fRestart)); pEngineState->fRestart = TRUE; } else if (IDRELOAD_BOOTSTRAPPER == nResult) { LogId(REPORT_STANDARD, MSG_BA_REQUESTED_RELOAD); *pfReloadApp = TRUE; } } // unload UX UserExperienceUnload(&pEngineState->userExperience); ReleaseObject(pEngineForApplication); return hr; }
int GetTextOSK(char *buf,int buflen,int mode,const char *title,const char *init) { if(buf == NULL)return -1; u16 *winit,*wtitle,*wresult; char nulstr[] = ""; if(init == NULL)init = nulstr; if(title == NULL)title = nulstr; winit = (u16*)malloc((strlen(init) + 1) * 2); wtitle = (u16*)malloc((strlen(title) + 1) * 2); wresult = (u16*)malloc((buflen + 1) * 2); if(winit == NULL || wtitle == NULL || wresult == NULL) { free(winit); free(wtitle); free(wresult); return -1; } dxpCpCode_toUcs2(winit,strlen(init) + 1,(const dxpChar*)init,dxpGeneralData.charset); dxpCpCode_toUcs2(wtitle,strlen(title) + 1,(const dxpChar*)title,dxpGeneralData.charset); SceUtilityOskData data; memset(&data, 0, sizeof(SceUtilityOskData)); sceUtilityGetSystemParamInt(PSP_SYSTEMPARAM_ID_INT_LANGUAGE, &data.language); data.unk_00 = 1; //ATOK data.lines = 1; data.unk_24 = 1; data.inputtype = mode; data.desc = wtitle; data.intext = winit; data.outtextlength = buflen; data.outtextlimit = buflen; data.outtext = wresult; SceUtilityOskParams params; memset(¶ms,0x00,sizeof(params)); params.base.size = sizeof(params); sceUtilityGetSystemParamInt(PSP_SYSTEMPARAM_ID_INT_LANGUAGE,¶ms.base.language); sceUtilityGetSystemParamInt(PSP_SYSTEMPARAM_ID_INT_UNKNOWN,¶ms.base.buttonSwap); params.base.graphicsThread = 0x11; params.base.accessThread = 0x13; params.base.fontThread = 0x12; params.base.soundThread = 0x10; params.datacount = 1; params.data = &data; sceUtilityOskInitStart(¶ms); int done = 0; while(ProcessMessage() != -1 && !done) { ClearDrawScreen(); if ( dxpDialogDrawScene != NULL ) dxpDialogDrawScene(); GUFINISH switch(sceUtilityOskGetStatus()) { case PSP_UTILITY_DIALOG_INIT: break; case PSP_UTILITY_DIALOG_VISIBLE: sceUtilityOskUpdate(1); break; case PSP_UTILITY_DIALOG_QUIT: sceUtilityOskShutdownStart(); break; case PSP_UTILITY_DIALOG_NONE: case PSP_UTILITY_DIALOG_FINISHED: done = 1; break; default: break; } ScreenFlip(); } // dxpCpSJIS_fromUcs2((dxpChar*)buf,buflen,wresult); dxpCpCode_fromUcs2((dxpChar*)buf,buflen,wresult,dxpGeneralData.charset); free(winit); free(wtitle); free(wresult); return 0; }
void CReceiver::VLogon(const CFxEventInfo& eventInfo, const string& protocolVersion) { CFxMessage message(FX_MSG_LOGON, eventInfo); message.Data = new CFxMsgLogon(protocolVersion); ProcessMessage(message); }
bool KSaneWidgetPrivate::winEvent(MSG* pMsg, long* result) { return ProcessMessage(*pMsg); }
// 入力検知から画面の描画までのループ(ゲーム本体に近い) int Display::game_loop(int IsContinue) { Character character; IsometricView iso; // プレイヤーの初期位置は一つ目の部屋の左上 character.player_coordinate_init(); LATEST_HIT_DIRECT = character.player_input(); // IsometricView表示 if(IsQuarter == IDYES){ //iso.DisplayIsometricView(); IsContinue = IDYES; while(ProcessMessage() == 0 /*&& CheckHitKey(KEY_INPUT_ESCAPE) == 0*/) { //ClearDrawScreen(); LATEST_HIT_DIRECT = character.player_input(); if(character.player_move() == GAME_OVER){ // プレイヤーの移動先が空間かtailの時ゲームオーバー return MessageGameOver(); } ClearDrawScreen(); iso.DisplayIsometricView(); LATEST_HIT_DIRECT = character.player_input(); //ScreenFlip(); // 残りのアイテムが無くなったらクリア if(LeftItemNum == 0){ return MessageEnding(); } } } // IsometricViewでない時 if(IsQuarter == IDNO){ //disp_map(); LATEST_HIT_DIRECT = character.player_input(); IsContinue = IDYES; while(ProcessMessage() == 0 /*&& CheckHitKey(KEY_INPUT_ESCAPE) == 0*/) { //ClearDrawScreen(); LATEST_HIT_DIRECT = character.player_input(); character.player_input(); if(character.player_move() == GAME_OVER){ // プレイヤーの移動先が空間かtailの時ゲームオーバー return MessageGameOver(); } ClearDrawScreen(); disp_map(); LATEST_HIT_DIRECT = character.player_input(); //ScreenFlip(); // 残りのアイテムが無くなったらクリア if(LeftItemNum == 0){ return MessageEnding(); } } } return 0; }
bool wxEventLoop::Dispatch() { wxCHECK_MSG( IsRunning(), false, _T("can't call Dispatch() if not running") ); MSG msg; BOOL rc = ::GetMessage(&msg, (HWND) NULL, 0, 0); if ( rc == 0 ) { // got WM_QUIT return false; } if ( rc == -1 ) { // should never happen, but let's test for it nevertheless wxLogLastError(wxT("GetMessage")); // still break from the loop return false; } #if wxUSE_THREADS wxASSERT_MSG( wxThread::IsMain(), wxT("only the main thread can process Windows messages") ); static bool s_hadGuiLock = true; static wxMsgList s_aSavedMessages; // if a secondary thread owning the mutex is doing GUI calls, save all // messages for later processing - we can't process them right now because // it will lead to recursive library calls (and we're not reentrant) if ( !wxGuiOwnedByMainThread() ) { s_hadGuiLock = false; // leave out WM_COMMAND messages: too dangerous, sometimes // the message will be processed twice if ( !wxIsWaitingForThread() || msg.message != WM_COMMAND ) { MSG* pMsg = new MSG(msg); s_aSavedMessages.Append(pMsg); } return true; } else { // have we just regained the GUI lock? if so, post all of the saved // messages // // FIXME of course, it's not _exactly_ the same as processing the // messages normally - expect some things to break... if ( !s_hadGuiLock ) { s_hadGuiLock = true; wxMsgList::compatibility_iterator node = s_aSavedMessages.GetFirst(); while (node) { MSG* pMsg = node->GetData(); s_aSavedMessages.Erase(node); ProcessMessage(pMsg); delete pMsg; node = s_aSavedMessages.GetFirst(); } } } #endif // wxUSE_THREADS ProcessMessage(&msg); return true; }
int main(int argc, char **argv) { #ifdef DXPORTLIB SetUseCharSet(DX_CHARSET_EXT_UTF8); #endif SetWindowText(_T("DxPortLib Test App")); SetWindowSizeChangeEnableFlag(TRUE); SetGraphMode(640, 480, 32); ChangeWindowMode(TRUE); if (DxLib_Init() == -1) { return -1; } SRand(0); InitBounceThings(); int isWindowed = TRUE; int wasPressed = 0; int timerDelta = 0; int timeLast = GetNowCount(); int screenshotWasPressed = 0; int drawScreen = MakeScreen(640, 480, FALSE); while (ProcessMessage() == 0 #ifndef DX_NON_INPUT && CheckHitKey(KEY_INPUT_ESCAPE) == 0 #endif ) { /* If Alt+Enter is pressed, flip to fullscreen mode. */ if (CheckHitKey(KEY_INPUT_RETURN) && (CheckHitKey(KEY_INPUT_LALT) || CheckHitKey(KEY_INPUT_RALT)) ) { if (wasPressed == 0) { isWindowed = 1 - isWindowed; ChangeWindowMode(isWindowed); } wasPressed = 1; } else { wasPressed = 0; } /* Game logic here */ MoveBounceThings(); /* Draw logic here */ SetDrawScreen(drawScreen); SetDrawBright(255, 255, 255); SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 255); DrawFillBox(0, 0, 640, 480, 0xFF000000); DrawLineBox(10, 10, 630, 470, 0xFFFFFFFF); SetDrawBlendMode(DX_BLENDMODE_ALPHA, 128); DrawFillBox(20, 20, 620, 460, GetColor(0x90, 0x80, 0x70)); DrawBounceThings(); if (CheckHitKey(KEY_INPUT_S)) { if (screenshotWasPressed == 0) { SaveDrawScreenToPNG(0, 0, 640, 480, _T("test_draw_screenshot.png")); screenshotWasPressed = 1; } } else { screenshotWasPressed = 0; } SetDrawScreen(DX_SCREEN_BACK); DrawGraph(0, 0, drawScreen, FALSE); ScreenFlip(); /* Time to next frame automatically... */ int newTime = GetNowCount(); timerDelta += newTime - timeLast; timeLast = newTime; int n = timerDelta; if (n > 16) { n = 16; } timerDelta -= n; WaitTimer(16 - n); } DxLib_End(); return 0; }
static void *thread_socket ( void *arg ) { struct addrinfo hints ; struct addrinfo *result ; ssize_t nread ; char buf[BUF_SIZE] ; memset ( &hints , 0 , sizeof (struct addrinfo ) ) ; hints.ai_family = AF_INET ; hints.ai_socktype = SOCK_DGRAM ; hints.ai_flags = AI_PASSIVE ; hints.ai_protocol = 0 ; hints.ai_canonname = NULL ; hints.ai_addr = NULL ; hints.ai_next = NULL ; s = getaddrinfo ( NULL , "50007" , &hints , &result ) ; if ( s != 0 ) { fprintf ( stderr , "getaddrinfo: %s\n" , gai_strerror ( s ) ) ; exit ( EXIT_FAILURE ) ; } sfd = socket ( result->ai_family , result->ai_socktype , result->ai_protocol ) ; if ( sfd == - 1 ) { fprintf ( stderr , "Could not create socket.\n" ) ; exit ( EXIT_FAILURE ) ; } else { printf ( "Socket created.\n" ) ; } if ( bind ( sfd , result->ai_addr , result->ai_addrlen ) != 0 ) { fprintf ( stderr , "Could not bind.\n" ) ; exit ( EXIT_FAILURE ) ; } else { printf ( "Binded.\n" ) ; } peer_addr_len = sizeof (struct sockaddr_storage ) ; freeaddrinfo ( result ) ; while ( 1 ) { nread = recvfrom ( sfd , buf , BUF_SIZE , 0 , ( struct sockaddr * ) &peer_addr , &peer_addr_len ) ; if ( nread <= 0 ) { printf ( "No data received.\n" ) ; break ; } else { printf ( "Data received. Count:%d.\n" , nread ) ; } char host[NI_MAXHOST] , service[NI_MAXSERV] ; s = getnameinfo ( ( struct sockaddr * ) &peer_addr , peer_addr_len , host , NI_MAXHOST , service , NI_MAXSERV , NI_NUMERICSERV ) ; if ( s == 0 ) { printf ( "Received %ld bytes from %s:%s>>>%s\n" , ( long ) nread , host , service , buf ) ; } else { fprintf ( stderr , "getnameinfo: %s\n" , gai_strerror ( s ) ) ; } if ( ProcessMessage ( buf , nread ) < 0 ) { send_message_safe ( "message bad" ) ; } } close ( sfd ) ; return 0 ; }
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { ChangeWindowMode(TRUE); SetDrawScreen( DX_SCREEN_BACK); if(DxLib_Init()==-1) // DXライブラリ初期化処理 { return -1 ; // エラーが起きたら直ちに終了 } //デバック用にコンソールを出現させる AllocConsole(); freopen("CONOUT$","w",stdout); freopen("CONIN$","r",stdin); Mode gamemode=OPENING; AI_T ai[AI_NUM]; int death[AI_NUM]={0}; Tagger tagger[TAGGER_NUM]; int tagger_num = 0; int STAGE[WIDTH][HEIGHT]={0}; int round=0; int end=0; while(ProcessMessage()!=-1){ switch(gamemode){ case OPENING: intro(); gamemode=SETTING; break; case SETTING: make_Stage(STAGE);//マップ構成 tagger_num = init_Tagger(tagger,STAGE);//鬼の初期化 //tagger_numは鬼の要素番号 //for(int i=0;i<AI_NUM;i++){//AIの初期化 //henteko : aiをすべてinit_Aiに渡す init_Ai(ai,STAGE); //} round++; gamemode=RUNNING; break; case RUNNING: if(tagger[tagger_num].step==0){ //tagger[tagger_num].act=next_Tagger(tagger[tagger_num],STAGE,ai); tagger[tagger_num].act=tagger[tagger_num].moveFunc(tagger[tagger_num].x,tagger[tagger_num].y,STAGE,ai); //AIと一緒で、moveFunc使う } for(int i=0;i<AI_NUM;i++){ if(ai[i].step==0){ setview_Ai(&ai[i],STAGE); //ai[i].act=next_Ai(ai[i].view); //henteko : 下のmoveFunc()を使うためコメントアウト ai[i].act = ai[i].moveFunc(ai[i].view); } } update_Tagger(&tagger[tagger_num],STAGE); for(int i=0;i<AI_NUM;i++){ update_Ai(&ai[i],STAGE); } update_stage(STAGE,ai,tagger[tagger_num]); ClearDrawScreen(); draw(STAGE,ai,tagger[tagger_num]); DrawFormatString(30,30,GetColor(0,255,255),"ROUND%d",round); if(tagger[tagger_num].step==0){ for(int i=0;i<AI_NUM;i++){ if(death_Ai(ai[i],tagger[tagger_num])==1){ death[i]++; const char* str = strcat(ai[i].name , "がつかまりました"); //文字列連結 DrawString(100,240,str,GetColor(255,0,0)); WaitTimer(3000); if(round>=ROUND_MAX){ gamemode=ENDING; } else{ gamemode=SETTING; } break; } } } if(CheckHitKey(KEY_INPUT_R)==1){ gamemode=SETTING; } break; case ENDING: result(ai,death); WaitKey(); end=1; break; default: break; } if(end==1 || CheckHitKey(KEY_INPUT_ESCAPE))break; ScreenFlip(); } DxLib_End() ; // DXライブラリ使用の終了処理 return 0 ; // ソフトの終了 }
void GameServer::Run() { XmlParser parser("settings/Players.xml"); PlayerType playerType = (PlayerType)parser.ReadInt("/PlayerData/PlayerOneType"); u32 keybinds[4] = { CL_KEY_LEFT, CL_KEY_RIGHT, CL_KEY_UP, CL_KEY_J }; Initialize(); InitializeLevel(); InitializePlayer(playerType, keybinds); InitializeNetwork(); s32 timeElapsedMs, lastTime, currentTime, waitTime; currentTime = lastTime = CL_System::get_time(); // Main game loop while (!m_quit) { //Calculate the elapsed time since the beginning of the last frame currentTime = CL_System::get_time(); timeElapsedMs = currentTime - lastTime; if (timeElapsedMs > 50) { //Guard to ensure that the frame time isn't too long timeElapsedMs = 50; } lastTime = currentTime; m_frameCounter++; m_incomingMessages.clear(); m_outgoingMessages.clear(); while (true) { MessageData packet; u32 bytes_read = m_connection.ReceivePacket(packet.data, sizeof(packet.data)); if (bytes_read == 0) { break; } m_incomingMessages.push_back(packet); } std::vector<MessageData>::iterator it = m_incomingMessages.begin(); for (; it != m_incomingMessages.end(); ++it) { ProcessMessage((*it).data); } //Update the game state m_level->Update(); m_updateSignal.invoke(timeElapsedMs); m_drawSignal.invoke(); // Flip the display, showing on the screen what we drew since last call to flip() m_window.flip(0); ComposeUpdateMessage(); if ((m_frameCounter % 6) == 0) { ComposeSyncMessage(); } if (m_outgoingMessages.size() > 0) { std::vector<MessageData>::iterator it = m_outgoingMessages.begin(); for (; it != m_outgoingMessages.end(); ++it) { m_connection.SendPacket((*it).data, (*it).size); } } //Measure the time for this frame's update waitTime = 16 - (CL_System::get_time() - currentTime); if (waitTime < 0) { waitTime = 0; } // This call processes user input and other events CL_KeepAlive::process(0); // Sleep for a little while to avoid using too much of the CPU. CL_System::sleep(waitTime); } }
void CEsperEngine::ProcessMessage (const SArchonMessage &Msg, CHexeSecurityCtx *pSecurityCtx) // ProcessMessage // // Processes messages { try { DWORD dwStartTime = sysGetTickCount(); // Arc.fileMsg if (strEquals(Msg.sMsg, MSG_ARC_FILE_MSG)) { SArchonMessage NewMsg; CInterprocessMessageQueue::DecodeFileMsg(Msg, &NewMsg); SendMessage(NewMsg); } // Arc.getStatus else if (strEquals(Msg.sMsg, MSG_ARC_GET_STATUS)) MsgGetStatus(Msg, pSecurityCtx); // Arc.housekeeping else if (strEquals(Msg.sMsg, MSG_ARC_HOUSEKEEPING)) MsgHousekeeping(Msg, pSecurityCtx); // Arc.sandboxMsg else if (strEquals(Msg.sMsg, MSG_ARC_SANDBOX_MSG)) { SArchonMessage SandboxMsg; CHexeSecurityCtx SecurityCtx; SandboxMsg.sMsg = Msg.dPayload.GetElement(0); SandboxMsg.sReplyAddr = Msg.sReplyAddr; SandboxMsg.dwTicket = Msg.dwTicket; SandboxMsg.dPayload = Msg.dPayload.GetElement(1); SecurityCtx.Init(Msg.dPayload.GetElement(2)); return ProcessMessage(SandboxMsg, &SecurityCtx); } // Esper messages else if (strEquals(Msg.sMsg, MSG_ESPER_HTTP)) MsgEsperHTTP(Msg); else if (strEquals(Msg.sMsg, MSG_ESPER_GET_USAGE_HISTORY)) MsgEsperGetUsageHistory(Msg, pSecurityCtx); // Else, unhandled message else { CString sError = strPattern(ERR_INVALID_MSG, Msg.sMsg); SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, sError, Msg); m_pProcess->Log(MSG_LOG_ERROR, sError); } DWORD dwTime = sysGetTicksElapsed(dwStartTime); if (dwTime >= 1000) Log(MSG_LOG_INFO, strPattern(ERR_MSG_TIMING, Msg.sMsg, dwTime)); } catch (...) { m_pProcess->Log(MSG_LOG_ERROR, strPattern(ERR_CRASH_MSG, Msg.sMsg)); SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, ERR_INTERNAL_SERVER_ERROR, Msg); } }
void tTVPApplication::HandleMessage() { MSG msg = {0}; if( !ProcessMessage(msg) ) { HandleIdle(msg); } }
int ShowSaveDialog( /* セーブモード */ int mode, /* セーブデータのバッファ */ void * buf, /* bufのサイズ */ unsigned int size, /* ms0:/PSP/SAVEDATA/GameName */ const char * GameName, /* ゲームのタイトル、セーブデータのタイトル、セーブデータの詳細 */ const char * GameTitle, const char * SaveTitle, const char * SaveDetail ) { if ( mode < 0 || mode > 6 ) return -1; //オートセーブモードでは0000にセーブする char NameList[][20] = { "0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "" }; SceUtilitySavedataParam dialog; if ( dxpSaveDialogInit(&dialog, mode, buf, size, GameName, "0000", NameList, GameTitle, SaveTitle, SaveDetail) < 0 ) return -1; if ( sceUtilitySavedataInitStart(&dialog) != 0 ) return -1; int done = 0; while( ProcessMessage() != -1 && !done ) { if ( mode != PSP_UTILITY_SAVEDATA_AUTOSAVE ) { ClearDrawScreen(); if ( dxpDialogDrawScene != NULL ) dxpDialogDrawScene(); } GUFINISH switch( sceUtilitySavedataGetStatus() ) { case PSP_UTILITY_DIALOG_INIT: break; case PSP_UTILITY_DIALOG_VISIBLE: sceUtilitySavedataUpdate(1); break; case PSP_UTILITY_DIALOG_QUIT: sceUtilitySavedataShutdownStart(); break; case PSP_UTILITY_DIALOG_FINISHED: done = 1; break; case PSP_UTILITY_DIALOG_NONE: done = 1; default: break; } if ( mode != PSP_UTILITY_SAVEDATA_AUTOSAVE ) ScreenFlip(); } memset(dxp_save_resource, 0, sizeof(PspUtilitySavedataFileData) * 4); int ret; if ( mode == DXP_SAVE_MODE_LOAD ) { //正常に読み込んだ //if(dialog.unknown1 != 0) //if(dialog.unknown1 == 1021) if ( dialog.base.result == 0 ) { memcpy(buf, dialog.dataBuf, size); ret = 0; } //キャンセルされた else if ( dialog.base.result == 1 ) { memset(buf, 0x0, size); ret = -2; } //セーブデータが存在しなかった //else if(dialog.base.result == -2146368761) else { memset(buf, 0x0, size); ret = -3; } } else { ret = 0; } free(dialog.dataBuf); return ret; }