Simple game design: I'm scared of tons of loops - oop

I started making a simple 2D game than runs on LAN using C++ and SFML library. The game uses a typical update function every frame with its loop to change state of the objects. The game class stores a vector/list of players and monsters and two maps (one for tileset - just graphics, 2nd one holding terrain mechanics - wall, ground etc).
In loop, I call a Think() function (which does move/jump/attack, etc) on every monster (different monsters behave differently but all are inherited from abstract class Monster with theirs appropriate override).
The problem is:
For every monster I need to loop through every other object to check collision
For every monster I need to find near objects (by its coords) so the monster can behave according to what it is seeing
For every non-living object (like flying fireball, any other projectile) I need to update its coords according to passed time (this is easy) but again check collision
For every player I need to loop through all other players/non-lived/monsters to collect information about near objects to send appropriate state of the game to them.
I'm scared how many loops/nested loops this game would have.
I've already seen that some games implement small-instance-based maps world so the loops are always going through small amount of data and since every map is separated its easy to find anything/send update to players.
I could apply this approach to every floor with ease but the floor 0 would be still really huge (array around 5000x5000 tiles to walk on).
I'm thinking now of changing world map array to class that stores references to each object by its coordinates. I just came up with an idea that sorting objects by theirs coords would improve performance of loops or even replace them.
Is this a correct design? Or does exist a better idea?

You should not worry to much about many loops. You can always optimize once you run into problems.
However for the collision you should avoid to check each object against all others, as this will require n^2 checks. Still, this only applies if you really run into performance problems. If this happens, the default approach is to use a grid, which is updated once per frame (or less) to calculate each object's position in the grid. This means each of your cells will know about all objects in it.
Then, if you want to find collisions for a single object, you just check it, with the objects in the same cell and in adjacent cells.
If you have a big amount of objects, you might consider a dynamically adjusting grid, which can be achieved via a quadtree for example. But in most cases a simple statically defined grid should be sufficient.

Related

An object for every sprite? (Games, OOP)

Currently I am trying my best programming a little video game in the style of the old Zelda games. However, I am having some trouble with the whole OOP style of thinking. To be more specific, I don't really know how to "design" the screens.
Let's say I have a class for my sprites and loaded a Wall-sprite to have a border for a certain area, should I make an extra "wall"-class, or is the wall being a "sprite" already enough? I thought it might be senseless to define an extra class since it would not have any different variables than the actual sprite class (as my wall IS only a sprite) so I didn't consider it to be a useful idea.
I am asking this because I have a little problem with the collision detection as well: What I currently do is loading a sprite for an object only once and rendering it multiple times at several locations. But the problem is that this causes the collision only to be detected at the last position the sprite was rendered at.
It gives me more problems when I render 2 cave-entrances somewhere but my game only checks for the 2nd entrance if I "entered" it.
So I thought making an extra "entrance"-class and creating 2 completely different objects of it that are treated separately might help, but should I then also create 30 objects for my wall-sprites?
Hmmm, there is really two questions, well three, but the OOP-thinking is too non-specific for a good question. So let's see if we can answer it by answering your valid ones.
Good OO Design is centered around "Patterns" (Common solutions to a variety of Problems) in the case of your sprite re-use in OO this would be known as a "Fly-weight" Pattern. Three important structural elements in good OO and understanding them is key to "getting it". They are:
Interfaces - They are free (relatively) of operational code, and provide only method and constructor signatures(generally) to allow for clean separation of coding concerns.
Classes - Only the reusable parts(ideally) of an object they are "the Mold or Pattern" that objects are instantiated (or patterned) from.
Objects - Instances (this chair or that chair as opposed, to Chair as an ideal) of the same form of Class (the ideal Chair). Objects (ideally) should keep as instance values only that which differentiates it from other instances of the same ideal.
However, because your original sprite is not an object you are having this collision problem, because it actually is the same instance rendered again and again, the graphics pipeline does not keep all of its previous locations as separate things it actual just stores pixels(usually), once they've been translated.
In this case if each instance is an object, each instance would have its location as a local instance variable(s), while its graphical representation and collision detection method would be common to all instances of the class.
Don't think of it as having 30 whole copies in memory at once, you only have thirty copies of the instance variables. This is true if you use OO or not; in a procedural solution to get proper collision detection you would have to maintain an array of all of the places you rendered that sprite and iterate through each time, further your code would be less cleanly separated and you would have to iterate through the array for every sprite interaction as well as for updating moving sprites. With OO you could handle this with one class method call that recurses it children.
A good class structure for this simple example might be:
An Abstract Sprite Class (abstract because you will never use a non-specific Sprite) containing only code common to all sprites
A Concrete Wall Sprite Class that extends Sprite, only the code for non-moving wall sprites.
A Concrete Trigger Sprite Class (whose graphic might be clear or null) for behaviors that need to be triggered in "open spaces"
A Concrete Agent Sprite Class for moving sprites (might implement a movable interface meaning all derivatives of the class have a move() method.
A Concrete Character class that extends agent for a movable sprite that is driven by user commands.
It may seem confusing at first, but it's actually cleaner, simpler, and more maintainable doing it the OO way.
:)

