OOP Game Design Theory - c++

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.

Related

Should I move to Object Oriented Programming(black boxes) and how?

Right now I have a DirectX engine with a couple of classes - Application,Graphics,Sound and each of them is around 1k lines and they each reference eachother.I initially tried to limit use of classes and stuff like passing the D3D Device and instead made it global for all classes to use,but I see in everyone else's engine that everything is split up into many classes and they have stuff like Engine->GetRenderer->Render(MyD3DContext); isn't that terriby inefficient?Why not just make MyD3DContext global and use it directly in the Render function.And one last thing I don't get is = how are you supposed to make classes that work independent of eachother?Sounds weird.
Firstly why do you think that's terribly inefficient? Besides being much easier to code and maintain, that is also blazingly fast. OOP isn't a bottleneck, its a boon for large projects with multiple developers and multiple concerns(such as real world games).
Let me give you an example, since you mentioned "games":
The game is a Simulation
The simulation contains entities(Objects)
Objects can do things, and have attributes. Hence Objects are like an encapsulation of attributes and actions. This is what makes the "Object" in "Object Oriented Programming". You can think they're(objects are) created in a fictional factory in your simulator. The blueprint of object is the "class", and is called encapsulation.
Each of these objects are bound to your world, probably through some sort of highly mathematical Half-Life-2(source) level Physics engine. You wouldn't want to code the "physics" for each class. Instead you would inherit from a class(or interface) "IPhysics". And then whenever you change the gravity from 10.0 to 15.0, this value is propagated throughout the "world" scenario. This is inheritance.
Each object in your game, say Half-Life-2, Gordon Freeman can at the same time, act as a "Player" and "Can-Be-Scripted" if you know what I mean. This is polymorphism. One object acting in different types.
So you see, this is pretty easy(and terribly EFFICIENT) to model and present the fictional game in OOP.
It isn't terribly inefficient. And you definitely need an introduction to OOP of some sort. Maybe even something online
Yes.
As the project becomes larger having one global anything will cause a vast list of problems. It's also not particularly inefficient to traverse a few pointers. Worry about efficiency in the right areas, areas that you have proven by running tests are inefficient, and try and maintain code clarity and separation at all times.
If you're worried about inefficiency why not knock together a test app that has exactly that kind of structure and time how long it takes to do all that dereferencing. You'll find it insignificant to, say, building up the list of polys in sight.
The only way you'll see the benefit of having well encapsulated non-global objects will be as your project grows and you change things around.
there are a couple big tenants of OO design: in particular Code-Reuse/modularity and scope/isolation. Globals are generally frowned upon these days because they just don't scale well to large development efforts and always end up causing problems, so OO attempts to limit the scope of any given call to the minimum required to perform the function.
as for Modularity/reuse, the larger a sub-module grows, generally the more specific it becomes, and as such the less likely that it will fit all the purposes it could if it were broken apart into more modular chunks. as a result you spend less time rewriting the same code for a slightly tweaked purpose, which also reduces the adjacent purposes that you might break while implementing code for your new one. that makes it more efficient to implement, though there may or may not be some slight cost at runtime. likely not though. remember, it doesn't take a lick more binary to run Render() whether its defined in a root module or composed several layers deep in a composed object. its still just a function pointer.
these are just general concepts, so take what you like.
hope that helps.

Efficiently calling a Python function

