Creating a City Building Game with SFML Part 5: The Game World

Get started with this tutorial series here!

With the Tile class now in place we can put them to use by combining them into a Map. The Mapclass will contain a 2D array of Tiles as well as a bunch of helper variables and functions for altering the array. This will be our largest class yet (definition-wise, there aren’t too many declarations) as some of the functions are complicated. But anyway, let’s examine map.hpp

  1. #ifndef MAP_HPP
  2. #define MAP_HPP
  4. #include <SFML/Graphics.hpp>
  6. #include <string>
  7. #include <map>
  8. #include <vector>
  10. #include "tile.hpp"
  12. class Map
  13. {
  14.     private:
  16.     void depthfirstsearch(std::vector<TileType>& whitelist,
  17.         sf::Vector2i pos, int label, int type);
  19.     public:
  21.     unsigned int width;
  22.     unsigned int height;
  24.     std::vector<Tile> tiles;
  26.     /* Resource map */
  27.     std::vector<int> resources;
  29.     unsigned int tileSize;
  31.     unsigned int numSelected;
  33.     unsigned int numRegions[1];
  35.     /* Load map from disk */
  36.     void load(const std::string& filename, unsigned int width, unsigned int height,
  37.         std::map<std::string, Tile>& tileAtlas);
  39.     /* Save map to disk */
  40.     void save(const std::string& filename);
  42.     /* Draw the map */  
  43.     void draw(sf::RenderWindow& window, float dt);
  45.     /* Checks if one position in the map is connected to another by
  46.      * only traversing tiles in the whitelist */
  47.     void findConnectedRegions(std::vector<TileType> whitelist, int type);
  49.     /* Update the direction of directional tiles so that they face the correct
  50.      * way. Used to orient roads, pylons, rivers etc */
  51.     void updateDirection(TileType tileType);
  53.     /* Blank map constructor */
  54.     Map()
  55.     {
  56.         this->tileSize = 8;
  57.         this->width = 0;
  58.         this->height = 0;
  59.         this->numRegions[0] = 1;
  60.     }
  61.     /* Load map from file constructor */
  62.     Map(const std::string& filename, unsigned int width, unsigned int height,
  63.         std::map<std::string, Tile>& tileAtlas)
  64.     {
  65.         this->tileSize = 8;
  66.         load(filename, width, height, tileAtlas);
  67.     }
  68. };
  70. #endif /* MAP_HPP */

The width and height values are just the dimensions of the map, which we have to remember because we aren’t using a 2D array to contain the tiles (I’m sorry, I lied); we’re using a single std::vector and just pretending that it’s two dimensional. This makes it much simpler (and more efficient) to iterate through when the position of the tile is not needed, and it isn’t very complicated when the position is needed either.

The resources std::vector will be used later by the industrial zone tiles in order to produce their goods. Each tile will have a limited amount of resources that the zone can extract, which is what that array manages. Zones will also buy goods from other (smaller) zones that do have resources, and so industrial zones will not simply accelerate their production and then suddenly become useless. But that’s all for another tutorial! Right now we have a few simple variables, and then finally some functions. We will use a custom binary format to load and save the maps, which we’ll examine when we define the functions. Then there’s the now familiar draw function, and some rather simple constructors.

There’s three functions that we haven’t discussed; findConnectingRegionsdepthfirstsearch, and updateDirectionupdateDirection is simple (if tedious to implement) and iterates over each Tile in the Map, changing their tileVariant so as to change their animation and orient (if they have a correctly created texture) them in the correct direction. The other two functions will be used to split the Map into different regions, labeling them according to what region they fall in. The whitelist argument is simply a std::vector containing all the different TileTypes that can make up the region. So if you wanted a “greenery” region you might pass TileType::GRASS and TileType::FOREST as arguments. type is the index of the regions array in the Tile class that the region information should be stored in. Currently we only have one possible region, but as mentioned above more will be added later.

Now let’s begin creating map.cpp

  1. #include <SFML/Graphics.hpp>
  2. #include <string>
  3. #include <map>
  4. #include <vector>
  5. #include <fstream>
  7. #include "map.hpp"
  8. #include "tile.hpp"
  10. /* Load map from disk */
  11. void Map::load(const std::string& filename, unsigned int width, unsigned int height,
  12.     std::map<std::string, Tile>& tileAtlas)
  13. {
  14.     std::ifstream inputFile;
  15., std::ios::in | std::ios::binary);
  17.     this->width = width;
  18.     this->height = height;
  20.     for(int pos = 0; pos < this->width * this->height; ++pos)
  21.     {
  22.         this->resources.push_back(255);
  24.         TileType tileType;
  25.*)&tileType, sizeof(int));
  26.         switch(tileType)
  27.         {
  28.             default:
  29.             case TileType::VOID:
  30.             case TileType::GRASS:
  31.                 this->tiles.push_back("grass"));
  32.                 break;
  33.             case TileType::FOREST:
  34.                 this->tiles.push_back("forest"));
  35.                 break;
  36.             case TileType::WATER:
  37.                 this->tiles.push_back("water"));
  38.                 break;
  39.             case TileType::RESIDENTIAL:
  40.                 this->tiles.push_back("residential"));
  41.                 break;
  42.             case TileType::COMMERCIAL:
  43.                 this->tiles.push_back("commercial"));
  44.                 break;
  45.             case TileType::INDUSTRIAL:
  46.                 this->tiles.push_back("industrial"));
  47.                 break;
  48.             case TileType::ROAD:
  49.                 this->tiles.push_back("road"));
  50.                 break;
  51.         }
  52.         Tile& tile = this->tiles.back();
  53.*)&tile.tileVariant, sizeof(int));
  54.*)&tile.regions, sizeof(int)*1);
  55.*)&tile.population, sizeof(double));
  56.*)&tile.storedGoods, sizeof(float));
  57.     }
  59.     inputFile.close();
  61.     return;
  62. }

