Programming a simple Game, - c++

Hey im programming a simple game using directX and C++ and i have hit a slight problem which im sure some genius can fix.
I currently have an array of 8 Aliens and i currently use this code to move them left to right and down a line.
bool turnaround=false;
if ((Aliens[0].pos.x<-5 & Aliens[0].vel.x<0)|(Aliens[3].pos.x>5&Aliens[3].vel.x>0))
{
turnaround=true;
if(Aliens[0].vel.x<0)
Aliens[0].animCtrl->SetTrackSpeed(0,1);
else
Aliens[0].animCtrl->SetTrackSpeed(0,-1);
}
However this currently stops them short if ones to the left or right have been destroyed (they are destroyed by a variable Aliens[i].dead = true
I was wondering if anyone can come up with the if statement or nested if's required to say if ones furthest left or right are destroyed go further across :/
Thanks :)

I presume from your question that you are constructing some sort of space invaders type game. Here would be one way to approach this that might be better than what you currently have (in a pseudo-code form):
For each alien:
If alien is currently on an odd row:
Set direction to left
If alien x position is near 0:
Set direction to down
Else
Set direction to right
If alien x position is near screen width:
Set direction to down
This should cause the aliens to move down towards the bottom of the screen row by row. (Of course there are many different formations aliens could take in this type of game, this is just one). You aren't clear about what sort of behaviour you want them to exhibit when they are killed ("go further across" is ambiguious, is this the player or some of the aliens, or what?), however, if you elaborate on that I may be able to lend further advice here.
I would also suggest you reconsider your design for a minute. You have what appears to be a fixed size array that holds the 8 aliens. While this may allow you to construct a particular level, it is likely to prove very restrictive. What if in another level you want 12 aliens? I suggest you turn your Aliens array into an std::vector, so you can add them to a level as you like at will. Even better, if you have different types of enemies that all share the same properties, you could create a superclass CEnemy that these enemies all inherit from. This is likely to make your design more robust and expandable.
Also, as has been stated by others already, use logical operators when you want to run an AND or OR operation, not bitwise. (That is, use || instead of |, etc) There is an important difference between the two.

By the way, you should get in the habit of using the logical operators (&& and ||) for things like this instead of bitwise operators. They should be more efficient because of short circuiting and prevent bugs later down the road.
I'm not sure if there's enough information to answer your real question. Why are you manually accessing the 0th and 3rd Alien? How do you want the aliens to behave, ideally?
EDIT 1:
Something like this should work:
Alien * furthestLeftAlien, * furthestRightAlien;
/** here loop through your Aliens array to find
the furthest left and furthest right aliens **/
if(furthestLeftAlien->dead || furthestRightAlien->dead)
{
goFurtherAcross():
}

You should really be using a different data structure altogether. C++ std library has several different container classes that can help you.
For instance, a std::deque allows you to easily remove items from either end.
You could remove dead aliens like:
while (!Aliens.empty() && Aliens.front().is_dead()) Aliens.pop_front();
while (!Aliens.empty() && Aliens.back().is_dead()) Aliens.pop_back();
And then your code above would go:
bool turnaround=false;
if ((Aliens.front().pos.x<-5 && Aliens.front().vel.x<0) || (Aliens.back().pos.x>5 && Aliens.back().vel.x>0))
{
turnaround=true;
if(Aliens.front().vel.x<0)
Aliens.front().animCtrl->SetTrackSpeed(0,1);
else
Aliens.front().animCtrl->SetTrackSpeed(0,-1);
}
Though to be honest, I'm not sure how the code here is meant to turn around the whole row of aliens. Instead of using a turnaround variable, why not just turn the aliens around inside the if statement?

Related

Faster to create map of pointers or if statement

