Game Development Reference
Finally, if we are trying to add an item into a slot already populated by a different item, we
will return false to indicate adding is not possible.
The next operation we want to perform is removal of an item from the grid. Due to the fact
that we created a static array for the grid and that we move items into it, we will need a
way to represent an empty item. A way for us to test that a slot in the grid has nothing in it.
What we will do is create a default initialized slot, with a default constructed item and we
will use it as our empty slot.
static slot_item Empty;
Unlike addition however, we will not move this empty slot item, instead we will copy its
value as to replace the item that was there.
void Remove(int m, int n, int count)
slot_item& slot = m_items[m][n];
if ( slot.Count() != 0 )
slot.Count() = math::Max(0, slot.Count() - count);
if ( slot.Count() == 0 )
m_items[m][n] = slot_item::Empty;
At this point we have a complete, reusable, general purpose grid system that allows us to
add, remove and swap items, and does not rely on dynamic allocations.
For our purposes, we want to implement a grid that draws an image at each of the grid's
slots and some text to indicate the number of items within each slot.
We start by creating a derived grid class that will implement the drawing functionality.
template <int m, int n, typename T>
class grid_game : public grid<m,n,T>
. . .
slot and then calling its own Draw function. This implies that we will create a specialized
grid_item class that is able to draw itself.