Game Development Reference
In-Depth Information
can only create objects that derive from its return type. Many game engines manage this by having
all creatable objects derive from a common base class. For our purposes, in the context of learning,
it's better to cover a couple of examples. Listing 23-2 shows a factory for the Enemy derived classes.
Listing 23-2. The Enemy Factory
Enemy* CreateEnemy(EnemyType enemyType)
{
Enemy* pEnemy = nullptr;
switch (enemyType)
{
case EnemyType::Dragon:
pEnemy = new Enemy(EnemyType::Dragon);
break;
case EnemyType::Orc:
pEnemy = new Enemy(EnemyType::Orc);
break;
default:
assert(false); // Unknown enemy type
break;
}
return pEnemy;
}
If you were to create new inherited classes for these enemy types at some point in the future, you
would only be required to update the factory function to add these new classes to your game. This is
a handy feature of using factory methods to take advantage of polymorphic base classes.
So far all of the Option and Enemy objects in Text Adventure have been member variables within the
Game class. This doesn't work too well with factory objects because the factory will create the objects
on the heap, not using stack memory; therefore the Game class must be updated to store pointers to
the Option and Enemy instances. You can see how this is done in Listing 23-3.
Listing 23-3. Updating Game to Store Pointers to Option and Enemy Instances
class Game
: public EventHandler
{
private:
static const unsigned int m_numberOfRooms = 4;
using Rooms = std::array<Room::Pointer, m_numberOfRooms>;
Rooms m_rooms;
Player m_player;
Option::Pointer m_attackDragonOption;
Option::Pointer m_attackOrcOption;
Option::Pointer m_moveNorthOption;
Option::Pointer m_moveEastOption;
Option::Pointer m_moveSouthOption;
Option::Pointer m_moveWestOption;
Option::Pointer m_openSwordChest;
Option::Pointer m_quitOption;
 
Search WWH ::




Custom Search