< Previous | Contents | Next >
The first thing I do is create a Player class to represent the players who are waiting in the game lobby. Because I don’t know how many players I’ll have in my lobby at one time, it makes sense to use a dynamic data structure. Normally, I’d go to my toolbox of containers from the STL. But I decided to take a different approach in this program and create my own kind of container using dynamically allocated memory that I manage. I didn’t do this because it’s a better programming choice—always see whether you can leverage good work done by other programmers, like the STL—but because it makes for a better game programming example. It’s a great way to really see dynamic memory in action.
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 9 folder; the filename is game_lobby.cpp. Here’s the beginning of the program, which includes the Player class:
//Game Lobby
//Simulates a game lobby where players wait #include <iostream>
Introducing the Game Lobby Program 317
#include <string> using namespace std; class Player
{
public:
Player(const string& name = ""); string GetName() const;
Player* GetNext() const; void SetNext(Player* next);
private:
string m_Name;
Player* m_pNext; //Pointer to next player in list
};
Player::Player(const string& name): m_Name(name),
m_pNext(0)
{}
string Player::GetName() const
{
return m_Name;
}
Player* Player::GetNext() const
{
return m_pNext;
}
void Player::SetNext(Player* next)
{
m_pNext = next;
}
The m_Name data member holds the name of a player. That’s pretty straightfor- ward, but you might be wondering about the other data member, m_pNext. It’s a pointer to a Player object, which means that each Player object can hold a name and point to another Player object. You’ll get the point of all this when I talk
318 Chapter 9 n Advanced Classes and Dynamic Memory: Game Lobby
Figure 9.12
A Player object can hold a name and point to another Player object.
about the Lobby class. Figure 9.12 provides a visual representation of a Player
The class has a get accessor method for m_Name and get and set accessor member functions for m_pNext. Finally, the constructor is pretty simple. It initializes m_Name to a string object based on what’s passed to the constructor. It also sets m_pNext to 0, making it a null pointer.