C++ Beginner game programming: Keeping track of objects, inventory lists, arrays of different amnts of object/characters, etc - c++

I was just playing an old SNES RPG (Secret of Mana, if anyone cares) and was wondering a few general things about game programming.
Sorry for some of the brain-dead questions, I'm really a beginner. :)
These questions are quite general, but use SNES-style RPGs as a "template" to get an idea of what I mean:
How do games keep track of all the objects, triggered events, etc in its "world"? For example, how does it keep track of which treasure chests have already been opened, which doors are locked, which story events have already triggered?
Does it basically create an array of elements each corresponding to a chest/door/event/etc and "mark" each (change its value from 0 to 1) when it has been opened/triggered? If there are multiple approaches, what are they?
How are "variable lists" handled? Ie, if you have a game when you can have a huge inventory of objects (ie: armor, swords) and have X of each object, how is this done?
My guess: have a struct that has a big array with a spot for every possible object (an array of X ints, where X is number of possible objects to own) where each element's value represent how many of that object you have, and then have a giant enum of every object so that an object is matched to a corresponding index, and access it, like: numberOfSwords = inventory[SWORDS] where SWORDS is part of an enum and has some integer number associated with it. How close am I?
How about the case where the number of objects can vary? Ie, if I have a game where I have some amount of enemies on the screen and they can get killed / give birth to new enemies at any point, it would seem to me like I would need an array of "enemy" objects to loop through and process, but that the number of elements would vary at any one time. What is the usual approach to this? Linked lists?
Any help / hint / pointers are really appreciated.

In a very basic manner your answers are not too far off, things could be done the way that you mention them. However space and processing power can come into play so instead of an array of bools to track which treasure chests or how far along the chain of events you are you may want to slim it down to bits being on and off and use the bitwise operators for masking to see where you are in a storyline or whether or not to show the treasure chest you are about to display as opened or close.
For inventories, instead of tracking how many of each item a player has it may be better to have a base item for everything a player can pick up; weapons, armor and even money. Then you could make a linked list of just the items the player has. Use the Enum for the item as you mentioned and then the quantity of that item. This would allow for sorting of things and would also only keep in memory the items the player's character(s) actually have/has. You could extend this data structure to also track if the item is equipped. You could likely keep more generic what the item does sort of information in an items table.
The enemies would likely be a bit more complicated as you need to do a few more things with them. A linked list here though is still likely your best bet. That way removal of an object form the list would be a mite bit easier (can simply remove the link and the like when a player kills them or add in a new enemy wherever needed in the list.)
Honestly there is no one answer and it can depend on quite a few things. The best way is really to simply try it out.. For a simple 'what if I do this for this' it really does not end up taking all that long to give it a whirl and see how far you get. If you start running into issues you can start to consider other options :)
Hope this helps.
Edit: Just wanted to add in a link to www.codesampler.com. Generally more DirectX oriented tutorial sites but as a beginner it can start you thinking or give you a set of places to start. As an added bonus alot of the DirectX SDK examples/samples started to be formatted very much like how this site's tutorials are done. Can help ease you into the whole thing.

This is a pretty advanced question for a beginner.
I'd like to echo In Silico's response that you should learn C++ language basics before you tackle this subject.
To give you a place to start, you should know about container classes (Linked Lists, Vectors, HashTables/Dictionaries, Queues etc) and how they work. Since the Standard Template Library (STL) is pretty standardized, it would be a good place for a beginner to start.
You should also know about inheritance and how to build a hierarchy of classes.
For example, you asked about inventory in a role playing game:
I'd start by defining an InventoryItem class that defines or sets up an interface for all of the code necessary for an item to participate in your inventory system.
Something like:
class InventoryItem
{
private:
std::string description; // A description of the item
bool inInventory; // True if in the players inventory, false if on the ground etc...
int weight; // How much the item weighs
int size; // How much space the item takes in inventory
// etc...
};
In the InventoryItem class you'd also define the member functions and data needed for InventoryItem to be placed in your container class of choice.
The same sort of thing holds true for triggered items, things on the ground etc. They're typically kept in a container class of some sort.
The STL containers will take care of the variable sizes of the containers mentioned in the last part of your question(s).
vector is a good place to start for a general list of items.
HashTables/Dictionaries are good for looking things up with a key.
I hope this is enough to get you started. Good luck.

