binpress

Creating a City Building Game with SFML Part 7: Tile Selection

Get started with this tutorial series here!

With that all done we can start to add the ability to change the Map by bulldozing tiles and placing new ones. For this to work we’d need a way for the player to select the tiles to be changed. For this we will use an std::vector like tiles, but it will store ints instead. The player will left click and drag to select the tiles, and when they release the left mouse button the selection will be replaced with the new tiles. First then, we’ll need to create this std::vector. Whilst it is only relevant to the GameStateEditor class, we will place it in Map instead, as it’s far easier to manage there.

  1. /* 0 = Deselected, 1 = Selected, 2 = Invalid */
  2. std::vector<char> selected;
  3. unsigned int numSelected;
  4.  
  5. /* Select the tiles within the bounds */
  6. void select(sf::Vector2i start, sf::Vector2i end, std::vector<TileType> blacklist);
  7.  
  8. /* Deselect all tiles */
  9. void clearSelected();

We’ve used chars instead of ints to be more efficient but we’ll still interpret them as numbers. numSelected is, unsurprisingly, the number of tiles that are currently selected (and are not invalid). We have the extra invalid option (so sadly we can’t use an std::vector<bool>) for tiles that are within the selection area but cannot be replaced by the tile we are planning on adding (no zones over rivers, for example). We then have the select function that selects all the tiles within the bounding rectangle of start and end, and sets all the tiles within that rectangle that are in the blacklistto invalid. Finally, we have clearSelected to just deselect every tile.

Now we have to update the constructors

  1. /* Blank map constructor */
  2. Map()
  3. {
  4.     this->numSelected = 0;
  5.     this->tileSize = 8;
  6.     this->width = 0;
  7.     this->height = 0;
  8.     this->numRegions[0] = 1;
  9. }
  10. /* Load map from file constructor */
  11. Map(const std::string& filename, unsigned int width, unsigned int height,
  12.     std::map<std::string, Tile>& tileAtlas)
  13. {
  14.     this->numSelected = 0;
  15.     this->tileSize = 8;
  16.     load(filename, width, height, tileAtlas);
  17. }

With the data structures and declarations set up, let’s go to map.cpp to write the function definitions for select and clearSelected.

  1. void Map::clearSelected()
  2. {
  3.     for(auto& tile : this->selected) tile = 0;
  4.  
  5.     this->numSelected = 0;
  6.  
  7.     return;
  8. }
  9.  
  10. void Map::select(sf::Vector2i start, sf::Vector2i end, std::vector<TileType> blacklist)
  11. {
  12.     /* Swap coordinates if necessary */
  13.     if(end.y < start.y) std::swap(start.y, end.y);
  14.     if(end.x < start.x) std::swap(start.x, end.x);
  15.  
  16.     /* Clamp in range */
  17.     if(end.x >= this->width)      end.x = this->width - 1;
  18.     else if(end.x < 0)               end.x = 0;
  19.     if(end.y >= this->height)         end.y = this->height - 1;
  20.     else if(end.y < 0)               end.y = 0;
  21.     if(start.x >= this->width)        start.x = this->width - 1;
  22.     else if(start.x < 0)             start.x = 0;
  23.     if (start.y >= this->height)  start.y = this->height - 1;
  24.     else if(start.y < 0)             start.y = 0;
  25.  
  26.     for(int y = start.y; y <= end.y; ++y)
  27.     {
  28.         for(int x = start.x; x <= end.x; ++x)
  29.         {
  30.             /* Check if the tile type is in the blacklist. If it is, mark it as
  31.              * invalid, otherwise select it */
  32.             this->selected[y*this->width+x] = 1;
  33.             ++this->numSelected;
  34.             for(auto type : blacklist)
  35.             {
  36.                 if(this->tiles[y*this->width+x].tileType == type)
  37.                 {
  38.                     this->selected[y*this->width+x] = 2;
  39.                     --this->numSelected;
  40.                     break;
  41.                 }
  42.             }
  43.         }
  44.     }
  45.  
  46.     return;
  47. }

