TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: RICHARD VETO
from: CHRISTOPHER BUTLER
date: 1998-04-02 23:36:00
subject: Programming

Hi Richard!
Hey, Richard wasn't it you that was talking about Programming on 28 Mar 98? 
Yeah... you were talking to All, weren't you?
 RV> While writing this online game, I've encountered a small problem and
 RV> am not sure how to go about it.  In most games, there is a player
 RV> inventory.  This inventory is an array within the player structure.
 RV> The problem is, the inventory can have armor, weapons, wands, rings;
 RV> each of which are different structures.  How do I link all those
 RV> structures to reflect in the player inventory?  Do I use a union?
One way you could go about this is to have a base "Item" class, with all the 
functions/variables you'll want to know for each item, and an enum or 
something that specifies what kind this item is. eg:
enum ItemTypes { Item, Armor, Weapon, Wand, Ring };
class Item
{
 public:
  Item(char *a_name, ItemTypes a_type=Item);
...
 private:
  char *name;
  ItemTypes type;
};
Item::Item(char *a_name, ItemTypes a_type):
  type(a_type)
{
  name = new char[strlen(a_name) + 1];    /* I don't know if this is portable
                                             or not, but it works on GCC, you
                                             may need to replace this with a
                                             set maximum length. */
  strcpy(name, a_name);
}
And then, for every type of item, derive a class from this base class:
class Armor: public Item
{
 public:
  Armor(char *a_name, int a_protection);
...
 private:
  int protection;
};
Armor::Armor(char *a_name, int a_protection):
  Item(a_name, Armor), protection(a_protection)
{
}
This may not be the best or cleanest code in the world, but hopefully you 
will get the idea :-)
-----------------------------------------------------------------------------
Chris Butler                               [email: chrisb@sandy.force9.co.uk]
-----------------------------------------------------------------------------
 "Usenet is like the Klingon High Council."
 -- Peter da Silva
--- FMailX32 1.22
---------------
* Origin: ... The Death Butler BBS, +44-1582-620141 ... (2:257/135)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.