In addition to James' excellent post, some keywords for you to google for
Data structures
linked list
doubly linked list
queue
for the theory of dynamic memory management.
Also, let me share my standard recommended links for people asking for aid on basic c++:
Full scale tutorial on c++
C++ Language Reference (including STL)
ANSI C Language reference for all those pesky C stuff that C++ keeps using

Your question is not specific for "games programming". You are asking how arbitrary data is organized and stored in bigger programs. There is no definite answer to this, there are lots of different approaches. A common general approach is to make a data model of all the things you want to store. In C++ (or any other languages with object oriented capabilities), one can create an object oriented class model for this purpose. This introduction to C++ contains a complete tutorial on object oriented modeling in C++.
Lots of applications in general use a layered approach - the data model is one layer in your application, separated from other layers like a presentation layer or application ("game") logic.
Your data modeling approach will have to deal with persistency (that means, you want to store all your data on disk and reload it later). This question was asked earlier here on SO. This fact will give you some restrictions, for example, on the use of pointers.
EDIT: if your data model reaches a certain complexity, you might consider using a (lightweight) database, like SQLlite, which has a C/C++ api.
Finally, here is a link that might give you a good start, seems to fit exactly on your question:
http://www.dreamincode.net/forums/topic/26590-data-modeling-for-games-in-c-part-i/

Regarding Question #1, I concur with James and others on using a database that stores the persistent state of your game objects.
Regarding questions #2 and #3, about variable numbers of objects and objects that need frequent updating: I'd suggest maintaining a registry of objects that need updating for each game "cycle" (most games operate on cycles -- loops, if you like, though a modern game uses many loops spawned as separate threads).
For instance, every time you introduce a new enemy or other object that needs to be updated to respond to the current situation or behave in a certain way, you register that object in a list. Each cycle, you iterate through your current list of updateables (probably based on some priority scheduling mechanism), and update them accordingly.
But the particular data structure you use will depend on your program. Linked lists are a valid foundation structure, but in all likelihood you'll want to use a custom compound structure that meets your particular needs. Your approach may combine any number of classic data structures to achieve the best result in performance and effect.
Considering this, I can't emphasize enough the importance of studying advanced data structures before you tackle any sort of serious programming project. There are scores of great books on the topic and you'd do well to study them. Here's a link to a tolerable overview of the classic data structures: http://randu.org/tutorials/c/ads.php

Related

SIMD and object-oriented programming

I have been reading about SIMD for some time and I am going through the slides over at Insomniac Games.
I like the idea and I am certainly open to making my code run more efficiently but I am just not clear how to get started with SIMD in terms of higher level code design.
For instance, let's assume that I am using a language low-level enough to let me know what the memory layout of arrays or classes is, e.g. C++.
If I now have a class such as User with attributes user_id or user_name, as a person modelling the domain that I am in, I know that I will be able to put users into hashmaps, or perhaps into arrays, vectors, or maybe sets, all depending on a particular use-case that a given User is needed in.
That is, I have a reusable User object and what data structure these objects are in is something independent of the User class's own internal structure.
Now, all the SIMD guides say, and I understand why, that instead of arrays-of-structures I should be using structures-of-arrays.
This makes sense as far SIMD instructions go but I cannot find a way to reconcile it with the fact that I am not starting with an array-of-structures that I can easily turn into a structure-of-arrays. Instead, I am starting with User. Sometimes users - in the sense of references to User objects - will be in arrays, sometimes in hashmaps, sometimes in other containers.
But this is not a scenario that online guides mention - all of them just say to turn AOS into SOA and again, I understand why, it is just that it is not a starting position of mine.
I feel that there is a gap that I just cannot make a leap over because I cannot find more complex examples. For instance, maybe I should keep user-related data in, say, two places, one is the User object for general ad-hoc access and another in SOA for SIMD instructions?
Put more generally, how does one model more object-oriented design into SIMD?
Or do people designing entire applications with SIMD in mind do not adhere to such OO concerns at all, instead opting for more data-oriented design?
Or perhaps SIMD is limited to selected modules in one's codebase and such a translation between OOP and SIMD takes place in runtime when needed (i.e. the actual data is kept both in User objects and in SOA and there is manual code to keep them in sync).
I would appreciate it if people with SIMD experience could shed more light on it from a higher level perspective. Thank you.

