Appropriate data structure for a list of items with general and specific properties in C

自作多情 提交于 2019-12-11 11:01:52

问题


I'm making a multiplayer text game, and every player in the game is assigned an inventory. The inventory is a simple linear linked list which contains the ID of the item and the state of the item in the game. For example, player1 could have a red car with 50% of fuel and it would be represented in the list as (5, 50) where 5 is the ID of a red car in the game and 50 is the amount of fuel of that specific car.

But this means the information of every item in the game should be saved in some data structure.

I thought of using something like

enum itemtype {car, gun, bullet, etc};
struct itemlist {
    itemtype type;
    char* name;
    int volume, weight;
} itemlist[];

And all the information of red cars (car, "Red car", 15m^3, 2000kg) would be stored in itemlist[5], because the ID for red cars is 5.

But there are different types of items in this game, so each item has its own properties. Cars would have (max_speed, acceleration) and bullets would have (mass, velocity, kinetic_energy). And some parts of the code need to access these specific properties in order to do stuff in the game.

So this means

  • getting the ID from the inventory
  • checking the array for specific properties of such item
  • do stuff with the retrieved properties

but I don't know how to do that because there are different categories of items with different specific properties each one.

Adding an array to the struct wouldn't help because properties can be anything, like strings or numbers. Adding a nested structure might be fine but there could be something that tries to use item[5].properties.max_speed and I'm not sure if this is safe, because someone could try to get the property max_speed from an item that doesn't have it.

So, what's the best way of storing general and specific properties for such list of items?


回答1:


Err, maybe I'm missing something here but isn't this exactly what the union was built to do?

Make each item in your list a union data type along the lines of:

struct itemelem {
    itemtype type;
    union {
        cartype c;
        bullettype b;
    };
};

In that case, you would use type to identify what the element type was, so you could then access the correct union specifier, sort of a poor man's polymorphism :-)



来源:https://stackoverflow.com/questions/10273904/appropriate-data-structure-for-a-list-of-items-with-general-and-specific-propert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!