Non-object-oriented game tutorials

I've been tasked with writing an essay extolling the virtues of object oriented programming and creating an accompanying game to demonstrate them.
My initial idea is to find a tutorial for a simple game written in a programming language which does not follow the OOP paradigm (or written in an OOP language but not in an OOP way) and recreate it in an OOP way using either C# or Java (haven't yet decided). This would then allow me to make concrete comparisons between the two.
The game doesn't have to be anything complex; Tetris, Pong, etc. that sort of thing. The problem I've had so far is finding a suitable tutorial, any suggestions?
Let's say that you found source code for a game not in OOP. There are some OOP virtues that you can point out in your essay:
Organization.
Since a game has many tasks, it is a good idea to assign a responsibility to one class. This means write one class that keeps score, one class that does file access (reading and writing game state, for example), classes to represent your characters, etc. Otherwise, you will have one huge text file with thousands of lines of code. It would be a nightmare to even look at it, let alone find what you need and fix it.
Encapsulation.
This is grouping together properties and functions for better organization. We used to have a different array to store each property - (example) one array for aircraft names, one array for firepower, another array for top speed, etc. That sucks because you need to make sure that the same index across all those arrays actually describes the correct aircraft. It's better to create an Aircraft object and give it those property names. You'll then have one array that holds aircraft - no need to keep track of too many arrays.
Reusability.
As you write more games (and even other apps), you will come across the need to reuse classes. For example, you would use the same Card class in your Solitaire game as any card game you'll write in the future.
Polymorphism/Inheritance.
Say that you want to display each character - both heroes and villains in some sort of a grid. You will want both Hero and Villain to inherit Character. Character will have common properties and even a[n abstract] Display() function. You would then write the custom Display() function for Character and Villain (that access class-specific data for drawing). You then create an array of Character objects, and you may store either a Villain or Hero in each slot. When the game goes through that list to display, each item.Display() call will automatically pick the correct Display() function based on the Character's actual type. Try to do this without OOP and you'll end up with a long if-else (and probably even nested) statement and all drawing routines in one place.
That's just from the type of my head from experience in general programming that you can definitely apply in game programming. There are probably more OOP aspects than mentioned, so you may want to research. Best of everything for your essay!
You can try grabbing a (simple) TI-Basic game from TICalc, Omnimaga, or most other calculator programming websites and try to understand its code.
Try a BASIC game from this site:
http://www.atariarchives.org/basicgames/

OO architecture for rendering in shader based games

