< Previous | Contents | Next >

The Player Class

The first thing I do is create a Player class to represent the players who are waiting in the game lobby. Because I dont know how many players Ill have in my lobby at one time, it makes sense to use a dynamic data structure. Normally, Id 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 didnt do this because its a better programming choicealways see whether you can leverage good work done by other programmers, like the STLbut because it makes for a better game programming example. Its 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. Heres 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. Thats pretty straightfor- ward, but you might be wondering about the other data member, m_pNext. Its a pointer to a Player object, which means that each Player object can hold a name and point to another Player object. Youll get the point of all this when I talk

image

318 Chapter 9 n Advanced Classes and Dynamic Memory: Game Lobby


image

image

image

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

object.

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 whats passed to the constructor. It also sets m_pNext to 0, making it a null pointer.