void Init(HWND hWnd) { // Set our global window handle to our main window g_hWnd = hWnd; // Create our double buffering our window g_Buffer.CreateDoubleBuffering(hWnd); // This is where we create the image of our character HBITMAP hPlayerImage = g_Buffer.LoadABitmap((LPSTR)kPlayerImage); // Initialize our player with it's image and position g_Player.Init(hPlayerImage, kPlayerStartX, kPlayerStartY); // Init, load and draw the first map file g_Map.Load(kStartMap); g_Map.SetDrawFlag(true); // Here we load then play the starting background music if(!g_Music.Init("techno.mod")) exit(0); g_Music.PlaySong(); // we need to seed our random number generator (rand()) for moving npcs. srand(GetTickCount()); // Set the backbuffer to black first (This clears the backbuffer) g_Buffer.ClearScreen(BLACK_BRUSH); }
void LoadOrSaveAMap(bool bLoad) { string strMapName = ""; // Create a STL string to read in the input from the user char szName[255] = {0}; // Create a traditional string of characters for the file name // In this function we setup a prompt for the user to type in the file name to // either save or load. If you want to load a file, you pass in "true", otherwise // we use "false" to indicate that we want to save a file. This cuts down on code // since a lot of the code is the same for each action. This function doesn't // actually do the saving and loading code, but handles the input from the user. // The save and load code is in our CMap::Load() and CMap::Save() functions that // we call from here. // Get an output handle for the console window and set the cursor position for a prompt HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hOutput, g_promptPos); // To clear the prompt, we just print out a bunch of tabs and then reset the cursor position cout << "\t\t\t\t\t\t\t\t\t\t"; SetConsoleCursorPosition(hOutput, g_promptPos); // Get an input handle and set the console window to allow input from the user // and echo it to the screen. This is important. If you don't set this mode, // the user won't see what they are typing. HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); SetConsoleMode(hInput, ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT); // Below we check if we want to load or save a file, then display the appropriate message if(bLoad) cout << "Enter a map to Load: "; else cout << "Enter a map to Save: "; // Here we get the map name that we want to save or load cin >> strMapName; // Then we extract the string from the string class and put it in a normal array or characters strcpy(szName, strMapName.c_str()); // Next we either load or save the map entered by the user, depending on bLoad if(bLoad) g_Map.Load(szName); else g_Map.Save(szName); // Next, we restore the console mode for getting mouse and keyboard input and redraw the screen SetConsoleMode(hInput, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT); g_Map.Draw(); }
void Init() { // This is where we create the image of our character, a brown @ symbol CHAR_INFO playerImage = {'@', FOREGROUND_RED | FOREGROUND_GREEN}; // Initialize our player with it's image and position g_Player.Init(playerImage, kPlayerStartX, kPlayerStartY); // Init the map and load the first map. Then set the flag that tells // the map's Draw() function to draw that frame. We don't want to draw // every frame, but only when something happens. g_Map.SetDefault(); g_Map.Load(kStartMap); g_Map.SetDrawFlag(true); }
void HandleExitTiles() { // This function handles our exit setting on the destination map. If the // exit map (destination map) isn't open, then we want to get the name of // the map to open from the user. We check to see if it's valid, and if // it's not, we need to delete all the exits on the main map since they // are invalid. If it is valid, then we want to load the destination map // so that they user can choose the spot where the player will end up on // the other map. If the exit map is already open and this function is // called, we want to go through all the exits we set and fill in their // destination information. This function is thus called twice, when we // want to load the destination map, and after we are finished placing exits. // If we don't have the exit map open if(!g_bExitMapOpen) { char szExitFile[255] = {0}; // Bring up the open dialog box and get a map to exit to if(GetExitFileName(szExitFile)) { g_ExitMap.Load(szExitFile); // Open the map to exit to g_bExitMapOpen = true; // State that we now have the exit map open g_pCurrentMap = &g_ExitMap; // Set the current map to our exit map g_pCurrentMap->SetCurrentType(EXIT_TYPE); // Set the current type to the exit type } else // If the file is invalid, delete the exits g_pCurrentMap->DeleteBlankExits(); } else // If we already have the exit map open { // Get the size of the current exit list and get the last exit tile in the list. // In other words, get the last tile we just placed on the exit map. int size = g_ExitMap.GetCurrentListSize(); CExit *pExit = (CExit*)g_ExitMap.GetCurrentListTile(size - 1); // Set the exits we just placed on the main map with the // new destination info (name, position, etc...) g_Map.SetExits(g_ExitMap.GetMapName(), pExit); // Restore the current map to our normal map we were working with g_pCurrentMap = &g_Map; g_bExitMapOpen = false; } }
void LoadOrSaveAMap(bool bLoad) { string strMapName = ""; // Create a STL string to read in the input from the user char szName[255] = {0}; // Create a traditional string of characters for the file name // Get an output handle for the console window and set the cursor position for a prompt HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hOutput, g_promptPos); // To clear the prompt, we just print out a bunch of tabs and then reset the cursor position cout << "\t\t\t\t\t\t\t\t\t\t"; SetConsoleCursorPosition(hOutput, g_promptPos); // Get an input handle and set the console window to allow input from the user HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); SetConsoleMode(hInput, ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT); // Below we check if we want to load or save a file, then display the appropriate message if(bLoad) cout << "Enter a map to Load: "; else cout << "Enter a map to Save: "; // Here we get the map name that we want to save or load cin >> strMapName; // Then we extract the string from the string class and put it in a normal array or characters strcpy(szName, strMapName.c_str()); // Next we either load or save the map entered by the user, depending on bLoad if(bLoad) g_Map.Load(szName); else g_Map.Save(szName); // Next, we restore the console mode for getting mouse and keyboard input and redraw the screen SetConsoleMode(hInput, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT); g_Map.Draw(); }
void HandleMenu(int menuID) { if(menuID == ID_FILE_QUIT) // If the user chose File->Quit { PostQuitMessage(0); // Quit the program } //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// else if(menuID == ID_FILE_OPENUP) // If the user chose File->Open { // Have windows bring up the Open File dialog box and Load the file chosen if(GetOpenFileName(&g_OpenInfo)) g_Map.Load(g_OpenInfo.lpstrFile); } else if(menuID == ID_FILE_SAVEIT) // If the user chose File->Save { // If we have a n valid name for our map already, do a normal save if(strlen(g_Map.GetMapName()) > 3) g_Map.Save(g_Map.GetMapName()); else { // If haven't given our map a name yet, do a "SaveAs" and bring up the save dlg box if(GetSaveFileName(&g_OpenInfo)) g_Map.Save(g_OpenInfo.lpstrFile); } } else if(menuID == ID_FILE_SAVEAS) // If the user chose File->SaveAs { // Bring up the save dlg box and allow the user to type in a new map name and save it if(GetSaveFileName(&g_OpenInfo)) g_Map.Save(g_OpenInfo.lpstrFile); } //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// else if(menuID == ID_FILE_RESET) // If the user chose File->Reset g_Map.SetDefault(); // Destroy all the tiles on the map and start over else if(menuID == ID_TILES_TILES) // If the user chose Tiles->Tiles g_Map.SetCurrentType(TILE_TYPE); // Set the tool bar tile type to tiles else if(menuID == ID_TILES_ITEMS) // If the user chose Tiles->Items g_Map.SetCurrentType(ITEM_TYPE); // Set the tool bar tile type to items else if(menuID == ID_TILES_MONSTERS) // If the user chose Tiles->Monsters g_Map.SetCurrentType(MONSTER_TYPE); // Set the tool bar tile type to monsters else if(menuID == ID_TILES_CITIZENS) // If the user chose Tiles->Citizens g_Map.SetCurrentType(NPC_TYPE); // Set the tool bar tile type to citizens else if(menuID == ID_TILES_EXITS) // If the user chose Tiles->Exits g_Map.SetCurrentType(EXIT_TYPE); // Set the tool bar tile type to exits (no tiles of course) else if(menuID == ID_HELP_ABOUT) // If the user chose Help->About // Instead of creating a help dialog box, we can just use a simple system MessageBox() call MessageBox(g_hWnd, "www.GameTutorials.com Map Editor\n\n" "\t- Choose the desired tile type from the Tiles menu,\n" "\t then click on a tile in the tile window. You can\n" "\t then draw the tiles on the map with the left mouse button.\n\n" "\t- Right click to remove the current cursor tile.\n\n" "\t- To delete a item:monster:citizen:exit, make sure you choose\n" "\t that type from the menu, then right click on the tile.\n\n" "\t- When setting an exit you can hold down shift to place more exits.\n" "\t Once you place an exit without holding the shift key you will be\n" "\t prompted to choose the destination map. Then place one tile for\n" "\t the position where the character will end up.\n\n" "\t- Hit Esc to quit the program.", "About", MB_OK | MB_ICONINFORMATION); // Over assuming that a tile type was changed, reset the scroll bar size. // The -1 is because the tool bar window's title size offsets it a bit (being smaller). g_ScrollInfo.nMax = g_Map.GetCurrentTypeSize() - MAP_HEIGHT - 1; // If there isn't enough (or any) tiles to fill up the tool bar window, disable the scroll bar if(g_ScrollInfo.nMax < 0) { g_ScrollInfo.nMax = 0; EnableScrollBar(g_hWndTool, SB_VERT, ESB_DISABLE_BOTH); } else EnableScrollBar(g_hWndTool, SB_VERT, ESB_ENABLE_BOTH); // Enable the scroll bar if it's needed // Reset the scroll bar info g_scrollBarPosY = 0; g_ScrollInfo.nPage = 0; // Update the current scroll bar information with no need to redraw (FALSE) SetScrollInfo(g_hWndTool, SB_VERT, &g_ScrollInfo, FALSE); ShowScrollBar(g_hWndTool, SB_VERT, TRUE); // If we chose a tile type, put a check box next to it switch(menuID) { case ID_TILES_TILES: case ID_TILES_ITEMS: case ID_TILES_MONSTERS: case ID_TILES_CITIZENS: case ID_TILES_EXITS: g_pCursorTile = NULL; CheckTileType(menuID); break; } }
//pêtla g³ówna gry void CGame::mainLoop() { CMap mapa; mapa.Load("data/xml_data/maps/level_001.xml"); mapa.RespawnMapObjects(true); //rêczna, bezpieczna inicjacja niektórych singleton initSingletons(); //jakaœ funkcja ³aduj¹ca na pocz¹tku zasoby dla poprawy wydajnoœci... //bardzo Ÿle napisane...mo¿na poni¿sze opakowaæ do jakiejœ klasy/metody? CFont font = *gResourceManager.GetFont("data/fonts/tahoma.ttf"); fps_text.setString("Zaczynamy"); fps_text.setFont(font); fps_text.setCharacterSize(20); fps_text.setColor(sf::Color::Blue); fps_text.setPosition(10,10); /* //³adowanie danych z poziomu CResourceManager'a if(gResourceManager.LoadPhysicalTemplate("data/xml_data/units_enemy/destroyer.xml") == false) printf("Data not loaded...\n"); if(gResourceManager.LoadPhysicalTemplate("data/xml_data/units_monster/monster.xml") == false) printf("Data not loaded...\n"); //tworzê fabrykê i inicjujê j¹ danymi pobramymi z CResourceManager'a uprzednio za³adowanymi CEnemyTemplate *p_enemy_template = (CEnemyTemplate*)gResourceManager.GetPhysicalTemplate("data/xml_data/units_enemy/destroyer.xml"); //ten kod jest testowy, bo tworzenie (respawn) obiektów bêdzie z poziomu ³adowania mapy (level'a) CEnemy *p_enemy = p_enemy_template->Create(L"ID_enemy"); if(p_enemy) { p_enemy->SetUseDisplayableBody(false); p_enemy->setSmoothing(false); p_enemy->SetPosition(400, 200); p_enemy->SetScale(2.5f); p_enemy->SetScaleHead(1.0f,1.0f); p_enemy->SetColorHead(sf::Color::Transparent); p_enemy->SetColorShadow(sf::Color::Transparent); p_enemy->SetAnimationHead("backpack_anim"); p_enemy->SetAnimationBody("backpack_anim"); //p_enemy->SetRotationBody(32.f); //p_enemy->SetRotationHead(310); //testy...sprawdziæ...jak to dzia³a... //p_enemy->SetColorHead(sf::Color::Blue); //kolorujemy obiekt body na niebiesko //p_enemy->SetColorBody(sf::Color::Red); //kolorujemy obiekt head na czerwono //p_enemy->RestoreColor(); //odzyskujemy oryginalny kolor body and head //p_enemy->RestoreColorBody(); //odzyskujemy oryginalny kolor body //p_enemy->RestoreColorHead(); //odzyskujemy oryginalny kolor head } //tworzê fabrykê i inicjujê j¹ danymi pobramymi z CResourceManager'a uprzednio za³adowanymi CMonsterTemplate *p_monster_template = (CMonsterTemplate*)gResourceManager.GetPhysicalTemplate("data/xml_data/units_monster/monster.xml"); //ten kod jest testowy, bo tworzenie (respawn) obiektów bêdzie z poziomu ³adowania mapy (level'a) CMonster *p_monster = p_monster_template->Create(L"ID_monster"); if(p_monster) { //p_enemy->SetUseDisplayableBody(false); p_monster->setSmoothing(false); p_monster->SetPosition(550, 200); //p_enemy->SetScale(2.5f); //p_enemy->SetScaleHead(1.0f,1.0f); //p_enemy->SetColorHead(sf::Color::Transparent); //p_enemy->SetColorShadow(sf::Color::Transparent); //p_enemy->SetAnimationHead("backpack_anim"); //p_enemy->SetAnimationBody("backpack_anim"); } */ printf("CGame::Run()\n"); while (m_render_window->isOpen()) { //zegar float elapsedTime = m_clock.GetElapsedTime(); m_clock.Reset(); //mo¿na te¿ skorzystaæ z poni¿szego zegara... //float elapsedTime = gClock.GetElapsedTime(); //gClock.Update(); while (m_render_window->pollEvent(m_event)) { switch (m_event.type) { case sf::Event::Closed: m_render_window->close(); return; case sf::Event::KeyPressed: for (std::set<IKeyListener*>::iterator i = m_keyListeners.begin() ; i != m_keyListeners.end(); i++ ) (*i)->KeyPressed(m_event.key); break; default: break; } } m_render_window->clear(sf::Color(120,128,23)); //m_render_window->clear(sf::Color::White); Update(elapsedTime); //aktualizacja gry m_render_window->draw(fps_text); //statystyki... m_render_window->display(); //wyœwietlenie sceny w oknie } }
bool Controller::Initialize(const char* server_name, const char* configure_file) { _server_name = server_name; _configure_file = configure_file; // 加载配置 if (!gConfigureMap.Load(configure_file)) { printf("error: %s\n", gConfigureMap.GetErrMsg().c_str()); return false; } gConfigureMap.Print(); // 初始化日志 std::string log_path = JoinPath(gConfigureMap["log"]["log_path"].str(), server_name); if (!Logger::Initialize(log_path.c_str(), gConfigureMap["log"]["max_file_size"].as<uint32_t>(DefaultConf::kMaxLogFileSize), gConfigureMap["log"]["max_file_num"].as<uint32_t>(DefaultConf::kMaxLogFileNum), gConfigureMap["log"]["log_level"].c_str())) { printf("logger initialize failed, errmsg: %s\n", Logger::GetErrMsg().c_str()); } LogInfo("Logger initialize succeed\n"); int poller_max_event = gConfigureMap["poller_max_event"].as<int>(DefaultConf::kPollerMaxEventNum); assert(poller_max_event > 0); _poller = new Poller(poller_max_event); assert(_poller); LogInfo("Poller initialize succeed\n"); // 初始化监听端口 // TODO different port bind different protocol(unpack function) // 每个监听端口最好能独立的包完整性检查,每个访问外部server的端口,最好也能绑定独立协议 const Value & val = gConfigureMap["listen"]; _listen_size = val.size() + 128; _listen_sockets = new ListenFdInfo[_listen_size]; for (uint32_t i=0; i<_listen_size; ++i) { unsigned int port = val[i]["port"].as<unsigned>(0); int fd = ListenTcpV4(port); if (fd < 0) { FillErrmsg("listen failed: ", errno); return false; } _listen_sockets[fd].port = port; _listen_sockets[fd].fd = fd; if (_poller->Add(fd, (uint64_t)fd, EPOLLIN)) { FillErrmsg("listen fd add to poller failed: ", errno); return false; } } _io_handler_num = gConfigureMap["server"]["io_handler_num"].as<uint32_t>(DefaultConf::kIoHandlerNum); _io_handers = new IoHandler[_io_handler_num]; assert(_io_handers); for (uint32_t i=0; i<_io_handler_num; ++i) { if(!_io_handers[i].Initialize()) { _errmsg = "io handler initialize failed"; return false; } } _worker_num = gConfigureMap["server"]["worker_num"].as<uint32_t>(DefaultConf::kWorkerNum); _workers = new Worker[_worker_num]; assert(_workers); for (uint32_t i=0; i<_worker_num; ++i) { if(!_workers[i].Initialize()) { _errmsg = "initialize workers failed"; return false; } } int pool_size = _io_handler_num + _worker_num; int queue_size = gConfigureMap["server"]["queue_size"].as<uint32_t>(DefaultConf::kQueueSize); _task_pool = new TaskPool(); assert(_task_pool); if (!_task_pool->Initialize(pool_size, queue_size)) { LogErr("task poll initialize failed"); return false; } return true; }