bool StageBuilder::loadLevelFromFile(int level) { // Load the specified level file, and if it isn't found return false std::ifstream levelFile("BrickBreakerData/levels/" + std::to_string(level) + ".txt"); if (!levelFile.is_open()) { return false; } // Various variables used in the while loop below std::string line; char special = '\0'; unsigned long numBricksPerLines = 0; float brickWidth = 0; int row = 0; int col = 0; while (getline(levelFile, line)) { col = 0; // If on the first line, store its length to determine how wide each brick should be if (numBricksPerLines == 0) { numBricksPerLines = line.size(); brickWidth = ((stageSize_.x - separation_) / numBricksPerLines); } // If the line is too long, shorten it. If it is too short, add spaces. if (line.size() > numBricksPerLines) { line.resize(numBricksPerLines, ' '); } for (char c : line) { // Get the appropriate special character based on the character read from file switch (c) { case '-': special = '\0'; break; case '~': special = SPECIALS[rand() % (sizeof(SPECIALS)/sizeof(char))]; // Random special character break; default: c = ' '; // No brick in the default case } // If the character in the file is a space, don't make a brick if (c != ' ') { objects_.push_back( new Brick(origin_.x + separation_ + brickWidth * col, origin_.y + separation_ + row * (brickHeight_ + separation_), brickWidth - separation_, brickHeight_, special ) ); } ++col; } ++row; } // Close the file and return true to mark the load successful levelFile.close(); return true; }
GameState::GameState(sf::RenderWindow& app, const ArchetypesManager& archMan, std::string gameFile) : level(app, archMan) { std::ifstream levelFile("resources/" + gameFile); level.read(levelFile); std::cerr << "Level read\n"; clock.restart(); }
void LevelManager::LoadLevel(const Message& m) { Log("Level load message received, loading level..."); string levelFile("levels/racetrackLevel"); levelFile.append(m.msg.begin() + 1, m.msg.end()); levelFile.append(".irr"); engine->smgr->loadScene(levelFile.c_str()); auto carNode = engine->smgr->getSceneNodeFromName("start1"); camera = engine->smgr->addCameraSceneNode(carNode); // do bullet stuff network->BroadcastMessage("l", 'A'); Log("Level load complete, acknowledgement sent."); }
void XMLSerializer::Load( const std::string& levelPath ) { if ( !Management::Get( )->GetFileManager( )->FileExists( levelPath ) ) { std::stringstream logMessage; logMessage << "Unable to locate level file at path: " << levelPath; Logger::Get( )->Warn( logMessage.str( ) ); return; } _loadProgress = 0; _loadTotal = 0; Management::Get( )->GetEventManager( )->QueueEvent( new ScriptEvent( "WORLD_LOADING_STARTED", levelPath ) ); IResource* resource = Management::Get( )->GetResourceManager( )->GetResource( levelPath ); Document levelFile( resource->GetFileBuffer()->fileBytes ); this->LoadElement( levelFile.FirstChildElement( ) ); }
bool Level::LoadFromFile(std::string filename)//двоеточия-обращение к методам класса вне класса { TiXmlDocument levelFile(filename.c_str());//загружаем файл в TiXmlDocument // загружаем XML-карту if (!levelFile.LoadFile())//если не удалось загрузить карту { std::cout << "Loading level \"" << filename << "\" failed." << std::endl;//выдаем ошибку return false; } // работаем с контейнером map TiXmlElement *map; map = levelFile.FirstChildElement("map"); // пример карты: <map version="1.0" orientation="orthogonal" // width="10" height="10" tilewidth="34" tileheight="34"> width = atoi(map->Attribute("width"));//извлекаем из нашей карты ее свойства height = atoi(map->Attribute("height"));//те свойства, которые задавали при работе в tileWidth = atoi(map->Attribute("tilewidth"));//тайлмап редакторе tileHeight = atoi(map->Attribute("tileheight")); // Берем описание тайлсета и идентификатор первого тайла TiXmlElement *tilesetElement; tilesetElement = map->FirstChildElement("tileset"); firstTileID = atoi(tilesetElement->Attribute("firstgid")); // source - путь до картинки в контейнере image TiXmlElement *image; image = tilesetElement->FirstChildElement("image"); std::string imagepath = image->Attribute("source"); // пытаемся загрузить тайлсет sf::Image img; if (!img.loadFromFile(imagepath)) { std::cout << "Failed to load tile sheet." << std::endl;//если не удалось загрузить тайлсет-выводим ошибку в консоль return false; } img.createMaskFromColor(sf::Color(255, 255, 255));//для маски цвета.сейчас нет маски tilesetImage.loadFromImage(img); tilesetImage.setSmooth(false);//сглаживание // получаем количество столбцов и строк тайлсета int columns = tilesetImage.getSize().x / tileWidth; int rows = tilesetImage.getSize().y / tileHeight; // вектор из прямоугольников изображений (TextureRect) std::vector<sf::Rect<int> > subRects; for (int y = 0; y < rows; y++) for (int x = 0; x < columns; x++) { sf::Rect<int> rect; rect.top = y * tileHeight; rect.height = tileHeight; rect.left = x * tileWidth; rect.width = tileWidth; subRects.push_back(rect); } // работа со слоями TiXmlElement *layerElement; layerElement = map->FirstChildElement("layer"); while (layerElement) { Layer layer; // если присутствует opacity, то задаем прозрачность слоя, иначе он полностью непрозрачен if (layerElement->Attribute("opacity") != NULL) { float opacity = strtod(layerElement->Attribute("opacity"), NULL); layer.opacity = 255 * opacity; } else { layer.opacity = 255; } // контейнер <data> TiXmlElement *layerDataElement; layerDataElement = layerElement->FirstChildElement("data"); if (layerDataElement == NULL) { std::cout << "Bad map. No layer information found." << std::endl; } // контейнер <tile> - описание тайлов каждого слоя TiXmlElement *tileElement; tileElement = layerDataElement->FirstChildElement("tile"); if (tileElement == NULL) { std::cout << "Bad map. No tile information found." << std::endl; return false; } int x = 0; int y = 0; while (tileElement) { int tileGID = atoi(tileElement->Attribute("gid")); int subRectToUse = tileGID - firstTileID; // Устанавливаем TextureRect каждого тайла if (subRectToUse >= 0) { sf::Sprite sprite; sprite.setTexture(tilesetImage); sprite.setTextureRect(subRects[subRectToUse]); sprite.setPosition(x * tileWidth, y * tileHeight); sprite.setColor(sf::Color(255, 255, 255, layer.opacity)); layer.tiles.push_back(sprite);//закидываем в слой спрайты тайлов } tileElement = tileElement->NextSiblingElement("tile"); x++; if (x >= width) { x = 0; y++; if (y >= height) y = 0; } } layers.push_back(layer); layerElement = layerElement->NextSiblingElement("layer"); } // работа с объектами TiXmlElement *objectGroupElement; // если есть слои объектов if (map->FirstChildElement("objectgroup") != NULL) { objectGroupElement = map->FirstChildElement("objectgroup"); while (objectGroupElement) { // контейнер <object> TiXmlElement *objectElement; objectElement = objectGroupElement->FirstChildElement("object"); while (objectElement) { // получаем все данные - тип, имя, позиция, и тд std::string objectType; if (objectElement->Attribute("type") != NULL) { objectType = objectElement->Attribute("type"); } std::string objectName; if (objectElement->Attribute("name") != NULL) { objectName = objectElement->Attribute("name"); } int x = atoi(objectElement->Attribute("x")); int y = atoi(objectElement->Attribute("y")); int width, height; sf::Sprite sprite; sprite.setTexture(tilesetImage); sprite.setTextureRect(sf::Rect<int>(0, 0, 0, 0)); sprite.setPosition(x, y); if (objectElement->Attribute("width") != NULL) { width = atoi(objectElement->Attribute("width")); height = atoi(objectElement->Attribute("height")); } else { width = subRects[atoi(objectElement->Attribute("gid")) - firstTileID].width; height = subRects[atoi(objectElement->Attribute("gid")) - firstTileID].height; sprite.setTextureRect(subRects[atoi(objectElement->Attribute("gid")) - firstTileID]); } // экземпляр объекта Object object; object.name = objectName; object.type = objectType; object.sprite = sprite; sf::Rect <float> objectRect; objectRect.top = y; objectRect.left = x; objectRect.height = height; objectRect.width = width; object.rect = objectRect; // "переменные" объекта TiXmlElement *properties; properties = objectElement->FirstChildElement("properties"); if (properties != NULL) { TiXmlElement *prop; prop = properties->FirstChildElement("property"); if (prop != NULL) { while (prop) { std::string propertyName = prop->Attribute("name"); std::string propertyValue = prop->Attribute("value"); object.properties[propertyName] = propertyValue; prop = prop->NextSiblingElement("property"); } } } objects.push_back(object); objectElement = objectElement->NextSiblingElement("object"); } objectGroupElement = objectGroupElement->NextSiblingElement("objectgroup"); } } else { std::cout << "No object layers found..." << std::endl; } return true; }
void TestLevel::LoadLevelFromFile() { std::ifstream levelFile("Levels\\0.txt", std::ios::in | std::ios::ate); if (levelFile.is_open()) { std::streampos size; char* levelInfo; size = levelFile.tellg(); levelInfo = new char[size]; levelFile.seekg(0, std::ios::beg); levelFile.read(levelInfo, size); levelFile.close(); std::cout << "SIZE " << size << "\n"; float gridSize = 2; int x = 0; int z = 0; CrateDropper* dropper = nullptr; bool wasLast = false; for (int c = 0; c < size; c++) { if (levelInfo[c] == '\n') { z++; x = 0; wasLast = true; } else { x++; switch (levelInfo[c]) { case 'N': case 'E': case 'S': case 'W': { GameObject* wall = new GameObject(); wall->AddComponent(new ModelRender("DinoLasers\\Wall.obj", "Wall")); BoundingObject* wallBO = new BoundingObject(); wallBO->SetLayer(2 | 4 | 8 | 16); wallBO->SetIsMoveable(false); wall->AddComponent(wallBO); if (!wasLast && (levelInfo[c - 1] == '#' || levelInfo[c + 1] == '#')) { //wallBO->SetIgnoreAxis(0); //wall->GetTransform().SetScale(vector3(0.8f)); } else { //wallBO->SetIgnoreAxis(2); } gridSize = wallBO->GetHalfWidth()[0] * 2; wall->GetTransform().SetPosition(vector3(static_cast<float>(x)* gridSize, 0.0f, static_cast<float>(z)* gridSize)); //wall->GetTransform().SetOrentation(quaternion(vector3(0.0f, (rand() % 4) * glm::pi<float>() / 2, 0.0f))); //wallBO->SetIgnoreAxis(0); if (levelInfo[c] == 'N') { wallBO->SetIgnoreAxis(0); } else if (levelInfo[c] == 'E') { //wallBO->SetIgnoreAxis(0); } else if (levelInfo[c] == 'S') { wallBO->SetIgnoreAxis(2); } else if (levelInfo[c] == 'W') { wallBO->SetIgnoreAxis(8); } GameObjectManager::GetInstance()->AddGameObject(wall); } break; case 'D': { dino->GetTransform().SetPosition(vector3(static_cast<float>(x)* gridSize, 0.0f, static_cast<float>(z)* gridSize)); } break; case 'C': { if (dropper == nullptr) { dropper = crateDropper->GetComponent<CrateDropper>(); } dropper->AddSpawnPoint(vector3(static_cast<float>(x)* gridSize, 10.0f, static_cast<float>(z)* gridSize)); } break; } wasLast = false; } } delete[] levelInfo; } else { std::cout << "ERROR LOADING FILE" << std::endl; } }
bool Level::LoadFromFile(std::string filename) { TiXmlDocument levelFile(filename.c_str()); // Загружаем XML-карту if(!levelFile.LoadFile()) { std::cout << "Loading level \"" << filename << "\" failed." << std::endl; return false; } // Работаем с контейнером map TiXmlElement *map; map = levelFile.FirstChildElement("map"); // Пример карты: <map version="1.0" orientation="orthogonal" // width="10" height="10" tilewidth="34" tileheight="34"> width = atoi(map->Attribute("width")); height = atoi(map->Attribute("height")); tileWidth = atoi(map->Attribute("tilewidth")); tileHeight = atoi(map->Attribute("tileheight")); // Берем описание тайлсета и идентификатор первого тайла TiXmlElement *tilesetElement; tilesetElement = map->FirstChildElement("tileset"); firstTileID = atoi(tilesetElement->Attribute("firstgid")); // source - путь до картинки в контейнере image TiXmlElement *image; image = tilesetElement->FirstChildElement("image"); std::string imagepath = image->Attribute("source"); // Пытаемся загрузить тайлсет sf::Image img; if(!img.loadFromFile(imagepath)) { std::cout << "Failed to load tile sheet." << std::endl; return false; } // Очищаем карту от света (109, 159, 185) // Вообще-то в тайлсете может быть фон любого цвета, но я не нашел решения, как 16-ричную строку // вроде "6d9fb9" преобразовать в цвет img.createMaskFromColor(sf::Color(109, 159, 185)); // Грузим текстуру из изображения tilesetImage.loadFromImage(img); // Расплывчатость запрещена tilesetImage.setSmooth(false); // Получаем количество столбцов и строк тайлсета int columns = tilesetImage.getSize().x / tileWidth; int rows = tilesetImage.getSize().y / tileHeight; // Вектор из прямоугольников изображений (TextureRect) std::vector<sf::Rect<int> > subRects; for(int y = 0; y < rows; y++) for(int x = 0; x < columns; x++) { sf::Rect<int> rect; rect.top = y * tileHeight; rect.height = tileHeight; rect.left = x * tileWidth; rect.width = tileWidth; subRects.push_back(rect); } // Работа со слоями TiXmlElement *layerElement; layerElement = map->FirstChildElement("layer"); while(layerElement) { Layer layer; // Если присутствует opacity, то задаем прозрачность слоя, иначе он полностью непрозрачен if (layerElement->Attribute("opacity") != NULL) { float opacity = strtod(layerElement->Attribute("opacity"), NULL); layer.opacity = 255 * opacity; } else { layer.opacity = 255; } // Контейнер <data> TiXmlElement *layerDataElement; layerDataElement = layerElement->FirstChildElement("data"); if(layerDataElement == NULL) { std::cout << "Bad map. No layer information found." << std::endl; } // Контейнер <tile> - описание тайлов каждого слоя TiXmlElement *tileElement; tileElement = layerDataElement->FirstChildElement("tile"); if(tileElement == NULL) { std::cout << "Bad map. No tile information found." << std::endl; return false; } int x = 0; int y = 0; while(tileElement) { int tileGID = atoi(tileElement->Attribute("gid")); int subRectToUse = tileGID - firstTileID; // Устанавливаем TextureRect каждого тайла if (subRectToUse >= 0) { sf::Sprite sprite; sprite.setTexture(tilesetImage); sprite.setTextureRect(subRects[subRectToUse]); sprite.setPosition(x * tileWidth, y * tileHeight); sprite.setColor(sf::Color(255, 255, 255, layer.opacity)); layer.tiles.push_back(sprite); } tileElement = tileElement->NextSiblingElement("tile"); x++; if (x >= width) { x = 0; y++; if(y >= height) y = 0; } } layers.push_back(layer); layerElement = layerElement->NextSiblingElement("layer"); } // Работа с объектами TiXmlElement *objectGroupElement; // Если есть слои объектов if (map->FirstChildElement("objectgroup") != NULL) { objectGroupElement = map->FirstChildElement("objectgroup"); while (objectGroupElement) { // Контейнер <object> TiXmlElement *objectElement; objectElement = objectGroupElement->FirstChildElement("object"); while(objectElement) { // Получаем все данные - тип, имя, позиция, etc std::string objectType; if (objectElement->Attribute("type") != NULL) { objectType = objectElement->Attribute("type"); } std::string objectName; if (objectElement->Attribute("name") != NULL) { objectName = objectElement->Attribute("name"); } int x = atoi(objectElement->Attribute("x")); int y = atoi(objectElement->Attribute("y")); int width, height; sf::Sprite sprite; sprite.setTexture(tilesetImage); sprite.setTextureRect(sf::Rect<int>(0,0,0,0)); sprite.setPosition(x, y); if (objectElement->Attribute("width") != NULL) { width = atoi(objectElement->Attribute("width")); height = atoi(objectElement->Attribute("height")); } else { width = subRects[atoi(objectElement->Attribute("gid")) - firstTileID].width; height = subRects[atoi(objectElement->Attribute("gid")) - firstTileID].height; sprite.setTextureRect(subRects[atoi(objectElement->Attribute("gid")) - firstTileID]); } // Экземпляр объекта Object object; object.name = objectName; object.type = objectType; object.sprite = sprite; sf::Rect <int> objectRect; objectRect.top = y; objectRect.left = x; objectRect.height = height; objectRect.width = width; object.rect = objectRect; // "Переменные" объекта TiXmlElement *properties; properties = objectElement->FirstChildElement("properties"); if (properties != NULL) { TiXmlElement *prop; prop = properties->FirstChildElement("property"); if (prop != NULL) { while(prop) { std::string propertyName = prop->Attribute("name"); std::string propertyValue = prop->Attribute("value"); object.properties[propertyName] = propertyValue; prop = prop->NextSiblingElement("property"); } } } // Пихаем объект в вектор objects.push_back(object); objectElement = objectElement->NextSiblingElement("object"); } objectGroupElement = objectGroupElement->NextSiblingElement("objectgroup"); } } else { std::cout << "No object layers found..." << std::endl; } return true; }
bool Level::LoadFromFile(std::string filename) { TiXmlDocument levelFile(filename.c_str()); if (!levelFile.LoadFile()) { std::cout << "Loading level \"" << filename << "\" failed." << std::endl; return false; } //Map element. This is the root element for the whole file. TiXmlElement *map; map = levelFile.FirstChildElement("map"); //Set up misc map properties. width = atoi(map->Attribute("width")); height = atoi(map->Attribute("height")); tileWidth = atoi(map->Attribute("tilewidth")); tileHeight = atoi(map->Attribute("tileheight")); //Tileset stuff TiXmlElement *tilesetElement; tilesetElement = map->FirstChildElement("tileset"); firstTileID = atoi(tilesetElement->Attribute("firstgid")); //Tileset image TiXmlElement *image; image = tilesetElement->FirstChildElement("image"); std::string imagepath = image->Attribute("source"); if (!tilesetImage.loadFromFile("Images/"+imagepath))//Load the tileset image { std::cout << "Failed to load tile sheet." << std::endl; return false; } tilesetImage.setSmooth(false); //Columns and rows (of tileset image) int columns = tilesetImage.getSize().x / tileWidth; int rows = tilesetImage.getSize().y / tileHeight; std::vector <sf::Rect<int> > subRects;//container of subrects (to divide the tilesheet image up) //tiles/subrects are counted from 0, left to right, top to bottom for (int y = 0; y < rows; y++) { for (int x = 0; x < columns; x++) { sf::Rect <int> rect; rect.top = y * tileHeight; rect.height = y * tileHeight + tileHeight; rect.left = x * tileWidth; rect.width = x * tileWidth + tileWidth; subRects.push_back(rect); } } //Layers TiXmlElement *layerElement; layerElement = map->FirstChildElement("layer"); while (layerElement) { Layer layer; if (layerElement->Attribute("opacity") != NULL)//check if opacity attribute exists { float opacity = strtod(layerElement->Attribute("opacity"), NULL);//convert the (string) opacity element to float layer.opacity = 255 * opacity; } else { layer.opacity = 255;//if the attribute doesnt exist, default to full opacity } //Tiles TiXmlElement *layerDataElement; layerDataElement = layerElement->FirstChildElement("data"); if (layerDataElement == NULL) { std::cout << "Bad map. No layer information found." << std::endl; } TiXmlElement *tileElement; tileElement = layerDataElement->FirstChildElement("tile"); if (tileElement == NULL) { std::cout << "Bad map. No tile information found." << std::endl; return false; } int x = 0; int y = 0; while (tileElement) { int tileGID = atoi(tileElement->Attribute("gid")); int subRectToUse = tileGID - firstTileID;//Work out the subrect ID to 'chop up' the tilesheet image. if (subRectToUse >= 0)//we only need to (and only can) create a sprite/tile if there is one to display { sf::Sprite sprite;//sprite for the tile sprite.setTexture(tilesetImage); sprite.setTextureRect(subRects[subRectToUse]); sprite.setPosition(x * tileWidth, y * tileHeight); sprite.setColor(sf::Color(255, 255, 255, layer.opacity));//Set opacity of the tile. //add tile to layer layer.tiles.push_back(sprite); } tileElement = tileElement->NextSiblingElement("tile"); //increment x, y x++; if (x >= width)//if x has "hit" the end (right) of the map, reset it to the start (left) { x = 0; y++; if (y >= height) { y = 0; } } } layers.push_back(layer); layerElement = layerElement->NextSiblingElement("layer"); } //Objects TiXmlElement *objectGroupElement; if (map->FirstChildElement("objectgroup") != NULL)//Check that there is atleast one object layer { objectGroupElement = map->FirstChildElement("objectgroup"); while (objectGroupElement)//loop through object layers { TiXmlElement *objectElement; objectElement = objectGroupElement->FirstChildElement("object"); while (objectElement)//loop through objects { std::string objectType; if (objectElement->Attribute("type") != NULL) { objectType = objectElement->Attribute("type"); } std::string objectName; if (objectElement->Attribute("name") != NULL) { objectName = objectElement->Attribute("name"); } int x = atoi(objectElement->Attribute("x")); int y = atoi(objectElement->Attribute("y")); int width = atoi(objectElement->Attribute("width")); int height = atoi(objectElement->Attribute("height")); Object object; object.name = objectName; object.type = objectType; sf::Rect <int> objectRect; objectRect.top = y; objectRect.left = x; objectRect.height = y + height; objectRect.width = x + width; if (objectType == "solid") { solidObjects.push_back(objectRect); } object.rect = objectRect; TiXmlElement *properties; properties = objectElement->FirstChildElement("properties"); if (properties != NULL) { TiXmlElement *prop; prop = properties->FirstChildElement("property"); if (prop != NULL) { while(prop) { std::string propertyName = prop->Attribute("name"); std::string propertyValue = prop->Attribute("value"); object.properties[propertyName] = propertyValue; prop = prop->NextSiblingElement("property"); } } } objects.push_back(object); objectElement = objectElement->NextSiblingElement("object"); } objectGroupElement = objectGroupElement->NextSiblingElement("objectgroup"); } } else { std::cout << "No object layers found..." << std::endl; } return true; }
int main(int argc, char* argv[]) { if (!setupGLFW()) return 1; glfwWindowHint(GLFW_SAMPLES, 4); setupCoreGL(); #ifndef __APPLE__ const char* exePath = dirname(argv[0]); const char* resPath = "/Resources/"; const int newPathLen = strlen(exePath) + strlen(resPath) + 1; char newPath[newPathLen]; strcpy(newPath, exePath); strcat(newPath, resPath); int cwdError; if ((cwdError = chdir(newPath)) != 0) { perror(newPath); return 1; } #endif set_log_file(fopen("../Logs/uf.log", "a")); setDebug(DEBUG); setBind(DEBUG); #ifdef FULLSCREEN GLFWmonitor* monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* vidmode = glfwGetVideoMode(monitor); int width = vidmode->width; int height = vidmode->height; const char* title = "Ultra Fighters"; GLFWwindow* window = glfwCreateWindow(width, height, title, monitor, NULL); #else int width = 640; int height = 480; const char* title = "Ultra Fighters"; GLFWwindow* window = glfwCreateWindow(width, height, title, NULL, NULL); #endif if (!window) { log_msg(LOG_ERROR, "GLFW3 window creation failed.\n"); return 1; } glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); char cwd[PATH_MAX]; getcwd(cwd, sizeof(cwd)); log_msg(LOG_INFO, "#####################################\n"); log_msg(LOG_INFO, "Started Ultra Fighters!\n"); log_msg(LOG_INFO, "Current Working Directory: %s\n", cwd); log_msg(LOG_INFO, "Started loop!\n"); GameScene scene(window); std::ifstream levelFile("levelname.txt"); std::string levelName; std::getline(levelFile, levelName); WavefrontObject room(levelName.c_str()); scene.addChild(&room); HUD hud; scene.addChild(&hud); SphereNode snode(glm::vec3(-2, 2, 4), 0.75); // @temp scene.addChild(&snode); // @temp Loop loop = Loop(&scene); loop.start(); while (!glfwGetKey(window, GLFW_KEY_ESCAPE) && !glfwWindowShouldClose(window)) { glfwPollEvents(); } log_msg(LOG_INFO, "Stopping program...\n"); loop.stop(); glfwTerminate(); return 0; }
void Board::init(Image image, QString levelName) { prisonEntry = OUT; prisonExit = OUT; fruitHome = OUT; fruitPosition = OUT; pacmanHome = OUT; pacmanPosition = OUT; for (int m = 0; m < 8; m++) { monsterHome[m] = OUT; monsterPosition[m] = OUT; } for (int e = 0; e < 8; e++) { energizerPosition[e] = OUT; } for (int e = 0; e < 8; e++) { tunnelPosition[e] = OUT; } fill(0); numPoints = 0; numEnergizers = 0; numMonsters = 0; numTunnels = 0; if (!levelName.isNull() && !levelName.isEmpty()) if (mapName == levelName) image = File; else { QFile levelFile(levelName); if (!levelFile.open(IO_ReadOnly)) { QString msg = "The levelmap could not be constructed.\n\n" "The file '@LEVELNAME@' does not exist,\n" "or could not be opened for reading."; msg.replace(QRegExp("@LEVELNAME@"), levelName); // QMessageBox::information(0, tr("Initialization Error"), msg); printf("%s\n", msg.data()); } else { map.fill(' ', BoardHeight*BoardWidth); int height = 0; QTextStream levelStream(&levelFile); while (!levelStream.eof() && height < BoardHeight) { QString line = levelStream.readLine(); if (line.find(QRegExp("^ *;")) == -1) { line.replace(QRegExp(";.*"), ""); // strip off comments line.replace(QRegExp("\" *$"), ""); // strip off trailing " line.replace(QRegExp("^ *\""), ""); // strip off leading " map.replace(height*BoardWidth, (line.length() > BoardWidth) ? BoardWidth : line.length(), line.data()); height++; } } mapName = levelName; levelFile.close(); image = File; } } switch (image) { case Intro : // setup(demo_bits); break; case Demo : setup(demo_bits); break; case Level : setup(demo_bits); break; case File : setup((uchar *) map.data()); break; default : break; } }