Game Development Reference
In-Depth Information
The static options are added to the map using the [] operator. The key being used is postincremented
on each insert call. The AddDynamicOption method uses the vector::push_back method to push the
new option into the vector . Both methods have a call to assert in their first line that will trigger if the
Option pointer being added is a nullptr . This will allow you to track down invalid options while your
program is running.
Now that the options are stored within a Room instance, the class is required to have a method to
print the available options to the player, which is shown in Listing 19-4.
Listing 19-4. Printing the Available Options
void Room::PrintOptions() const
{
for (unsigned int i = 0; i < m_dynamicOptions.size(); ++i)
{
const Option* option = m_dynamicOptions[i];
std::cout << i + 1 << ": " << option->GetOutputText() << std::endl << std::endl;
}
for (StaticOptions::const_iterator iter = m_staticOptions.cbegin();
iter != m_staticOptions.cend();
++iter)
{
const Option* option = iter->second;
const unsigned int chosenOption = iter->first + m_dynamicOptions.size();
std::cout << chosenOption << ": "
<< option->GetOutputText() << std::endl << std::endl;
}
}
The PrintOptions method must print out all of the dynamic options followed by the static options.
Each option is preceded by an index number that the player will then be asked to enter. A for loop
is used to track the option number to be printed for the dynamic options, and you can see this in the
cout statement where we add 1 to i when printing.
Constant iterators are used to loop over the static options. Each static option is keyed starting from
1 so we can add the size of m_dynamicOptions to each key to find the appropriate index for each
static option. The iterators represent key-data pairs with the key stored in the first member of the
pair and the Option pointer stored in second .
The Room class will also be responsible for evaluating the player's input. Listing 19-4 shows the
Room::EvaluateInput method.
Listing 19-5. Room::EvaluateInput
Option* Room::EvaluateInput(unsigned int playerInput)
{
Option* option = nullptr;
const unsigned int numDynamicOptions = m_dynamicOptions.size();
if (playerInput <= numDynamicOptions)
 
Search WWH ::




Custom Search