I'm creating a game engine using C++ and SFML. I have a class called character that will be the base for entities within the game. The physics class is also going to handle character movement.
My question is, is it faster to create a vector of pointers to the characters that move in a frame. Then, whenever a function moves a character it places it inside that vector. After the physics class is done handling the vector it gets cleared?
Or is it faster to have a bool variable that gets set to true whenever a function moves a character and then have an if statement inside my physics class that tests every character for movement?
EDIT:
Ok i've gone with a different approach where a function inside the Physics class is responsible for dealing with character movement. Immediately upon movement, it tests for collision detection. If collision happens it stops the movement in that direction.
Thanks for your help guys
Compared to all the other stuff that is going on in your program (physics, graphics), this will not make a difference. Use the method that makes programming easier because you will not notice a runtime difference at all.
If the total number of characters is relatively small, then you won't notice the difference between the approaches.
Else (the number of characters is large), if most of characters move during a frame, then the approach with flag inside a character seems more appropriate, because even with vector of moved characters, you'll traverse all of them and besides that you get additional overhead of maintaining the vector.
Else (the number of characters is large, but only few of them move during a frame), it may be better to use vector because it can save you time by not traversing characters which didn't move.
What is a small or large number, depends on your application. You should test under which conditions you get better performance using either of approaches.
This would be the right time to quote Hoare, but I'll abstain. Generally, however, you should profile before you optimize (if, and only if, the time budget is not enough on the minimum spec hardware -- if your game runs at 60fps on the target hardware you will do nothing whatsoever).
It is much more likely that the actual physics calculations will be the limiting factor, not doing the "is this unit moving?" check. Also, it is much more likely that submitting draw calls will bite you rather than checking a few hundred or so units.
As an "obvious" thing, it appears to be faster to hold a vector of object pointers and only process the units that are actually moving. However, the "obvious" is not always correct. Iterating linearly over a greater number of elements can very well be faster than jumping around (due to cache). Again, if this part of your game is identified as the bottleneck (very unlikely) then you will have to measure which is better.

Defending classes with 'magic numbers'

A few months ago I read a book on security practices, and it suggested the following method for protecting our classes from overwriting with e.g. overflows etc.:
first define a magic number and a fixed-size array (can be a simple integer too)
use that array containing the magic number, and place one at the top, and one at the bottom of our class
a function compares these numbers, and if they are equal, and equal to the static variable, the class is ok, return true, else it is corrupt, and return false.
place this function at the start of every other class method, so this will check the validity of the class on function calls
it is important to place this array at the start and the end of the class
At least this is as I remember it. I'm coding a file encryptor for learning purposes, and I'm trying to make this code exception safe.
So, in which scenarios is it useful, and when should I use this method, or is this something totally useless to count on? Does it depend on the compiler or OS?
PS: I forgot the name of the book mentioned in this post, so I cannot check it again, if anyone of you know which one was it please tell me.
What you're describing sounds a Canary, but within your program, as opposed to the compiler. This is usually on by default when using gcc or g++ (plus a few other buffer overflow countermeasures).
If you're doing mutable operations on your class and you want to make sure you don't have side effects, I don't know if having a magic number is very useful. Why rely on a homebrew validity check when there are mothods out there that are more likely to be successful?
Checksums: I think it'd be more useful for you to hash the unencrypted text and add that to the end of the encrypted file. When decrypting, remove the hash and compare the hash(decrypted text) with what it should be.
I think most, if not all, widely used encryptors/decryptors store some sort of checksum in order to verify that the data has not changed.
This type of a canary will partially protect you against a very specific type of overflow attack. You can make it a little more robust by randomizing the canary value every time you run the program.
If you're worried about buffer overflow attacks (and you should be if you are ever parsing user input), then go ahead and do this. It probably doesn't cost too much in speed to check your canaries every time. There will always be other ways to attack your program, and there might even be careful buffer overflow attacks that get around your canary, but it's a cheap measure to take so it might be worth adding to your classes.

Performance OVER TIME problem

