Adding Bombs to the Grid

Updating the game to to place bombs randomly in the grid and render them when cells are cleared.

Ryan McCombe
Published

In this part of our Minesweeper tutorial, we'll build upon our existing code to add a crucial element of the game: bombs.

We'll implement the ability to place bombs randomly within our grid and reveal them when cells containing bombs are cleared.

We'll start by updating our global configurations to include new variables for bomb-related events and settings. Then, we'll modify our grid and cell classes to handle bomb placement and rendering.

By the end of this section, you'll have a Minesweeper grid where bombs can be placed and revealed, setting the stage for implementing the game's core mechanics in future parts.

Updating Globals

To begin implementing bombs in our Minesweeper game, we'll first update our Globals.h file with some new variables. These additions will help us manage bomb-related events and configure the game's difficulty:

  1. UserEvents::BOMB_PLACED: This new event type will be dispatched whenever a bomb is placed within a cell. This will allow other cells to keep track of how many bombs are in adjacent cells, which we'll use later to display the correct number.
  2. Config::BOMB_COUNT: This variable will control how many bombs are placed in the grid. By adjusting this number, we can easily change the difficulty of the game - more bombs generally mean a more challenging experience for the player.
  3. Config::BOMB_IMAGE: This string specifies the file name of the icon we want to render in cells that contain a bomb. By defining this in our global configuration, we can easily change the bomb image across our entire game if needed.
// Globals.h

// ...

namespace UserEvents{
  // ...
  inline Uint32 BOMB_PLACED =
    SDL_RegisterEvents(1);
}

namespace Config{
  inline constexpr int BOMB_COUNT{6};
  // ...

  // Asset Paths
  inline const std::string BOMB_IMAGE{
    "Bomb.png"};
  // ...
}

// ...

Placing Bombs in Random Cells

To implement bomb placement in our grid, we'll update our MinesweeperGrid class with a new PlaceBombs() function. This function will be responsible for randomly selecting cells and placing bombs in them.

Here's how the PlaceBombs() function will work:

  1. We'll create a loop that continues until we've placed the required number of bombs (specified by Config::BOMB_COUNT).
  2. In each iteration, we'll select a random index from our Children vector, which contains all the cells in our grid.
  3. We'll call a new PlaceBomb() function (which we'll add to our MinesweeperCell class later) on the randomly selected cell.
  4. If PlaceBomb() returns true, indicating a successful bomb placement, we'll decrement our counter of bombs to place.
  5. If PlaceBomb() returns false, indicating the selected cell already contains a bomb, we'll continue the loop to try placing the bomb in a different random cell.

This approach ensures that we place the correct number of bombs, and that no cell contains more than one bomb.

// Minesweeper/Grid.h
#pragma once
#include "Globals.h"
#include "Minesweeper/Cell.h"
#include "Engine/Random.h" 

class MinesweeperGrid {
// ...

private:
  void PlaceBombs(){
    int BombsToPlace{Config::BOMB_COUNT};
    while (BombsToPlace > 0) {
      const size_t RandomIndex{
        Engine::Random::Int(
          0, Children.size() - 1
        )};
      if (Children[RandomIndex].PlaceBomb()) {
        --BombsToPlace;
      }
    }
  }

  std::vector<MinesweeperCell> Children;
};

We'll call PlaceBombs() at the end of the MinesweeperGrid constructor.

// Minesweeper/Grid.h

// ...

class MinesweeperGrid {
public:
  MinesweeperGrid(int x, int y){
    // ...
    PlaceBombs();
  }
  
  // ...
};

Updating Cells to Receive Bombs

Now that we've implemented bomb placement in our grid, we need to update our MinesweeperCell class to handle bombs. We'll make the following changes:

  1. Add a new PlaceBomb() function that returns a bool. This function will be called by MinesweeperGrid when attempting to place a bomb in the cell.
  2. Add a hasBomb member variable to keep track of whether the cell contains a bomb.
  3. Create a GetHasBomb() getter function to allow other parts of our program to check if a cell contains a bomb without directly accessing the hasBomb variable.

Let's update our header file with these three declarations:

// Minesweeper/Cell.h

// ...

class MinesweeperCell : public Engine::Button {
public:
  // ...
  bool PlaceBomb();

  [[nodiscard]]
  bool GetHasBomb() const{ return hasBomb; }
  // ...

private:
  bool hasBomb{false};
  // ...
};

Over in our MinesweeperCell.cpp file, we'll implement the PlaceBomb() function. If the cell already has a bomb, we'll immediately return false, prompting the PlaceBombs() loop back in MinesweeperGrid to choose another cell.

Otherwise, we'll update our hasBomb member variable, report that a bomb has been placed, and return true to inform MinesweeperGrid that a bomb was successfully placed:

// Minesweeper/Cell.cpp

// ...

