/** ** Parse CREATEGAME */ static void ParseCreateGame(Session *session, char *buf) { char *description; char *map; char *players; char *ip; char *port; char *password; int players_int; int port_int; if (Parse5or6Args(buf, &description, &map, &players, &ip, &port, &password)) { Send(session, "ERR_BADPARAMETER\n"); return; } players_int = atoi(players); port_int = atoi(port); // FIXME: check ip if (strlen(description) > MAX_DESCRIPTION_LENGTH || strlen(map) > MAX_MAP_LENGTH || players_int < 1 || players_int > 16 || port_int < 1 || port_int > 66535 || (password && strlen(password) > MAX_GAME_PASSWORD_LENGTH)) { Send(session, "ERR_BADPARAMETER\n"); return; } CreateGame(session, description, map, players, ip, port, password); DebugPrint("%s created a game\n" _C_ session->UserData.Name); Send(session, "CREATEGAME_OK\n"); }
//============================================================================= // Starting point for a Windows application //============================================================================= int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Check for memory leak if debug build #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif MSG msg; // Create the game, sets up message handler game = CreateGame(); // Create the window if (!CreateMainWindow(hwnd, hInstance, nCmdShow)) return 1; try{ game->initialize(hwnd); // throws GameError // main message loop int done = 0; while (!done) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // look for quit message if (msg.message == WM_QUIT) done = 1; // decode and pass messages on to WinProc TranslateMessage(&msg); DispatchMessage(&msg); } else game->run(hwnd); // run the game loop } safeDelete(game); // free memory before exit return msg.wParam; } catch(const GameError &err) { game->deleteAll(); DestroyWindow(hwnd); MessageBox(NULL, err.getMessage(), "Error", MB_OK); } catch(...) { game->deleteAll(); DestroyWindow(hwnd); MessageBox(NULL, "Unknown error occured in game.", "Error", MB_OK); } safeDelete(game); // free memory before exit return 0; }
void FindOpponent(int incomeSd, int userID) { int found = 0; int i; for (i = 0; i < MAXUSERS; i++) if (i != userID && users_available[i]) { if (users[userID].ownLevel == users[i].desiredLevel && users[userID].desiredLevel == users[i].ownLevel) { found = 1; int gameID = CreateGame(userID, i); userGame[userID] = userGame[i] = gameID; userOp[userID] = i; userOp[i] = userID; printf("\n\nUserIDs: %d, %d\n", userID, i); printf("Game info\n"); printf("\tGameID: %d\n", gameID); printf("\tWhiteID: %d\n", games[gameID].white_user.userID); printf("\tBlackID: %d\n", games[gameID].black_user.userID); break; } } if (!found) { int result_val = 0; MessageType m = composeMessage(result, sizeof(int), &result_val); sendMessage(incomeSd, &m); while (userOp[userID] == userID) continue; } else { int result_val = 1; MessageType m = composeMessage(result, sizeof(int), &result_val); sendMessage(incomeSd, &m); } MessageType m = composeMessage(text, sizeof(users[userOp[userID]].name), &(users[userOp[userID]].name)); sendMessage(incomeSd, &m); Color color; if (games[userGame[userID]].white_user.userID == userID) color = white; else color = black; m = composeMessage(color_t, sizeof(Color), &color); sendMessage(incomeSd, &m); clearMessage(&m); }
bool GameWorld::init() { if ( !CCLayer::init() ) { return false; } CreateWorld(); CreateGame(); return true; }
void CGameServer::DestroyAllEntities(const tvector<tstring>& asSpare, bool bRemakeGame) { if (!GameNetwork()->IsHost() && !IsLoading()) return; if (m_pWorkListener) m_pWorkListener->SetAction("Locating dead nodes", GameServer()->GetMaxEntities()); for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++) { CBaseEntity* pEntity = CBaseEntity::GetEntity(i); if (!pEntity) continue; bool bSpare = false; for (size_t j = 0; j < asSpare.size(); j++) { if (asSpare[j] == pEntity->GetClassName()) { bSpare = true; break; } } if (bSpare) continue; pEntity->Delete(); if (m_pWorkListener) m_pWorkListener->WorkProgress(i); } if (m_pWorkListener) m_pWorkListener->SetAction("Clearing buffers", GameServer()->m_ahDeletedEntities.size()); for (size_t i = 0; i < GameServer()->m_ahDeletedEntities.size(); i++) { delete GameServer()->m_ahDeletedEntities[i]; if (m_pWorkListener) m_pWorkListener->WorkProgress(i); } GameServer()->m_ahDeletedEntities.clear(); if (CBaseEntity::GetNumEntities() == 0) CBaseEntity::s_iNextEntityListIndex = 0; if (bRemakeGame && GameNetwork()->IsHost()) m_hGame = CreateGame(); }
//Private int Engine::Initialize(){ m_EngineState = EngineState::Initializing; Game* game = CreateGame(); if (!game) return false; //Add some systems return true; }
void ShowHeroScene::CreateMenu() { auto strings = FileUtils::getInstance()->getValueMapFromFile("fonts/menu.xml"); std::string strBeginGame = strings["BeginGame"].asString(); std::string strCreateGame = strings["CreateGame"].asString(); std::string strJoinGame = strings["JoinGame"].asString(); std::string strExitGame = strings["ExitGame"].asString(); if (/*GameLogic::GetInstance()->IsSingleGame()*/GameLogic::GetInstance()->GetGameType() == SINGLE_GAME_TYPE) { MenuItemLabel* beginGameItem = MenuItemLabel::create(LabelTTF::create(strBeginGame, "Arial", 40), [&](Ref* sender) { BeginGame(); } ); beginGameItem->setPosition(Point(500,100)); auto menu = Menu::create(beginGameItem,NULL); menu->setPosition(Point(0, 0)); addChild(menu); } else { if (/*GameLogic::GetInstance()->IsCreator()*/GameLogic::GetInstance()->GetGameType() == CREATE_GAME_TYPE) { MenuItemLabel* createGameItem = MenuItemLabel::create(LabelTTF::create(strCreateGame, "Arial", 40), [&](Ref* sender) { CreateGame(); } ); createGameItem->setPosition(Point(500,100)); auto menu = Menu::create(createGameItem,NULL); menu->setPosition(Point(0, 0)); addChild(menu); } else { MenuItemLabel* joinGameItem = MenuItemLabel::create(LabelTTF::create(strJoinGame, "Arial", 40), [&](Ref* sender) { JoinGame(); } ); joinGameItem->setPosition(Point(500,100)); auto menu = Menu::create(joinGameItem,NULL); menu->setPosition(Point(0, 0)); addChild(menu); } } }
int main(int argc, char* args[]) { const int width=800, height=600, bpp=32; const char* caption = "FPS"; if (SDL_Init(SDL_INIT_EVERYTHING) < 0) return 1; if (SDL_SetVideoMode(width, height, bpp, SDL_OPENGL) == 0) return 2; // vsync SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1); SDL_WM_SetCaption(caption, 0); // Game* game = CreateGame(width, height); Gamepad* gamepad = CreateGamepad(); Uint32 accum = 0; Uint32 lastTick = SDL_GetTicks(); while (doLoop) { const Uint32 now = SDL_GetTicks(); accum += now-lastTick; lastTick = now; while (accum > TICKS_PER_FRAME) { gamepad->update(); game->update(*gamepad); accum -= TICKS_PER_FRAME; } game->render(); // delay some amount of time to play nice with the OS // this value can be tweaked SDL_Delay(1); } delete game; delete gamepad; SDL_Quit(); return 0; }
void StartMap(const std::string &filename, bool clean) { std::string nc, rc; gcn::Widget *oldTop = Gui->getTop(); gcn::Container *container = new gcn::Container(); Containers.push_back(container); container->setDimension(gcn::Rectangle(0, 0, Video.Width, Video.Height)); container->setOpaque(false); Gui->setTop(container); NetConnectRunning = 0; InterfaceState = IfaceStateNormal; // Create the game. DebugPrint("Creating game with map: %s\n" _C_ filename.c_str()); if (clean) { CleanPlayers(); } GetDefaultTextColors(nc, rc); CreateGame(filename.c_str(), &Map); UI.StatusLine.Set(NameLine); SetMessage("%s", _("Do it! Do it now!")); // Play the game. GameMainLoop(); // Clear screen Video.ClearScreen(); Invalidate(); CleanGame(); InterfaceState = IfaceStateMenu; SetDefaultTextColors(nc, rc); Gui->setTop(oldTop); Containers.erase(std::find(Containers.begin(), Containers.end(), container)); delete container; }
int main(int argc, char **argv) { //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); //creating engine Engine* engine = new Engine; GLUTInput* nativeInput = new GLUTInput; engine->nativeInput = nativeInput; WinAssetLoader* assetLoader = new WinAssetLoader; engine->assetLoader = assetLoader; GLUTDisplay* displayModule = new GLUTDisplay(engine, &argc, argv, GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH, 800, 600, "ENGINE"); engine->display = displayModule; displayModule->create(); CreateGame(); glutMainLoop(); //TEMP return 0; }
game NewGame() { game g = CreateGame(); if( g == NULL ) return NULL; RandomMap(g->gameMap); g->pc = CreateCharacter(g); wrefresh(g->win); init_pc(g->pc); box(g->arena, 0, 0); wrefresh(g->arena); int nzombies = NumZombies(g->arena); g->ZombieListHead = CreateCreature(g); init_npc(g->ZombieListHead->Character); wrefresh(g->arena); int n = 1; while( n < nzombies ) { wrefresh(g->arena); creature Z = CreateCreature(g); init_npc(Z->Character); InsertCreatureNode( g->ZombieListHead, Z ); ++n; } return g; }
//Private Methods int Engine::Initialize() { // Set the engine to Initializing m_EngineState = EngineState::Initializing; // Create the WorldSettings singleton Singleton<WorldSettings>::CreateInstance(); // Create a new point to a new game Game* game = CreateGame(); // Break if the new game failed if (!game) { return false; } // Add systems // Adding the Window system #if defined(DEBUG) | defined(_DEBUG) if (!AddSystem(new Window(WindowData(Singleton<WorldSettings>::GetInstance()->getWindowWidth(), Singleton<WorldSettings>::GetInstance()->getWindowHeight(), Singleton<WorldSettings>::GetInstance()->getWindowTitle())))) return false; #else AddSystem(new Window(WindowData(Singleton<WorldSettings>::GetInstance()->getWindowWidth(), Singleton<WorldSettings>::GetInstance()->getWindowHeight(), Singleton<WorldSettings>::GetInstance()->getWindowTitle()))); #endif // Adding the Graphics system #if defined(DEBUG) | defined(_DEBUG) if (!AddSystem(new Graphics(GraphicsData(GetSystem<Window>(SystemType::Sys_Window))))) return false; #else AddSystem(new Graphics(GraphicsData(GetSystem<Window>(SystemType::Sys_Window)))); #endif // Adding the Engine Timer system #if defined(DEBUG) | defined(_DEBUG) if (!AddSystem(new EngineTimer(EngineTimerData()))) return false; #else AddSystem(new EngineTimer(EngineTimerData())); #endif // Adding the Game Logic Data system #if defined(DEBUG) | defined(_DEBUG) if (!AddSystem(new GameLogic(GameLogicData()))) return false; #else AddSystem(new GameLogic(GameLogicData())); #endif // Initialize the system // Window Init Block #if defined(DEBUG) | defined(_DEBUG) if (!m_mapSystems[SystemType::Sys_Window]->Initialize()) return false; #else m_mapSystems[SystemType::Sys_Window]->Initialize(); #endif // Graphics Init Block #if defined(DEBUG) | defined(_DEBUG) if (!m_mapSystems[SystemType::Sys_Graphics]->Initialize()) return false; #else m_mapSystems[SystemType::Sys_Graphics]->Initialize(); #endif // Engine Timer Init Block #if defined(DEBUG) | defined(_DEBUG) if (!m_mapSystems[SystemType::Sys_EngineTimer]->Initialize()) return false; #else m_mapSystems[SystemType::Sys_EngineTimer]->Initialize(); #endif // Game Logic Init Block #if defined(DEBUG) | defined(_DEBUG) if (!m_mapSystems[SystemType::Sys_Logic]->Initialize()) return false; #else m_mapSystems[SystemType::Sys_Logic]->Initialize(); #endif // Create the singleton of the graphics device manager Singleton<GraphicsDeviceManager>::CreateInstance(); // Set that to the system we created Singleton<GraphicsDeviceManager>::GetInstance()->SetGraphics(GetSystem<Graphics>(SystemType::Sys_Graphics)); return true; }
int CALLBACK old( HINSTANCE Instance, HINSTANCE PrevInstance, LPSTR CommandLine, int ShowCode) { #if 1 Win32EnableConsole(); #endif sf::ContextSettings settings; settings.depthBits = 32; //24 settings.stencilBits = 0; //0 settings.antialiasingLevel = 0; //0 settings.majorVersion = 3; settings.minorVersion = 2; // Display the list of all the video modes available for fullscreen std::vector<sf::VideoMode> modes = sf::VideoMode::getFullscreenModes(); for (std::size_t i = 0; i < modes.size(); ++i) { sf::VideoMode mode = modes[i]; std::cout << "Mode #" << i << ": " << mode.width << "x" << mode.height << " - " << mode.bitsPerPixel << " bpp" << std::endl; } uint8 defaultStyle = (sf::Style::Titlebar | sf::Style::Close); auto mode = modes[17]; sf::RenderWindow renderWindow(sf::VideoMode(mode.width, mode.height, mode.bitsPerPixel), "OpenGL", defaultStyle , settings); renderWindow.setVerticalSyncEnabled(true); renderWindow.setFramerateLimit(60); renderWindow.resetGLStates(); settings = renderWindow.getSettings(); cout << "depth bits:" << settings.depthBits << endl; cout << "stencil bits:" << settings.stencilBits << endl; cout << "antialiasing level:" << settings.antialiasingLevel << endl; cout << "version:" << settings.majorVersion << "." << settings.minorVersion << endl; renderWindow.setActive(true); sfg::SFGUI sfgui; sfg::Desktop sfguiDesktop; CreateGui(sfguiDesktop); sf::Font retro_font; retro_font.loadFromFile( "../data/fonts/Retro Computer_DEMO.ttf" ); auto fent = std::make_shared<sf::Font>();// = sf::Font>(retro_font); fent->loadFromFile( "../data/fonts/Retro Computer_DEMO.ttf" ); //my_font.setGlobalBounds(text.getGlobalBounds.left, text.getGlobalBounds().top); sfguiDesktop.GetEngine().GetResourceManager().AddFont( "retro_font", fent ); //desktop.SetProperty( "*", "FontName", "custom_font" ); sfguiDesktop.SetProperties( "* {" " FontName: retro_font;" " FontSize: 18;" "}" ); sf::Text text; text.setFont(retro_font); text.setPosition(sf::Vector2f(2, 2)); text.setCharacterSize(18); text.setColor(sf::Color::White); KeyboardManager keyboardManager; //Game game(renderWindow, retro_font, &keyboardManager); char *GameDLLFullPath = "J:/build/terrific.dll"; char *TempDLLName = "J:/build/tmp.dll"; char *LockFileName = "J:/build/lock.tmp"; auto GameCodeDLL = Win32LoadGameCode(GameDLLFullPath, TempDLLName, LockFileName); Game *game = GameCodeDLL.CreateGame(renderWindow, retro_font, &keyboardManager); uint32 LoadCounter = 0; uint32 m_fps_counter = 0; float delta = 0; sf::Clock m_fps_clock; m_fps_clock.restart(); sf::Clock clock; sf::Clock frame_time_clock; sf::Int64 frame_times[5000]; std::size_t frame_times_index = 0; std::fill( std::begin( frame_times ), std::end( frame_times ), 0 ); int X(0), Y(0); while (globalRunning) { sf::Event event; while (renderWindow.pollEvent(event)) { if ((event.type == sf::Event::Closed)) { globalRunning = false; break; } else if ((event.type == sf::Event::MouseMoved)) { X = event.mouseMove.x; Y = event.mouseMove.y; } else if ((event.type == sf::Event::KeyPressed) | (event.type == sf::Event::KeyReleased)) { keyboardManager.ProcessEvent(event); } sfguiDesktop.HandleEvent(event); } FILETIME NewDLLWriteTime = Win32GetLastWriteTime(GameDLLFullPath); auto t = CompareFileTime(&NewDLLWriteTime, &GameCodeDLL.LastWriteTime); if(t != 0 && LoadCounter > 0) { //char buffer[256]; //sprintf(buffer, "J:/build/tmp%d.dll", LoadCounter); GameCodeDLL->DestroyGame(GameMemory); Win32UnloadGameCode(&GameCodeDLL); { sf::Clock clockT; while (clockT.getElapsedTime().asSeconds() < 0.5f) { system("cls"); cout << "Unloading Game Code . . . " << endl; } cout << "Game Code loaded!" << endl; clockT.restart(); } GameCodeDLL = Win32LoadGameCode(GameDLLFullPath, TempDLLName, LockFileName); if(GameCodeDLL.IsValid) { game = GameCodeDLL.CreateGame(renderWindow, retro_font, &keyboardManager); } LoadCounter++; } else { LoadCounter++; } auto microseconds = clock.getElapsedTime().asMicroseconds(); //delta = static_cast<float>( microseconds ) / 1000000.f; // Only update every 5ms delta = static_cast<float>(frame_time_clock.getElapsedTime().asSeconds()); if( microseconds > 5000 ) { game->update(delta); sfguiDesktop.Update(delta); keyboardManager.Update(); clock.restart(); renderWindow.setActive( true ); } renderWindow.clear(); delta = static_cast<float>(frame_time_clock.getElapsedTime().asSeconds()); game->draw(delta); sfgui.Display(renderWindow); renderWindow.draw(text); renderWindow.display(); auto frame_time = frame_time_clock.getElapsedTime().asMicroseconds(); frame_time_clock.restart(); frame_times[ frame_times_index ] = frame_time; frame_times_index = ( frame_times_index + 1 ) % 5000; if( m_fps_clock.getElapsedTime().asMicroseconds() >= 1000000 ) { m_fps_clock.restart(); sf::Int64 total_time = 0; for( std::size_t index = 0; index < 5000; ++index ) { total_time += frame_times[index]; } std::stringstream sstr; sstr << "SFGUI test -- FPS: " << m_fps_counter << " -- Frame Time (microsecs): min: " << *std::min_element( frame_times, frame_times + 5000 ) << " max: " << *std::max_element( frame_times, frame_times + 5000 ) << " avg: " << static_cast<float>( total_time ) / 5000.f; renderWindow.setTitle( sstr.str() ); m_fps_counter = 0; } ++m_fps_counter; } renderWindow.close(); Win32UnloadGameCode(&GameCodeDLL); { sf::Clock clockT; while (clockT.getElapsedTime().asSeconds() < 0.5f) { cout << "Unloading Game Code . . . " << endl; } clockT.restart(); } DeleteFile(TempDLLName); return 0; }
/******************************************************************************* * ########## 关于Callback回调函数 ########## * * 回调函数 Callback functions 是系统程序开发中常用的一种机制。 * * 在事件\消息驱动型的系统,我们会遇到以下情况: * (1)系统并不知道应用程序要如何处理事件(如鼠标点击); * (2)应用程序不知道何时会发生事件(如鼠标何时被点击)。 * 因此,应用程序定义好处理事件的函数,然后将这个函数的指针传递给操作系统,系统保存这个指针, * 当事件发生时,系统通过指针调用这个函数。 * * 因为很多情况下事件的发生都是硬件相关的,只有操作系统通过底层驱动才能获取硬件的IO情况。 * 现代操作系统的设计是不允许应用程序直接和硬件通讯的,必须全部由操作系统来进行管理。 * * 回调函数并不神秘,基本原理就是函数指针。 * 在消息和事件处理、多线程、异步IO等情况下经常会使用到。 * 回调函数机制是“消息驱动型”程序的基本技术。 * *******************************************************************************/ LONG CALLBACK MainWndProc( HWND hwnd, // UINT msg, // 消息 WPARAM wParam, // 消息参数,不同的消息有不同的意义,详见MSDN中每个消息的文档 LPARAM lParam) // 消息参数,不同的消息有不同的意义,详见MSDN中每个消息的文档 { // 注意,是switch-case, 每次这个函数被调用,只会落入到一个case中。 switch (msg) { // 当窗口被创建时,收到的第一个消息就是WM_CREATE, // 一般收到这个消息处理过程中,可以用来进行一些初始化的工作 case WM_CREATE: CreateGame(hwnd, INIT_TIMER_ELAPSE, ONE_LEVELS_SCORES, SPEEDUP_RATIO, MAX_X, MAX_Y, INIT_X, INIT_Y, INIT_SNAKE_LEN, INIT_DIR); ReSizeGameWnd(hwnd); break; // 当系统认为窗口上的GDI对象应该被重绘时,会向窗口发送一个WM_PAINT消息。 // 当然应用程序也可以通过调用 UpateWindow来主动向窗口发送一个WM_PAINT消息。 // 所有使用GDI在窗口上绘制图形的程序都 “必须” 写在这里。 // 如果不是在WM_PAINT消息的处理过程中绘制GDI图形,那么在窗口刷新时就会被新被抹除和覆盖 case WM_PAINT: GamePaint(hwnd); break; case WM_KEYDOWN: OnKeyDown(wParam); GamePaint(hwnd); break; case WM_LBUTTONDOWN: OnTimer(hwnd); GamePaint(hwnd); break; case WM_TIMER: OnTimer(hwnd); GamePaint(hwnd); break; case WM_DESTROY: ExitProcess(0); break; default: break; } return DefWindowProc(hwnd, msg, wParam, lParam); }