C++ dynamic way to determine the container to use

Updated again to reflect the question little bit different this time and hope I can get a solution to this:
I can think of a store where there would be 2 workers - 1 worker's job is to receive products and store in appropriate bins and second worker's job is to pick the product based on customer's request and sell that to customer.
The store is expected to store 'N' products ( variable ) and each of these bins needs to hold only similar products.
How to go about solving this problem?
If container can share dissimilar items - I could have gone with defining a single container in shared header file and each worker would have operate on this shared container. The issue here is container should only hold similar items and unable to think of a generic way to define a shared containers for variable 'N' products.
I also have thought about pre-defining the containers for each of the product types - but the issue with this approach is - when a new product is added - I would have to update the header to file to define a new container - which I am trying to avoid - if there is any way to define this container dynamically - and can be shared between 2 workers.
Thanks
You seem to be getting an awful lot of different concepts confused, certainly more than could be sorted out in this form.
One way to solve this would be a base class Product from which all your various "product types" derive, solving your first bullet point neatly, as any standard container could hold various types with a common base class.
But your description is so nebulous that I cannot tell if this would even be a viable solution for you...
My impression is that you are trying to solve advanced producer / worker problems without basic experience with OOP and C++. Start at the beginning, and work patiently through the examples of types, classes, objects and inheritance. If you do that, not only might you develop a better idea of what you are actually trying to achieve. You will also develop the vocabulary to ask questions in a way that could be answered with likewise precision. (Like, whether we are looking at a single-threaded "homework" style program, a multithreaded application, or multiple processes communicating with each other -- I am still not sure about that one.)
As it is, all we can do is guessing, and drivel in the general direction of what might or might not be a solution for what we understand might be your problem...

advice on an oo planing

I am trying to develop an object oriented representation of a finite element model. The finite element model consists of some output files(outputs of a commercial Finite element program) in binary format which keep certain data related to the finite element model (for people who are not in the field, these data correspond to nodes of the model( coordinates of the nodes), elements of the model, element connectivity for the element representations(which elements are associated with which nodes) and element matrix information). These data could also be represented generally as some vectors of ints and double and some other array structure if you call so.
I was thinking of making a general class FeModel and associating the above mentioned files as members of this class and work this way, of course these files would also be objects representing these files. However, the files that keep the information are not a part of the FeModel class that I was thinking on, at least conceptually. Since the idea does not relate to the real world representation, I thought that there should be a better way. Those files are just there to keep the information.
I am now thinking on the option of just reading the necessary information from these files in the FeModel class by creating suitable member functions and build what I want this way so that the interface is more or less a minimal one. However, on the other hand dividing this task into different classes representing the above mentioned files and using those as members in the FeModel class does not look also like a bad option to me. What are the decision criteria in these situations? I am aware of the fact that a problem could be solved in many different ways but are there some sort of guidelines to follow in similar kinds of cases where one hesitates between some options?
Greetz,
U.
My that's a bit of a wall of text. It could use a bit of filtering/rewriting.
As I understand it you have several files representing your 3D elements etc.
I nice OO way of doing it (at least in my mind) would be to have a separate class for each type of file you want to load, pass the filename in the constructor and load in the data, and have accessible members to access the data.
But without further information, structure to what you're asking it's a bit difficult to say.
You probably want to read about SOLID principles of OOP.
In my opinion, it's all about making you design less fragile in the face of changes. In few words, you should strive to the design which is changes-friendly: minor changes domain in model should be reflected by minor and local changes in the design and the implementation.
Don't forget that C++ is not OO-language, but rather language that supports several paradigms (including OO) and other paradigms could fit better to task at hand. If you have access to Bjarne Stroustrup excellent "The C++ Programming Language (Special Edition)", read through Part IV ("Design using C++") to get the idea of roles of classes and other C++ concepts.
An OO solution focuses on behavior, not data. You haven't told us what behaviors you need so we can't help with an OO solution.
That said, find your invariants and create a class for each related set of invariants and you should end up with a decent modular solution.
I suggest you read the book Object-Oriented Design Heuristics by Arthur Riel.