Hey so i'm making a simple text game using the pdCurses library and a few other minor things kind of like a vertical scroller in which you avoid the randomly generated walls....
Theres two walls on lef and right made out of 'X' characters and blank, black space in which you can move around and avoid the 'X's your character is an '8' and your forced to continue forward or get touched by the X's each time a new line of the randomly generated "map" is revealed( for performance tests i made a new line shown as fast as possible).
However i'm having some performance problems as the "map" (a vector of strings) gets bigger and bigger. I do not understand the problem however as i am not using all of it at any time, i'm only pulling out parts of it to display (56 lines usually).
I'll show you what i've got and hopefully someone will help or suggest a better way to accomplish my game.
Here's the condensed, important code:
Here's the function that is taking like .25-.75 seconds (new_map is also a vector member of the "Screen" class):
void Insert(const Map& map, int y1, int y2) {for ( int mc = y1, nm= 0; mc< map.Contents().size() && mc< y2; mc++, nm++)
new_map[nm] = map.Contents(mc);};
Here's the Map classes contents functions:
string Contents(int Y) {return contents[Y];};
char Contents(int Y, int X) {return contents[Y][X];};
vector <string> Save() {return save;};
and finally the main() which i have set so the screen updates as fast as possible... which isn't turning out to be so fast oh and L1 is one of my "maps"...
generate adds on new lines to the map as so it never ends:
double refreshes= 0;
for (bool quit = false; quit != true;)
{ double newTime= myStopwatch.ElapsedTime()- refreshes;
theScreen.Insert(L1, 0+refreshes, nrows+refreshes);
refreshes++;
if(L1.Contents().size()<= nrows+refreshes+2)
L1.generate();}
Thanks for any help or tips!! I know it's pretty terrible but i just started programming 2 months ago haha! =) ask if you need any more info.
The general issue seems to be that as your data set gets larger things like copying it around (which you seem to do all the time, e.g. in your snippet you are copying strings from one vector to the other) take longer.
Things to consider:
Do you need the data that is coming
off the screen?
Can you use C style array? Those would generally be faster and you'd also be able to see more clearly where the inefficiencies are.
Try thinking of your scrolling as simply moving the point from where you fetch data to the screen. You shouldn't need to make any copies or move any data around.
As an example for point #1 you may prefer to store your screen lines in a list and do something like:
std::list<string> screen;
// fill up with your initial screen.
generate(line); // generate your new line
screen.push_back(line); // to add a line
screen.pop_front(); // remove a line from the top
It's not perfect (there's memory management and some copying behind the scenes) but it will outperform copying and accumulating all the screen lines.
As an example for point #2, consider this code:
char screen[25][80];
for(int y = 0; y < 25; y++)
{
for(int x = 0; x < 79; x++)
{
screen[y][x] = screen[y][x+1];
}
}
This will "scroll" screen one character to the left. It will keep running at a constant and pretty fast time - on any modern CPU you can expect to be able to do over about a million of these scrolling operations per second.
Try unordered_map instead, its performance characteristics are somewhat better as the size grows. oops, you've got your own Map class that has nothing to do with std::map.
Anyway, the function you showed definitely could get slower as the vector gets larger. You say you don't need all the data at once, so some other data structure would probably be better. But without knowing more about your design (and by that I mean an explanation of what you're trying to accomplish, not just a copy of all the code), it's hard to recommend one.
You might think about keeping track of the indexes somehow, instead of copying the strings themselves around.

How should I store and and use gun fire data in a game?