I keep hitting this problem when building game engines where my classes want to look like this:
interface Entity {
draw();
}
class World {
draw() {
for (e in entities)
e.draw();
}
}
That's just pseudo-code to show roughly how the drawing happens. Each entity subclass implements its own drawing. The world loops through all the entities in no particular order and tells them to draw themselves one by one.
But with shader based graphics, this tends to be horribly inefficient or even infeasible. Each entity type is probably going to have its own shader program. To minimize program changes, all entities of each particular type need to be drawn together. Simple types of entities, like particles, may also want to aggregate their drawing in other ways, like sharing one big vertex array. And it gets really hairy with blending and such where some entity types need to be rendered at certain times relative to others, or even at multiple times for different passes.
What I normally end up with is some sort of renderer singleton for each entity class that keeps a list of all instances and draws them all at once. That's not so bad since it separates the drawing from the game logic. But the renderer needs to figure out which subset of entities to draw and it needs access to multiple different parts of the graphics pipeline. This is where my object model tends to get messy, with lots of duplicate code, tight coupling, and other bad things.
So my question is: what is a good architecture for this kind of game drawing that is efficient, versatile, and modular?
Use a two stages approach: First loop through all entities, but instead of drawing let them insert references to themself into a (the) drawing batch list. Then sort the list by OpenGL state and shader use; after sorting insert state changer objects at every state transistion.
Finally iterate through the list executing the drawing routine of each object referenced in the list.
This is not an easy question to answer, since there are many ways to deal with the problem. A good idea is to look into some Game/Rendering engines and see how this is handled there. A good starting point would be Ogre, since its well documented and open source.
As far as I know, it separates the vertex data from the material components (shaders) through the built-in material scripts. The renderer itself knows what mesh is to be drawn in what order and with what shader (and its passes).
I know this answer is a bit vague, but I hope I could give you a useful hint.

Game positioning OO design

I'm starting a game project, my first, it'll be like a civilization clone, with a big focus in war. I always worked with C# but for business apps (mostly web apps) so I have a doubt about what would be a good design to build the map positioning system.
I would like to each unit know where it's positioned, and to the map to know all units at each point, a two-way relationship, but I can't see what would be the best way to model this! I'd like some ideas and pseudo-code, if you could!
Thankz.
Make your map a two-dimensional array. At each position, put an array of all objects at that position. In addition, add position attributes to each object.
Yes, this will duplicate the information! So on each move you'll have to change the object and update the map.
However, fast reading and fast finding of the objects is very important for that kind of game. In addition, this solution avoids any search routine (e.g. go through the map and look for a particular object), which is generally a good idea: Replace all search routines over large datasets with indexes. The map should be seen as some kind of index over the object's position attributes.
The map should have all knowledge of all object on it. Furthermore, only each object on the map should know its location. This way, the map can ask all objects where they are and place them in their correct locations. You should never have to store the positioning information twice.
Here's one approach that should avoid duplication
Have a class which holds all objects on the map, and within it collections of different types of object
public class MapObjects
{
private Collection<GamePiece> gamePieces;
}
Each item in the collections will hold its (current) map co-ordinates
public class GamePiece
{
private MapCoordinate mapCoordinate;
// Other items relevant to a GamePiece.. Health, ItemType, etc
}
To find where a particular selected item is on the map should be easy, you have a reference to the GamePiece which holds its coordinates. To find what items are in a particular coordinate you need a helper method, probably within the MapObjects class:
public class MapObjects
{
public Collection<GamePiece> GamePiecesAtLocation(MapCoordinate mapCoordinate)
{
// Iterate through gamePieces collection and build a result
// collection of items at specified coordinates.
}
}
Good luck, sounds like an interesting project with plenty of challenges.
I would make the map hexagonal instead of a grid, so you don't have the odd Civilization phenomenon where you can cover more ground diagonally. Beyond that, I would just have each unit store its own position, and when you need to know which units are in a particular hex just iterate through the whole collection. It's hard to imagine having so many units involved that this approach would be a performance problem.
NSPoint is extremely useful when it comes to things like this. Each gameobject should have it's own location. You could store these gameobjects in arrays, one for each player, one for the whole game, it's up to you.
I will warn you that this is a huge project, not only codewise, but content wise, and requires lots of back and forth work while balancing the game. You should really try a few smaller games before you go after this one. Nothing is stopping you from diving in, but you are going to hit a lot of walls and write some serious spaghetticode if your first game is something this large. I would suggest starting with something like checkers, to get the turn based side of things down.
This is all coming from the guy who is currently writing a roguelike as his first game project. In my defense it is relatively straightforward, but there are a lot of things I was not expecting, and something as simple as calculating the sight / fog of war taking obstructions into account uses complex algorithms. I don't regret picking a roguelike as my first game, but after seeing how complex even the most basic concepts can be to implement, something like a turn based strategy game is simply something I'll leave to the pros for now.
If you're currently having trouble thinking of a way to not only create the units, but represent the map and store the locations, what are you going to do when it comes time to code in research? cities? production? resource gathering? A random map generator? Trajectory calculation? Hit probability? Armor? Mobility? Line of sight? Random events? AI?
I'm not trying to crush your dreams by any means, it's just that the genre you picked is more complex than it seems. Your brain will overload and burst at the seams. (I could continue rhyming on topic, but I will refrain to remind you that you should really try something like checkers first.)
Good design = simple design.
Make the map a list of objects.
Object
int X { get; set; }
int Y { get; set; }
Map
List<Object> objects
Add(Object)
Remove(Object)
GetAt(X, Y)
GetInBox(X,Y,Width,Height)
GetInRadius(X,Y,Radius)
That should be all you need. If the Get(..) queries get too slow, add caching or divide the map into sectors and keep a list of objects for each sector and update it when they move. This helps dramatically if you have many static objects or objects that don't move too quickly from sector to sector. My guess is that in a turn-based game, you won't need to optimize at all.