OOP Game Design Theory

I've tried to develop a 2D game with C++ in the past using mere objects, however, in the design process I don't know how and what parts of the engine I should split into smaller objects, what exactly they should do and how to make them interact with each other properly. I'm looking for books, tutorials, papers, anything that explains the game engine design in detail. Thanks.
Mandatory reading: http://scientificninja.com/advice/write-games-not-engines
Why do you think you need a game engine? Write the code you need in order to implement your game. Modify it along the way as requirements change. And when you have a complete game, take a step back and look at what the result looks like.
You can't, and shouldn't, lay out a complete class diagram at the start. Sketch out a rough idea of what general components you want, and what their responsibilities should be, and then try to code it. Start out with the classes you're sure of. Sooner or later, some of them will get big and unwieldy, so you split it into multiple smaller ones. Sometimes, you may find that several classes are basically doing the same thing, so you merge them back together. Hopefully, sooner or later, you'll end up with a design that works, which is more than you'd get if you tried to design a game engine up front.
If you haven't made a game before, how can you make an engine? There's tons of free engines out there or you will be spending 20 years trying to get something done because you will be rewriting over and over again.
There are two important types of objects in a game. There are objects that contain processes, and there are objects that interact with the environment and the user.
For those objects that run a process like changing the opacity of objects you'll want them to be independant of any class level variables. They should simply take in value(s) and return value(s). If you have a process to calculate gravity, the process should take in the object that it gravity is being calculated on, and return the the amount of gravity that the object is experiencing, and the direction of gravity if the game takes place in space.
The second more important types of objects are those that interact with the user and the environment. These objects should all inheret of the same base class. The base class will require an image, and the x and y position, and can have variables that perform specific processes like changing the speed or direction of the variable.
With this base class in place you can then perform proccesses like the gravity proccess mentioned earlier using every objects "built-in" variables like speed, direction, and x and y position.
You will also want to set up your objects to run peices of code under certain conditions. It may be a good idea to have your base class provide functions that get run when one of these conditions are met. Some useful conditional functions are a conditional function to go of when an object is first created and when it is destroyed. A conditional function to go of after a timer is set. A conditional functional to go of continually where you can place code to draw images on the screen. A conditional function to go off When a keyboard or mouse button is pushed. A conditional function to go off a set amount of times per second to calculate things like gravity on an object.
This framework has worked very well for me when creating games. It works for any type of game, and works horribly for other types of programs. Sorry if my writin is unclear, I'm typing on my iPod and It would be hard for me to go back and edit things on here.
Eberly's 3D Game Engine Architecture and 3D Game Engine Design are rather heavy on the theory, but cover all of the bases quite well.
http://fivedots.coe.psu.ac.th/~ad/jg/
This guy lays out a good oop style and through the book helps you build an engine frame. It's spot on good stuff.
If you want to code a simple 2d game, a good way to get an idea of what you#re actually trying to do is to:
write a simple game loop, that simply displays a frame buffer in the resolution you want
render a simple sprite with a a given direction and velocity bouncing off the screen edges
ensuring that your logic and display code are decoupled
If this sounds like a a lot of work, or if it contains ideas/ terms you're not 100% sure what they mean: Take a look at one or two of the existing game engines.
If you just want to get an idea of how it's done, coding something is a great way to learn.
If you're more interested in developing a game, I strongly recommend something like Unity as a base, so you can actually work on the game. And since it is an engine, you'll learn over time how many different parts there are, and how they interconnect.

