Game Development Reference
In-Depth Information
The bolded lines show that the Game class inherits from QuitObserver , now has a destructor,
and overloads the OnQuit method. Listing 23-13 shows how the constructor and destructor are
responsible for adding and removing the class as a listener to QuitOption .
Listing 23-13.NThe Game Class Constructor and Destructor
Game::Game()
: m_attackDragonOption{ CreateOption(PlayerOptions::AttackEnemy) }
, m_attackOrcOption{ CreateOption(PlayerOptions::AttackEnemy) }
, m_moveNorthOption{ CreateOption(PlayerOptions::GoNorth) }
, m_moveEastOption{ CreateOption(PlayerOptions::GoEast) }
, m_moveSouthOption{ CreateOption(PlayerOptions::GoSouth) }
, m_moveWestOption{ CreateOption(PlayerOptions::GoWest) }
, m_openSwordChest{ CreateOption(PlayerOptions::OpenChest) }
, m_quitOption{ CreateOption(PlayerOptions::Quit) }
, m_swordChest{ &m_sword }
{
static_cast<OpenChestOption*>(m_openSwordChest.get())->SetChest(&m_swordChest);
m_enemies.emplace_back(CreateEnemy(EnemyType::Dragon));
static_cast<AttackEnemyOption*>(m_attackDragonOption.get())->SetEnemy(m_enemies[0]);
m_enemies.emplace_back(CreateEnemy(EnemyType::Orc));
static_cast<AttackEnemyOption*>(m_attackOrcOption.get())->SetEnemy(m_enemies[1]);
static_cast<QuitOption*>(m_quitOption.get())->AddObserver(this);
}
Game::~Game()
{
static_cast<QuitOption*>(m_quitOption.get())->RemoveObserver(this);
}
The bolded lines again show the relevant updates to the code. The last update in Listing 23-14
implements the OnQuit method.
Listing 23-14. The Game::OnQuit Method
void Game::OnQuit()
{
m_playerQuit = true;
}
This is all there is to implementing the observer pattern. This has achieved another decoupling
between the QuitOption class and any other classes in the game that need to know about quit
events. The observer class is especially useful when creating game framework code for systems
such as online features. You can imagine a situation where you implement a class to download
leaderboards from a web server. This class could be used in multiple game projects and each
individual game could simply implement its own class to observe the downloader and act
appropriately when the leaderboard data has been received.
 
Search WWH ::




Custom Search