From 8735edb3ad40ec5dc66bbaa12653efbf52664b2d Mon Sep 17 00:00:00 2001 From: Benedikt Galbavy Date: Tue, 30 Jan 2024 14:10:26 +0100 Subject: [PATCH] Rewrote map loader --- include/Map.h | 13 ++++++++++++- src/Map.cpp | 51 +++++++++++++++++++++++++++++++++++++++++---------- 2 files changed, 53 insertions(+), 11 deletions(-) diff --git a/include/Map.h b/include/Map.h index 3ab48e6..369cb6c 100644 --- a/include/Map.h +++ b/include/Map.h @@ -6,5 +6,16 @@ public: Map() = default; ~Map() = default; - static void loadMap(const char* path, int sizeX, int sizeY); + // code comment below is a test for doxygen - do not remove + + /*! + * + * \brief + * This loads a map + * + * \param path The path to the map file + * \return Boolean for success + * + */ + static bool loadMap(const char* path, int sizeX, int sizeY); }; diff --git a/src/Map.cpp b/src/Map.cpp index 859bd4e..84afed5 100644 --- a/src/Map.cpp +++ b/src/Map.cpp @@ -1,25 +1,56 @@ #include "Map.h" +#include +#include #include +#include #include "Constants.h" #include "Game.h" +#include "SDL_error.h" -void Map::loadMap(const char* path, int sizeX, int sizeY) +bool Map::loadMap(const char* path, int sizeX, int sizeY) { - char tile; - std::fstream mapFile; + std::string tileIDstr; + char singleChar; + std::ifstream mapFile; mapFile.open(path); - - for (int y = 0; y < sizeY; y++) + + if (!mapFile.is_open()) { + SDL_SetError("Error loading map: Couldn't open map file!"); + return false; + } + + int x = 0, y = 0; // needed outside for-loop for error handling + bool success = true; + for (; !mapFile.eof(); mapFile.get(singleChar)) { - for (int x = 0; x < sizeX; x++) - { - mapFile.get(tile); - Game::addTile(atoi(&tile), x * TILE_SIZE, y * TILE_SIZE); - mapFile.ignore(); + if (singleChar == ',' || singleChar == '\n') { + if (tileIDstr.empty()) + continue; + Game::addTile(std::stoi(tileIDstr), x * TILE_SIZE, y * TILE_SIZE); + tileIDstr.clear(); + if (singleChar == '\n') { + if (x != sizeX) { + SDL_SetError("Error loading map: specified x size doesn't match map file!"); + success = false; + } + x = 0; + y++; + continue; + } + x++; + continue; } + if (!std::isdigit(singleChar)) continue; + tileIDstr += singleChar; + } + if (y != sizeY) { + SDL_SetError("Error loading map: specified y size doesn't match map file!"); + success = false; } mapFile.close(); + + return success }