I'm embedding Python into my game. The scripts will be used to define the character AI, how entities react to game events, etc — this means there's going to be a script for every type of entity in the game.
Each script will have a function like createEntity() or something which will return the constructed entity. What would be an efficient(ish) way of calling these functions (remember, there's one in every entity's script).
My initial thought was to do something like what you see below, however, I'm unsure as to how efficient this is. For example, what happens with the imported hero module after I run that string? Does it remain loaded in the main module? If that's the case, that's problematic since I'm going to be importing lots of scripts for all the entities I might need to add to the game world.
boost::python::handle<> result(
PyRun_String("import hero\n" "createEntity()\n",
Py_file_input, main_namespace.ptr(), main_namespace.ptr())
);
// Then extract the entity from `result`...
What suggestions do you have?
Your question does not specify whether space efficiency (i.e. memory), time efficiency, or labor efficiency is most important to you. Merely because you are considering a hybrid C++ / Python application, I assume that labor efficiency is a significant factor. Because you are developing a game, I assume that there will be some part of it that has a need for extremely tight execution speed.
Perhaps this approach will strike a balance. Make all the user interaction (input and output, including any networking) C++ based for minimum latency. You might place this in its own thread or process. Given a high level event from the model, like a character moving, this code very quickly updates the screen and the network. Given a user event, or an event from the network, it sends a message to the model.
The game model, which can be asynchronous to the view/control, would then be in Python for your convenience and so you can take advantage of functional programming etc. You could use shared memory or a similar IPC mechanism between the two and start them separately if actually embedding an interpreter is inconvenient.
While certain AI applications are CPU-intensive, and therefore it may be tempting to go back to C or C++ for them, I would advise doing that as a final step, in response to clear responsiveness issues in interpreted code, if you do it at all. You may even want to follow this line of thought with the graphics also, since nowadays most graphics processing is delegated to the video hardware, if you have a way to make the library calls you need from Python code.
Though I am not a game developer, I have been around and I have seen few situations in which the (nowadays) microseconds difference between single equivalent C and Python operations is perceptible to users. Perceptible performance problems are nearly always due to other factors, such as disk I/O, network latency or inefficient algorithm implementations.
Ousterhout on the role of scripting languages is an oldie but goodie. In the case of a game where you have said that the gameplay is to be scripted, the model (Python) is already organizing the flow as you have described it. If PyGame or similar library isn't up to the task of presenting the view, find or build a Python module that can.
Put another way, when I suggested you've got the integration backwards, it sounds like you are asking the view to call the model repeatedly to update itself. I cannot think of a way that putting the metaphoric cart before the horse will yield either efficiency or ease of development.

State management in adventure games

I have been thinking about making a point'n'click adventure game. The problem I have been running into is representing the game logic and state in a generic(and not butt ugly) way.
Game State:
You took an item from a room, it's no longer supposed to be there(could be done easily)
You talked to a character who went to do something that affects another room/screen, how to save in what state the room and character are
Game Logic:
You talk to a character, he does some animation and changes some stuff in the world state, how would you set this without hardcoding it into the game?
I guess the questions are related because figuring out how to represent the state will go a long way to figuring out how to define "actions."
One of the prettier options would be to use a scripting language, like Lua. You hardcode into the game only the properties that a given room or item or character might have, how they might relate to each other (e. g. item is in the room), and all the real stuff will be done by a script. This has an advantage of easier debugging, if you do it right (you won't need to recompile your game, actually, done right, you won't even need to restart it), but disadvantage of adding some complexity.
Also you may want to consider using some of the already available game engines for point and click adventures, like AGS or Wintermute. If you want to make a game, you will want to avoid programming as much as possible to jump straight to game design. I know that may be hard to accept for a programmer :)
Unless your game engine includes a scripting language of some sort, you'll have to hard-code something. Eliminating hard-coding tends to push the responsibility of defining actions to runtime, and the runtime environment will need some way to define those actions. If you don't have one already, look into an embeddable language like Lua or Python, or possibly even Javascript.

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

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

How would you go about implementing the game reversi? (othello)