Object Oriented application problems in game development

I'll be as direct as I can concerning this problem, because there must be something I'm totally missing coming from a structured programming background.
Say I have a Player class. This Player class does things like changing its position in a game world. I call this method warp() which takes a Position class instance as a parameter to modify the internal position of the Player. This makes total sense to me in OO terms because I'm asking the player "to do" something.
The issue comes when I need to do other things in addition to just modifying the players position. For example, say I need to send that warp event to other players in an online game. Should that code also be within Player's warp() method? If not, then I would imagine declaring some kind of secondary method within say the Server class like warpPlayer(player, position). Doing this seems to reduce everything a player does to itself as a series of getters and setters, or am I just wrong here? Is this something that's totally normal? I've read countless times that a class that exposes everything as a series of getters/setters indicates a pretty poor abstraction (being used as a data structure instead of a class).
The same problem comes when you need to persist data, saving it to a file. Since "saving" a player to a file is at a different level of abstraction than the Player class, does it make sense to have a save() method within the player class? If not, declaring it externally like savePlayer(player) means that the savePlayer method would need a way to get every piece of data it needs out of the Player class, which ends up exposing the entire private implementation of the class.
Because OOP is the design methodology most used today (I assume?), there's got to be something I'm missing concerning these issues. I've discussed it with my peers who also do light development, and they too have also had these exact same issues with OOP. Maybe it's just that structured programming background that keeps us from understanding the full benefits of OOP as something more than providing methods to set and get private data so that it's changed and retrieved from one place.
Thanks in advance, and hopefully I don't sound too much like an idiot. For those who really need to know the languages involved with this design, it's Java on the server side and ActionScript 3 on the client side.
I advise you not to fear the fact, that player will be a class of getters and setters. What is object anyway? It's compilation of attributes and behaviours. In fact the more simple your classes are, the more benefits of an OOP you'll get in the development process.
I would breakdown your tasks/features into classes like that:
Player:
has hitpoints attribute
has position attribute
can walkTo(position), firing "walk" events
can healUp(hitpoints)
can takeDamage(hitpoints), firing "isHurt" event
can be checked for still living, like isAlive() method
Fighter extends Player (you should be able to cast Player to Fighter, when it's needed) :
has strength and other fighting params to calculate damage
can attack() firing "attack" event
World keeps track of all players:
listens to "walk" events (and prevents illegal movements)
listents to "isHurt" events (and checks if they are still alive)
Battle handles battles between two fighters:
constructor with two fighters as parameters (you only want to construct battle between players that are really fighting with each other)
listens to "attack" events from both players, calculates damage, and executes takeDamage method of the defending player
PlayerPersister extends AbstractPersister:
saves player's state in database
restores player's state from database
Of course, you game's breakdown will be much more complicated, but i hope this helps you to start thinking of problems in "more OOP" way :)
Don't worry too much about the Player class being a bunch of setters and getters. The Player class is a model class, and model classes tend to be like that. It's important that your model classes are small and clean, because they will be reused all over the program.
I think you should use the warpPlayer(player, position) approach you suggested. It keeps the Player class clean. If you don't want to pass the player into a function, maybe you could have a PlayerController class that contains a Player object and a warp(Position p) method. That way you can add event posting to the controller, and keep it out of the model.
As for saving the player, I'd do it by making Player implement some sort of serialisation interface. The player class is responsible for serializing and unserializing itself, and some other class would be responsible for writing the serialised data to/from a file.
I would probably consider having a Game object that keeps track of the player object. So you can do something like game.WarpPlayerTo(WarpLocations.Forest); If there are multiple players, maybe pass a player object or guid with it. I feel you can still keep it OO, and a game object would solve most of your issues I think.
The problems you are describing don't belong just to game design, but to software architecture in general. The common approach is to have a Dependency Injection (DI) and Inversion of Control (IoC) mechanisms. In short what you are trying to achieve is to be able to access a local Service of sorts from your objects, in order for example to propagate some event (e.g warp), log, etc.
Inversion of control means in short that instead of creating your objects directly, you tell some service to create them for you, that service in turn uses dependency injection to inform the objects about the services that they depend on.
If you are sharing data between different PCs for multiplayer, then a core function of the program is holding and synchronising that piece of state between the PCs. If you keep these values scattered about in many different classes, it will be difficult to synchronise.
In that case, I would advise that you design the data that needs to be synchronised between all the clients, and store that in a single class (e.g. GameState). This object will handle all the synchronisation between different PCs as well as allowing your local code to request changes to the data. It will then "drive" the game objects (Player, EnemyTank, etc) from its own state. [edit: the reason for this is that keeping this state as small as possible and transferring it efficiently between the clients will be a key part of your design. By keeping it all in one place it makes it much easier to do this, and encourages you to only put the absolute essentials in that class so that your comms don't become bloated with unnecessary data]
If you're not doing multiplayer, and you find that changing the player's position needs to update multiple objects (e.g. you want the camera to know that the player has moved so that it can follow him), then a good approach is to make the player responsible for its own position, but raise events/messages that other objects can subscribe/listen to in order to know when the player's position changes. So you move the player, and the camera gets a callback telling it that the player's position has been updated.
Another approach for this would be that the camera simply reads the player's position every frame in order to updaet itself - but this isn't as loosely coupled and flexible as using events.
Sometimes the trick to OOP is understanding what is an object, and what is functionality of an object. I think its often pretty easy for us to conceptually latch onto objects like Player, Monster, Item, etc as the "objects" in the system and then we need to create objects like Environment, Transporter, etc to link those objects together and it can get out-of-control depending on how the concepts work together, and what we need to accomplish.
The really good engineers I have worked with in the past have had a way of seeing systems as collections of objects. Sometimes in one system they would be business objects (like item, invoice, etc) and sometimes they would be objects that encapsulated processing logic (DyeInjectionProcessor, PersistanceManager) which cut across several operations and "objects" in the system. In both cases the metaphors worked for that particular system and made the overall process easier to implement, describe, and maintain.
The real power of OOP is in making things easier to express and manage in large complex systems. These are the OOP principles to target, and not worry as much whether it fits a rigid object hierarchy.
I havent worked in game design, so perhaps this advice will not work as well, in the systems I do work on and develop it has been a very beneficial change to think of OOP in terms of simplification and encapsulation rather than 1 real world object to 1 OOP class.
I'd like to expand on GrayWizardx's last paragraph to say that not all objects need to have the same level of complexity. It may very well fit your design to have objects that are simple collections of get/set properties. On the other hand, it is important to remember that objects can represent tasks or collections of tasks rather than real-world entities.
For example, a player object might not be responsible for moving the player, but instead representing its position and current state. A PlayerMovement object might contain logic for changing a player's position on screen or within the game world.
Before I start simply repeating what's already been said, I'll point towards the SOLID principles of OOP design (Aviad P. already mentioned two of them). They might provide some high-level guidelines for creating a good object model for a game.