Efficient Methods for a Life Simulation

Having read up on quite a few articles on Artificial Life (A subject I find very interesting) along with several questions right here on SO, I've begun to toy with the idea of designing a (Very, very, very) simple simulator. No graphics required, even. If I've overlooked a question, please feel free to point it out to me.
Like I said, this will hardly be a Sims level simulation. I believe it will barely reach "acceptable freeware" level, it is simply a learning exercise and something to keep my skills up during a break. The basic premise is that a generic person is created. No name, height or anything like that (Like I said, simple), the only real thing it will receive is a list of "associations" and generic "use", "pick up" and "look" abilities.
My first question is in regards to the associations. What does SO recommend as an efficient way to handle such things? I was thinking a multimap, with the relatively easy set up of the key being what it wants (Food, eat, rest, et cetera) and the other bit (Sorry, my mind has lapsed) being what it associates with that need.
For example, say we have a fridge. The fridge contains food (Just a generic base object). Initially the person doesn't associate fridge with food, but it does associate food with hunger. So when its hunger grows it begins to arbitrarily look for food. If no food is within reach it "uses" objects to find food. Since it has no known associations with food it uses things willy-nilly (Probably looking for the nearest object and expanding out). Once it uses/opens the fridge it sees food, making the connection (Read: inserting the pair "food, fridge") that the fridge contains food.
Now, I realise this will be far more complex than it appears, and I'm prepared to hammer it out. The question is, would a multimap be suitable for a (Possibly) exponentially expanding list of associations? If not, what would be?
The second question I have is probably far easier. Simply put, would a generic object/item interface be suitable for most any item? In other words, would a generic "use" interface work for what I intend? I don't think I'm explaining this well.
Anyway, any comments are appreciated.
If you were doing this as a hard-core development project, I'd suggest using the equivalent of Java reflection (substitute the language of your choice there). If you want to do a toy project as a starter effort, I'd suggest at least rolling your own simple version of reflection, per the following rationale.
Each artifact in your environment offers certain capabilities. A simple model of that fact is to ask what "verbs" are applicable to each object your virtual character encounters (including possible dependence on the current state of that object). For instance, your character can "open" a refrigerator, a box of cereal, or a book, provided that each of them is in a "closed" state. Once a book is opened, your character can read it or close it. Once a refrigerator is opened, your character can "look-in" it to get a list of visible contents, can remove an object from it, put an object in it, etc.
The point is that a typical situation might involve your character looking around to see what is visible, querying an object to determine its current state or what can be done with it (i.e. "what-state" and "what-can-i-do" are general verbs applicable to all objects), and then use knowledge about its current state, the state of the object, and the verb list for that object to try doing various things.
By implementing a set of positive and negative feedback, over time your character can "learn" under what circumstances it should or should not engage in different behaviors. (You could obviously make this simulation interactive by having it ask the user to participate in providing feedback.)
The above is just a sketch, but perhaps it can give you some interesting ideas to play with. Have fun! ;-)
To the first question:
My understanding is that you have one-to-possibly-many relationship. So yes, a multimap seems appropriate to me.
To the second question:
Yes, I believe a generic interface for objects is appropriate. Perhaps use something similar to REST to manipulate object state.
I heard a podcast a while back with the developer of The Noble Ape Simulation, which may be interesting to you - conceptwise and perhaps codewise, as you can access the source code, as well as download binaries.
The podcast was FLOSS Weekly 31 with Randal Schwartz and Leo Laporte.
Life with lisp(sbcl) :)