I don’t think clearSelected requires explanation anymore, but select deserves some. We first make sure that the bounding rectangle is extending down and to the right (increasing in both axes) by using the std::swap function (found in the <algorithm> header) to make sure that the startcoordinates are smaller than the end ones. We then ensure that the bounding rectangle does not extend off the edges of the map (this would cause a buffer overflow, which we certainly do not want!), before starting at the top left of the rectangle and iterating over every tile within it. To save us an ifwe just default to selecting the tile, and then mark it as invalid if the tile’s tileType is in the blacklist. We have one more thing to in map.cpp; go to the load function and construct selected (the last line is the new one)

  1. /* Load map from disk */
  2. void Map::load(const std::string& filename, unsigned int width, unsigned int height,
  3.     std::map<std::string, Tile>& tileAtlas)
  4. {
  5.     std::ifstream inputFile;
  6.     inputFile.open(filename, std::ios::in | std::ios::binary);
  7.  
  8.     this->width = width;
  9.     this->height = height;
  10.  
  11.     for(int pos = 0; pos < this->width * this->height; ++pos)
  12.     {
  13.         this->resources.push_back(255);
  14.         this->selected.push_back(0);

With the selection functions in place the player needs a way to use them! As discussed before the left mouse button will control all of the selecting. Obviously this will be done in the GameStateEditorclass, so let’s go to game_state_editor.hpp and add a few necessary variables.

  1. enum class ActionState { NONE, PANNING, SELECTING };
  2.  
  3. class GameStateEditor : public GameState
  4. {
  5.     private:
  6.  
  7.     ActionState actionState;
  8.  
  9.     sf::View gameView;
  10.     sf::View guiView;
  11.  
  12.     Map map;
  13.  
  14.     sf::Vector2i panningAnchor;
  15.     float zoomLevel;
  16.  
  17.     sf::Vector2i selectionStart;
  18.     sf::Vector2i selectionEnd;
  19.  
  20.     Tile* currentTile;

As you can see we’ve added another entry to the ActionState enum, ActionState::SELECTING, and we’ve added two new sf::Vector2is, selectionStart and selectionEnd. These will be the start and end arguments that we pass to select. We’ve also added a pointer to a TilecurrentTile will point to whatever tile the player wants to replace the selection with. Not forgetting to initialize them in the constructor,

  1.     this->selectionStart = sf::Vector2i(0, 0);
  2.     this->selectionEnd = sf::Vector2i(0, 0);
  3.  
  4.     this->currentTile = &this->game->tileAtlas.at("grass");
  5.     this->actionState = ActionState::NONE;
  6. }

We’ll let the player choose currentTile later, for now we’ll just set it to the TileType::GRASStile. The selection code itself will be in the handleInput function like before, which now looks like:

  1. case sf::Event::MouseMoved:
  2. {
  3.     /* Pan the camera */
  4.     if(this->actionState == ActionState::PANNING)
  5.     {
  6.         sf::Vector2f pos = sf::Vector2f(sf::Mouse::getPosition(this->game->window) - this->panningAnchor);
  7.         gameView.move(-1.0f * pos * this->zoomLevel);
  8.         panningAnchor = sf::Mouse::getPosition(this->game->window);
  9.     }
  10.     /* Select tiles */
  11.     else if(actionState == ActionState::SELECTING)
  12.     {
  13.         sf::Vector2f pos = this->game->window.mapPixelToCoords(sf::Mouse::getPosition(this->game->window), this->gameView);
  14.         selectionEnd.x = pos.y / (this->map.tileSize) + pos.x / (2*this->map.tileSize) - this->map.width * 0.5 - 0.5;
  15.         selectionEnd.y = pos.y / (this->map.tileSize) - pos.x / (2*this->map.tileSize) + this->map.width * 0.5 + 0.5;
  16.  
  17.         this->map.clearSelected();
  18.         if(this->currentTile->tileType == TileType::GRASS)
  19.         {
  20.             this->map.select(selectionStart, selectionEnd, {this->currentTile->tileType, TileType::WATER});
  21.         }
  22.         else
  23.         {
  24.             this->map.select(selectionStart, selectionEnd,
  25.                 {
  26.                     this->currentTile->tileType,    TileType::FOREST,
  27.                     TileType::WATER,                TileType::ROAD,
  28.                     TileType::RESIDENTIAL,          TileType::COMMERCIAL,
  29.                     TileType::INDUSTRIAL
  30.                 });
  31.         }
  32.     }
  33.     break;
  34. }
  35. case sf::Event::MouseButtonPressed:
  36. {
  37.     /* Start panning */
  38.     if(event.mouseButton.button == sf::Mouse::Middle)
  39.     {
  40.         if(this->actionState != ActionState::PANNING)
  41.         {
  42.             this->actionState = ActionState::PANNING;
  43.             this->panningAnchor = sf::Mouse::getPosition(this->game->window);
  44.         }
  45.     }
  46.     else if(event.mouseButton.button == sf::Mouse::Left)
  47.     {
  48.         /* Select map tile */
  49.         if(this->actionState != ActionState::SELECTING)
  50.         {
  51.             this->actionState = ActionState::SELECTING;
  52.             sf::Vector2f pos = this->game->window.mapPixelToCoords(sf::Mouse::getPosition(this->game->window), this->gameView);
  53.             selectionStart.x = pos.y / (this->map.tileSize) + pos.x / (2*this->map.tileSize) - this->map.width * 0.5 - 0.5;
  54.             selectionStart.y = pos.y / (this->map.tileSize) - pos.x / (2*this->map.tileSize) + this->map.width * 0.5 + 0.5;
  55.         }
  56.     }
  57.     else if(event.mouseButton.button == sf::Mouse::Right)
  58.     {
  59.         /* Stop selecting */
  60.         if(this->actionState == ActionState::SELECTING)
  61.         {
  62.             this->actionState = ActionState::NONE;
  63.             this->map.clearSelected();
  64.         }
  65.     }
  66.     break;
  67. }
  68. case sf::Event::MouseButtonReleased:
  69. {
  70.     /* Stop panning */
  71.     if(event.mouseButton.button == sf::Mouse::Middle)
  72.     {
  73.         this->actionState = ActionState::NONE;
  74.     }
  75.     /* Stop selecting */
  76.     else if(event.mouseButton.button == sf::Mouse::Left)
  77.     {
  78.         if(this->actionState == ActionState::SELECTING)
  79.         {
  80.             this->actionState = ActionState::NONE;
  81.             this->map.clearSelected();
  82.         }
  83.     }
  84.     break;
  85. }

Examining what happens when the left mouse button is pressed, we see that if the player is not already selecting tiles then actionState is set accordingly and the position of the mouse in game world coordinates is recorded. We then use a far fancier looking formula than before to convert from the world coordinates to the Map coordinates. This is the reverse of what we did previously (tile coordinates to screen coordinates) and so a little bit of algebra can be used to rearrange the old equation into these new ones. I encourage you to try it out for yourself as sadly the derivation is too cumbersome to write in this format! I’m not just being lazy, I promise…

When the mouse is moved and the player is selecting tiles we repeat the same calculation on the new mouse position to compute the end point of the rectangle. We then use the select function to select the tiles. The if statement is there because the grass tile acts like a bulldozer, replacing anything that isn’t water with grass, but when placing any other tile you are building and not demolishing, and so the land must be free of other buildings first.

Hopefully this code should compile fine, and under the hood it should work although the selection box will not be visible. To fix this we need to go back into map.cpp (sorry, I was wrong when I said that was all!) and alter the draw function. A simple and effective way of marking the selection area is to simply darken all the tiles. We can do this using sf::Sprite‘s setColor function, which changes the overall color of the sprite using a color multiply. The sf::Color constructor takes rgb values from 0-255, or 0x0-0xff in hexadecimal

  1. /* Change the color if the tile is selected */
  2. if(this->selected[y*this->width+x])
  3.     this->tiles[y*this->width+x].sprite.setColor(sf::Color(0x7d, 0x7d, 0x7d));
  4. else
  5.     this->tiles[y*this->width+x].sprite.setColor(sf::Color(0xff, 0xff, 0xff));
  6.  
  7. /* Draw the tile */
  8. this->tiles[y*this->width+x].draw(window, dt);

If the Tile isn’t selected, we set it’s color to white (so that it is unchanged) and if it is we halve its brightness. Now running the code should allow you to draw lovely selection boxes! They might not do anything, but at it’s a step in the right direction.

Source code for this section

Author: Daniel Mansfield

Scroll to Top