On this game I have 3 defense towers (the number is configurable) which fire a "bullet" every 3 seconds at 30km/h. These defense towers have a radar and they only start firing when the player is under the tower radar. That's not the issue.
My question is how to store the data for the gun fire. I'm not sure exactly what data do I need for each bullet, but one that comes to mind is the position of the bullet of course. Let's assume that I only need to store that (I already have a struct defined for a 3D point) for now.
Should I try to figure it out the maximum bullets the game can have at a particular point and declare an array with that size? Should I use a linked-list? Or maybe something else?
I really have no idea how to do this. I don't need anything fancy or complex. Something basic that just works and it's easy to use and implement is more than enough.
P.S: I didn't post this question on the game development website (despite the tag) because I think it fits better here.
Generally, fixed length arrays aren't a good idea.
Given your game model, I wouldn't go for any data structure that doesn't allow O(1) removal. That rules out plain arrays anyway, and might suggest a linked list. However the underlying details should be abstracted out by using a generic container class with the right attributes.
As for what you should store:
Position (as you mentioned)
Velocity
Damage factor (your guns are upgradeable, aren't they?)
Maximum range (ditto)
EDIT To slightly complicated matters the STL classes always take copies of the elements put in them, so in practise if any of the attributes might change over the object's lifetime you'll need to allocate your structures on the heap and store (smart?) pointers to them in the collection.
I'd probably use a std::vector or std::list. Whatever's easiest.
Caveat: If you are coding for a very constrained platform (slow CPU, little memory), then it might make sense to use a plain-old fixed-size C array. But that's very unlikely these days. Start with whatever is easiest to code, and change it later if and only if it turns out you can't afford the abstractions.
I guess you can start off with std::vector<BulletInfo> and see how it works from there. It provides the array like interface but is dynamically re-sizable.
In instances like this I prefer a slightly more complex method to managing bullets. Since the number of bullets possible on screen is directly related to the number of towers I would keep a small fixed length array of bullets inside each tower class. Whenever a tower goes to fire a bullet it would search through its array, find an un-used bullet, setup the bullet with a new position/velocity and mark it active.
The slightly more complex part is I like to keep a second list of bullets in an outside manager, say a BulletManager. When each tower is created the tower would add all its bullets to the central manager. Then the central manager can be in charge of updating the bullets.
I like this method because it easily allows me to manage memory constrains related to bullets, just tweak the 'number of active towers' number and all of the bullets are created for you. You don't need to allocate bullets on the fly because they are all pooled, and you don't have just one central pool that you constantly need to change the size of as you add/remove towers.
It does involve slightly move overhead because there is a central manager with a list of pointers. And you need to be careful to always remove any bullets from a destroyed tower from the central manager. But for me the benefits are worth it.

Function pointers and their called parameters

This may be the wrong approach, but as I dig deeper into developing my game engine I have ran into a timing issue.
So lets say I have a set of statements like:
for(int i = 0; i < 400; i++)
{
engine->get2DObject("bullet")->Move(1, 0);
}
The bullet will move, however, on the screen there won't be any animation. It will basically "warp" from one part of the screen to the next.
So, I am thinking...create a vector of function pointers for each base object (which the user inherits from) and when they call "Move" I actually don't move the object until the next iteration of the game loop.
So something like:
while(game.running())
{
game.go();
}
go()
{
for(...)
2dobjs.at(i)->action.pop_back();
}
Or something like that, and this way it runs only a single action of each object during each iteration (of course I'll add in a check to see if there is actually "actions" to be ran).
And if that is a good idea, my question is how do I store the parameters. Since each object can do more than a single type of "action" rather than move (rotateby is one example), I think it would be nonsensical to create a struct similar in fashion to:
struct MoveAction {
MovePTR...;
int para1;
int para2;
};
Thoughts? Or is this the completely wrong direction?
Thoughts? Or is this the completely wrong direction?
It's the wrong direction.
Actually, the idea of being able to queue actions or orders has some merit. But usually this applies to things like AI and to more general tasks (like "proceed to location X", "attack anything you see", etc). So it usually doesn't cover the frame-by-frame movement issue that you're dealing with here.
For very simply entities like bullets, queuing tasks is rather overkill. After all, what else is a bullet going to do except move forward each time? It's also an awkward way to implement such simple motion. It brings up issues like, why only 400 steps forward? What if the area in front is longer? What if its shorter? What if some other object gets in the way after only say 50 steps? (Then 350 queued move actions were a waste.)
Another problem with this idea (at least in the simplistic way you've presented it) is that your bullets are going to move a fixed amount per each iteration of your game loop. But not all iterations are going to take the same amount of time. Some people's computers will obviously be able to run the code faster than others. And even disregarding that, sometimes the game loop may be doing considerably more work than other times (such as when many more entities are active in the game). So you would really want a way to factor in the time that each iteration is taking to adjust the movement and such so that the everything appears to move at a consistent speed to the user, regardless of how fast the game loop is running.
So instead of each movement action being "move X amount" they would be "move at X speed" and would then be multiplied by something like the time elapsed since the last iteration. And then you would really never know how many move actions to queue, because it would depend on how fast your game loop is running in that scenario. But again, this is another indication that queuing movement actions is an awkward solution to frame-by-frame movement.
The way most game engines do it is to simply call some sort of function on the each object each frame which evaluates its movement. Maybe a function like void ApplyMovement(float timeElapsedSinceLastFrame);. In the case of a bullet, it would multiply the speed at which a bullet should move per second by the passed in time since the last frame to determine the amount that the bullet should move this frame. For more complex objects you might want to do math with rotations, accelerations, decelerations, target-seeking, etc. But the general idea is the same: call a function each iteration of the game loop to evaluate what should happen for that iteration.
I don't think this is the right direction. After you store 400 moves in a vector of function pointers, you'll still need to pop and perform a move, redraw the screen, and repeat. Isn't it easier just to move(), redraw, and repeat?
I'd say your bullet is warping because it's moving 400 pixels/frame, not because you need to delay the move calculations.
But if this is the correct solution for your architecture, in C++ you should use classes rather than function pointers. For example:
class Action // an abstract interface for Actions
{
public:
virtual void execute() = 0; // pure virtual function
}
class MoveAction: public Action
{
public:
MoveAction(Point vel) : velocity(vel) {}
virtual void execute();
Point velocity;
...
}
std::vector<Action*> todo;
gameloop
{
...
todo.push_back(new MoveAction(Point(1,0))
...
}
So where does 400 come from? Why not just do it this way:
go()
{
engine->get2DObject("bullet")->Move(1, 0);
}
I think the general approach could be different to get what you want. I personally would prefer a setup where each go loop called functions to set the position for all objects including the bullet, then draw the scene. So each loop it would put the bullet where it should be right then.
If you do decide to go your route, you will likely have to do your struct idea. It's not pleasant, but until we get closures, you'll have to do.