I have been thinking about starting a side project at home to exercise my brain a bit. Reversi looks like a simply game, where mobility has a profound effect on game play.
It is at least a step up from tic tac toe. This would be a single player against an AI of some sort.
I am thinking to try this in C++ on a PC.
What issues am I likely to run into?
What graphics library would you recommend?
What questions am I not smart enough to ask myself?
Issues...
Well, just be sure when writing the strategy part of the game, not to simply do the move that gives you the most pieces. You must also give weight to board position. For example, given the opportunity to place a piece in a board corner should take priority over any other move (besides winning the game) as that piece can never be turned back over. And, placing a piece adjacent to a corner spot is just about the worst move you can ever make (if the corner space is open).
Hope this helps!
In overall, issues you will end up running onto will depend on you and your approaches. Friend tends to say that complex is simple from different perspective.
Choice of graphics library depends about what kind of game you are going to write? OpenGL is common choice in this kind of projects, but you could also use some GUI-library or directly just use windows' or xorg's own libraries. If you are going to do fancy, just use OpenGL.
Questions you ought ask:
Is C++ sensible choice for this project? Consider C and/or python as well. My answer to this would be that if you just want to write reversi, go python. But if you want to learn a low level language, do C first. C++ is an extension to C, therefore there's more to learn in there than there's in C. And to my judge, the more you have to learn onto C++ is not worth the effort.
How do you use the graphics library? If you are going to do fancy effects, go to the scene graph. Instead you can just render the reversi grid with buttons on it.
How ought you implement the UI, should you use the common UI concepts? Usual UI concepts (windowing, frames, buttons, menubars, dialogs) aren't so good as people think they are, there's lot of work in implementing them properly. Apply the scene graph for interpreting input and try different clever ways onto controlling the game. Avoid intro menus(they are dumb and useless work), use command line arguments for most configuration.
I yet give you some ideas to get you started:
Othello board is 8x8, 64 cells in overall. You can assign a byte per each cell, that makes it 64 bytes per each board state. It's 8 long ints, not very much at all! You can store the whole progress of the game and the player can't even notice it. Therefore it's advised to implement the othello board as an immutable structure which you copy always when you change a state. It will also help you later with your AI and implementing an 'undo' -feature.
Because one byte can store more information than just three states (EMPTY, BLACK, WHITE), I advice you will also provide two additional states (BLACK_ALLOWED, WHITE_ALLOWED, BOTH_ALLOWED). You can calculate these values while you copy the new state.
Algorithm for checking out where you can put a block, could go the board through one by one, then trace from empty cells to every direction for regex-patterns: B+W => W^, W+B => B^ This way you can encapsulate the game rules inside a simple interface that takes care of it all.
As the guys were suggesting my idea of telling you for thinking first for algorithms and the game logic. next answer for me was the graphics library, it depends on your target platform, programming language, framework etc. But as I suggest is using C# with Cairo 2D graphics library which you can achieve this using Mono framework (which then you can target all three major operating systems for your game to work) -> www.mono-project.org. Meanwhile I found this I think that and this kind of resource will help you: http://home.datacomm.ch/t_wolf/tw/misc/reversi/html/index.html. But if you finish this, you can try implementing Sudoku.
As mentioned by others, I would begin by getting a deep understanding of the gameplay and strategies, and the algorithms involved. This link may be useful to you, it describes basic Othello strategy and algorithms:
http://www.site-constructor.com/othello/Present/Basic_Strategy.html
You will want to look into minimax with alpha-beta pruning if you write an AI to play against. Your favorite search engine will have much to say on the topic.
After you've taken a whack at the game logic yourself, go read chapter 18 of Peter Norvig's outstanding book Paradigms of AI Programming. (Source code here.) It has a rather short and extremely readable program that can kick just about any human's butt; you ought to learn a lot by comparing your solution to it.
There are tons of libraries out there but as far as I can think your game is going to need event and graphics libraries....and a sound library for more fun!
Allegro 5 is a best choice...Its an All in one library.
http://liballeg.org/
though It is written in C language you can create Object Oriented programs.
and A tutorial for this...
http://fixbyproximity.com/2d-game-development-course/
or you can use low level APIs like.. OpenGL for graphics.
OpenAL for sound.
glfw for events.
but OpenGL is a big deal because you have to create your own sprite sheet handler and all that 2d stuff.
Go with allegro...Complete your game and then go for OpenGL!
Reversi should be a very simple game to implement. It is perfect to learn some basic algorithms of games theory (specifically min-max) during the implementation of the AI.
One thing to note on the AI is that it is perfectly possible to make a perfect AI for Reversi (one that always wins no matter the moves of its opponent). So on the strategy side, if your AI loses, you still have work to do :)
I wrote a reversi game many years ago, when I was still at school. Its strategy was very simple, it just went for the maximum number of pieces, but weighted so it preferred the edges and particularly the corners and didn't like squares that risked giving away the corners.
This worked fairly well against people who hadn't yet worked out what it was doing, but once you had it was very easy to use its strategy against it. I'm not proud to say, however, that it beat me the first few times even though I'd written it!
A proper AI with a few moves of lookahead is far more complicated. Should be an interesting problem, but at the time I was more interested in the user interface.