First we open a binary std::ifstream for the file specified. If you are not familiar with std::ifstream, it is the C++ way of reading from files. It inherits from the same class std::cindoes (both are input streams) and so has a very similar interface, although we won’t be using that here as we are dealing with binary files, not text files. Instead we will use the read member function. Once we’ve opened the stream we set width and height and then we loop enough times to read every Tile from the stream, reading the data upon each loop. read requires a char* as the first argument, which can be interpreted as a pointer to the start of an array of individual bytes (a char is the size of a byte).

The second argument is the number of bytes to read. If we pass a pointer to the variable we want to read and pretend it’s a char* pointer by using a cast, read will fill the variable with the data we want. We repeat this for all the variables we require. Note that in our first read call we are also pretending that tileType is of type int and not an enum; this is valid, as enums are (kind of) the same as ints, just referred to differently.

  1. void Map::save(const std::string& filename)
  2. {
  3.     std::ofstream outputFile;
  4., std::ios::out | std::ios::binary);
  6.     for(auto tile : this->tiles)
  7.     {
  8.         outputFile.write((char*)&tile.tileType, sizeof(int));
  9.         outputFile.write((char*)&tile.tileVariant, sizeof(int));
  10.         outputFile.write((char*)&tile.regions, sizeof(int)*1);
  11.         outputFile.write((char*)&tile.population, sizeof(double));
  12.         outputFile.write((char*)&tile.storedGoods, sizeof(float));
  13.     }
  15.     outputFile.close();
  17.     return;
  18. }

As you might expect, save is load in reverse. Well almost, we’re still processing the file in the same direction, so mostly we just replace the reads with writes! And we replace the std::ifstreamwith an std::ofstream of course. We then have a for loop, although in a form you won’t be familiar with unless you’ve seen some c++11; it says “for each tile in this->tiles, do the following” The auto keyword is another c++11 feature, and can be used instead of the variable’s type if the type is obvious. ‘auto’ is far easier to write than std::vector<Tile>::iterator, and without c++11 the loop would look far worse.

  1. void Map::draw(sf::RenderWindow& window, float dt)
  2. {
  3.     for(int y = 0; y < this->height; ++y)
  4.     {
  5.         for(int x = 0; x < this->width; ++x)
  6.         {
  7.             /* Set the position of the tile in the 2d world */
  8.             sf::Vector2f pos;
  9.             pos.x = (x - y) * this->tileSize + this->width * this->tileSize;
  10.             pos.y = (x + y) * this->tileSize * 0.5;
  11.             this->tiles[y*this->width+x].sprite.setPosition(pos);
  13.             /* Draw the tile */
  14.             this->tiles[y*this->width+x].draw(window, dt);
  15.         }
  16.     }
  17.     return;
  18. }

With the saving and loading functions done, we can write the code to draw the Map. For this we need to know the coordinates of the Tile, and so we use some normal nested for loops (y before x so we iterate horizontally first, and then vertically). We then have some formulae, seemingly conjured out of thin air, that convert the Map coordinates (x,y) to world coordinates that we can use to draw each Tile to the screen. They aren’t conjured from thin air however, and are created with just a small amount of reasoning!


Consider an isometric grid, where the very top point has coordinates (0, 0), the x axis extends along the right edge and the y axis extends along the left edge. If we increase x by 1, then pos.xwill increase by tileSize (remember tileSize is half the width, or the height, of each sprite) and pos.y will increase by tileSize * 0.5.

  1. pos.x = x * this->tileSize;
  2. pos.y = x * this->tileSize * 0.5;

If we increase y by 1, then pos.x will decrease by tileSize (follow along the grid lines) and pos.y will increase by tileSize * 0.5.

  1. pos.x = x * this->tileSize - y * this->tileSize;
  2. pos.y = x * this->tileSize * 0.5 + y * this->tileSize * 0.5;

With a tiny bit of algebra we get

  1. pos.x = (x - y) * this->tileSize;
  2. pos.y = (x + y) * this->tileSize * 0.5;

The way we’ve set up our coordinates means that all sprites to the left will have negative world coordinates. We don’t want that, so we shift the world coordinates to the right by half the width of the Map (in pixels). Once we’ve converted to the world coordinates, we set the position of the Tile‘s sprite and then draw it. Because we’re using a 1D std::vector instead of a 2D array, we have to convert our (x,y) coordinates to a single value by using index = y * this->width + x.

That’s all for now, in the next tutorial we will complete the definitions of the Map member functions!

Source code for this section

Author: Daniel Mansfield

Scroll to Top