bool MinesweeperCell::PlaceBomb(){
  if (hasBomb) return false;
  hasBomb = true;
  ReportEvent(UserEvents::BOMB_PLACED);
  return true;
}

// ...

We'll also update our HandleEvent() function to react to bomb placement events.

For now, we'll just log that a bomb was placed, but in future parts, we'll use this to update the count of adjacent bombs for neighboring cells.

// Minesweeper/Cell.cpp

// ...

void MinesweeperCell::HandleEvent(
  const SDL_Event& E){
  if (E.type == UserEvents::CELL_CLEARED) {
    // TODO
    std::cout << "A Cell Was Cleared\n";
  } else if (E.type ==
    UserEvents::BOMB_PLACED) {
    // TODO
    std::cout << "A Bomb was Placed\n";
  }
  Button::HandleEvent(E);
}

// ...

We can now run our program and verify everything is connected correctly by looking at our terminal output. Every time a bomb is placed in a cell, every cell will react to the event, so we should see a long list of logs:

A Bomb was Placed
A Bomb was Placed
A Bomb was Placed
...

Naturally, we'll replace this logging with more meaningful reactions later.

Rendering Bomb Images

Finally, lets update our program to render the bomb images in the appropriate cells. We'll add a BombImage member variable:

// Minesweeper/Cell.h
#pragma once
#include "Engine/Button.h"
#include "Engine/Image.h"

class MinesweeperCell : public Engine::Button {
 // ...

private:
  Engine::Image BombImage;
};

Over in our constructor, we'll initialize it. Our Engine::Image class needs to know the position (x and y) and size (w and h) we want the image to be rendered on the surface. It also needs to know the location of the image file. We'll pass all of this information to its constructor:

// Minesweeper/Cell.cpp

// ...

MinesweeperCell::MinesweeperCell(
  int x, int y, int w, int h, int Row, int Col)
  : Button{x, y, w, h}, Row{Row}, Col{Col},
    BombImage{
      x, y, w, h,
      Config::BOMB_IMAGE}{};

// ...

Finally, we update the Render() method of our MinesweeperCell. If the player has cleared the cell and the cell contains a bomb, we render the image:

// Minesweeper/Cell.cpp

// ...

void MinesweeperCell::Render(
  SDL_Surface* Surface){
  Button::Render(Surface);
  if (isCleared && hasBomb) {
    BombImage.Render(Surface);
  }
}

If we run our game and clear cells, we should now eventually find a bomb:

Development Helpers

To make future development easier, it would be helpful to know where the bombs are without having to find them by clearing cells. In our Globals.h file, we created a preprocessor definition called SHOW_DEBUG_HELPERS.

We can use this preprocessor definition in our MinesweeperCell::Render() method to display bombs in all cells during development, regardless of whether they've been cleared:

// Minesweeper/Cell.cpp

// ...

void MinesweeperCell::Render(
  SDL_Surface* Surface){
  Button::Render(Surface);
  if (isCleared && hasBomb) {
    BombImage.Render(Surface);
  }
#ifdef SHOW_DEBUG_HELPERS
  else if (hasBomb) {
    BombImage.Render(Surface);
  }
#endif
}

When our preprocessor definition is enabled, we will be able to see bombs without clearing cells, which will make future development more convenient:

To enable these debug helpers, ensure the SHOW_DEBUG_HELPERS macro is defined in your Globals.h file. To disable them, simply comment out or remove the #define SHOW_DEBUG_HELPERS line:

// Globals.h

// #define SHOW_DEBUG_HELPERS 

// ...

Complete Code

Complete versions of the files we changed in this part are available below

Files not listed above have not been changed since the previous section.

Summary

In this part of our Minesweeper tutorial, we've made significant progress in implementing one of the core elements of the game: bombs. We are now:

  1. Implementing a system for randomly placing bombs in the grid.
  2. Updating cells to track whether they contain a bomb.
  3. Rendering bomb images when cells are cleared.
  4. Adding a debug helper to visualize bomb placement during development.

In the next part of our tutorial, we'll build upon this foundation to implement the ability for cleared cells to display the number of bombs in neighboring cells. This feature is essential for providing players with the information they need to deduce the location of bombs and clear the grid safely.

We'll modify our cell class to keep track of neighboring bombs, update this count when bombs are placed, and display the count when a cell is cleared. This will involve working with events, updating our rendering logic, and introducing new graphical elements to represent the numbers.

Next Lesson
Lesson 36 of 129

Adjacent Cells and Bomb Counting

Implement the techniques for detecting nearby bombs and clearing empty cells automatically.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Using static_assert for Bomb Count
Why do we use static_assert() for checking the bomb count, and how does it differ from a regular runtime check?
Using SDL_PushEvent for Event Reporting
Why do we use SDL_PushEvent() for reporting events instead of directly calling a function?
Implementing "First Click Safe"
How can we implement a "first click is always safe" feature in our bomb placement logic?
Or Ask your Own Question
Purchase the course to ask your own questions