• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
mypel16000

Killing AI

34 posts in this topic

Hi there,

 

I am making a game of zombies and I am trying to make them die when I hit them. I have tried different methods, but they never work.

I just need some concepts to base my code on.

 

What I thought was:

 

having :          if the bullet hits the zombie, take 10 away from its health;

another if:      if health < 0, make a bool variable "Dead" true;

My zombies are stored in a vector, so:

 

for (int i = 0 ;  i < zombie.size() ; i++ )

{

      if( zombie[ i ].Dead )

     {

          zombie.clear( zombie.begin() + i )

     }

}

 

But this didn't work, I shot one and it died, but when I shot the 2nd one, all of the zombies on the screen died. How can I do this effectively?

 

 

P.S: I have tried simple deleting the object using delete zombies[ i ], but the program just stops responding

0

Share this post


Link to post
Share on other sites

I've tried, but the game "stops responding" when you use delete zombie[ i ]. Has it got something to do with its members or its functions or.... does it need a destructor?

0

Share this post


Link to post
Share on other sites

i suspect the problem is in your code for setting the dead flag.

 

edit: nvm, thought u were using erase, not clear.

Edited by slicer4ever
0

Share this post


Link to post
Share on other sites

the problem is in how I use the vectors I think, when I try to delete 1. all of the others are deleted,,,

0

Share this post


Link to post
Share on other sites

[quote name='mypel16000' timestamp='1358719100' post='5023641']
I've tried, but the game "stops responding" when you use delete zombie[ i ]
[/quote]

Could your array be going out of bounds?

0

Share this post


Link to post
Share on other sites

Isn't a zombie already dead?

 

(sorry for lame joke :P)

 

Anyway, you'd want to set it up so as soon as the zombie's health reaches 0 (not < 0, but <= 0) the game sets it as "dead".

1

Share this post


Link to post
Share on other sites

The problem is that you're modifying the very collection that you're iterating through. Every time you delete something from a collection that you're going through, the size will change, but not in the loop, so original size (i.e. 10) will now be one less, (i.e. 9), and when you get to the last original index (i.e. 10), you'll access random location, and usually crash the app.

Save indexes of zombies to delete in another collection, and delete them in one consistent loop after the loop you're doing now.

2

Share this post


Link to post
Share on other sites

This isn't working on my code. I believe I have got to the problem, and it is the bool "dead". I can't seem to fix what is wrong though.

 

What I first do is check to see if health is less than zero by looping through the objects in my vector:       zombies[ i ].checkHEalth();

If it returns a 0 or less, i change a public bool in the object ( dead ) to true. Then I loop through them again and zombies.clear() the ones that return true for dead. The problem is that on debugging the code, i find that when one dies all of the bools in the loop turn to true, and therefore they are all deleted.

 

Any more ideas about this

0

Share this post


Link to post
Share on other sites

 

for (vector<zombiesClass*>::iterator i = zombies.begin() ; 
i != zombies.end() ;)
{
if( (*i)->Dead )
{
delete zombies(i);
zombies.erase(i);
}
else ++i;
}

 

 

Perhaps something like this? (argh, cant get rid of italic text..)

 

Im not to sure this works thou. It deallocated the object and removes it from the vector without invalidizing the vector. Atleast that's what I intent to do with this code.

0

Share this post


Link to post
Share on other sites
Are you declaring your vector like this:
 
std::vector<Zombie> zombies;
 
Or like this:
std::vector<Zombie*> zombies;
 
 
P.S: I have tried simple deleting the object using delete zombies[ i ], but the program just stops responding
 
You can only 'delete' objects you have 'new'd. If you don't know what new or delete do, just don't touch them at all until you thoroughly research the issue.
new and delete are dangerous to your code (but won't do any harm to your computer, so feel free to experiment) if used improperly.
 
std::vectors are made for very fast access. It's not good for fast removals or fast inserts, unless you remove or insert from the end of the list with push_back() or pop_back(). You probably want a std::list, which is designed for inserting and erasing from in the very middle of the container.
 
std::list<Zombie> zombies;
typedef std::list<Zombie>::iterator ZombieIterator;
for(ZombieIterator it = zombies.begin(); it !- zombies.end(); it++)
{
	if(it->dead)
	{
		it = zombies.erase(it); //erase() removes the element at the position given, and returns the next element.
		it--; //Take a step back, so the for-loops 'it++' doesn't skip an element.
	}
}
 
Alternatively, you could use the "swap and pop" method. Swaps are fast. Pops are fast. You swap the dead zombie with the live zombie at the end of the vector (messing up ordering, but you might not care about the order in this situation), and pop back the vector erasing the dead zombie.
std::vector<Zombie> zombies;
typedef d::vector<Zombie>::iterator ZombieIterator;

for(ZombieIterator it = zombies.begin(); it != zombies.end(); it++)
{
	if(it->dead)
	{
		//Swap the value of the current zombie with the zombie at the back of the container.
		std::swap(*it, zombies.back());
		//Pop the back of the container.
		zombies.pop_back();
	}
}

A third method is to use a standard algorithm like std::remove_if() to do this for you. You pass a range of iterators to std::remove_if(), and you also pass a callback function or functor to say which elements to remove.
bool ZombieIsDead(const Zombie &zombie)
{
	return zombie.dead;
}

std::vector<Zombie> zombies;
typedef d::vector<Zombie>::iterator ZombieIterator;

ZombieIterator newEnd = std::remove_if(zombies.begin(), zombies.end(), ZombieIsDead);
zombies.erase(newEnd, zombies.end());

If using C++11, you can use a lambda as a callback function.
2

Share this post


Link to post
Share on other sites

Two of those methods are broken.

 

In the first method, if you erase the first element, the iterator will be pointing to the first element still when it is decremented, which is undefined behaviour.

 

In the second method, if you erase the last element, the iterator will be pointing at the end when it is incremented, which undefined behaviour again (and probably a crash).

 

The correct method would be to move the ++it inside the body of the for loop, and only call it if erase was not called, otherwise set the iterator to the return value of erase.

2

Share this post


Link to post
Share on other sites

I knew I should've tested the snippets before posting them. laugh.png
 
So the correct method to 'swap and pop' is:

std::vector<Zombie> zombies;
typedef d::vector<Zombie>::iterator ZombieIterator;
 
for(ZombieIterator it = zombies.begin(); it != zombies.end();)
{
	if(it->dead)
	{
		//Swap the value of the current zombie with the zombie at the back of the container.
		std::swap(*it, zombies.back());
		//Pop the back of the container.
		zombies.pop_back();
	}
	else
	{
		++it;
	}
}

Looking over my previous version, it'd also skip whatever elements were at the end before being swapped. rolleyes.gif

 

But the correct choice in most cases is the third solution I posted, using the heavily optimized and standardized std::remove_if() algorithm.

0

Share this post


Link to post
Share on other sites
I knew I should've tested the snippets before posting them. laugh.png

So the correct method to 'swap and pop' is:
std::vector<Zombie> zombies;typedef d::vector<Zombie>::iterator ZombieIterator; for(ZombieIterator it = zombies.begin(); it != zombies.end();){	if(it->dead)	{		//Swap the value of the current zombie with the zombie at the back of the container.		std::swap(*it, zombies.back());		//Pop the back of the container.		zombies.pop_back();	}	else	{		++it;	}}
Looking over my previous version, it'd also skip whatever elements were at the end before being swapped. rolleyes.gif

But the correct choice in most cases is the third solution I posted, using the heavily optimized and standardized std::remove_if() algorithm.
This isn't right man, try this when all Zombies are dead, and you'll end up with a crash, as when you pop_back the very first element, the iterator becomes invalid. It will be ok, as long as there's at least one element left though.
It's always good idea to make sure what does and what doesn't invalidate your iterator, and avoid any such cases if possible. It saves time in the future.

remove_if() does the trick for most cases, although it may not be as fast, due to additional calls overhead. Edited by Mercile55
1

Share this post


Link to post
Share on other sites

Just so I'm clear, the iterator isn't invalidated by pop_back(), except when the iterator is pointing at the last element, right?

 

std::vector::pop_back() - The end iterator and any iterator, pointer and reference referring to the removed element are invalidated.
Iterators, pointers and references referring to other elements that have not been removed are guaranteed to keep referring to the same elements they were referring to before the call.


So only if there is just one element left, then it will crash. I'm not seeing how it will crash on the first element.
 
So, would this work:

 

for(ZombieIterator it = zombies.begin(); it != zombies.end();)
{
	if(it->dead)
	{
		//Swap the value of the current zombie with the zombie at the back of the container.
		std::swap(*it, zombies.back());
		//Pop the back of the container.
		zombies.pop_back();
		
		if(zombies.empty())
		{
			break;
		}
	}
	else
	{
		++it;
	}
}


Or am I just digging myself deeper? smile.png

Edited by Servant of the Lord
1

Share this post


Link to post
Share on other sites
while ( it != zombies.end() )
{
    if  ( it->dead )
    {
        it = zombies.erase( it );
    }
    else
    {
        ++it;
    }
}

I remembered I had a similar issue before and using a while loop instead worked better :D

1

Share this post


Link to post
Share on other sites
It's not a question of whether there's one element left or not, when you pop_back the last element the iterator is invalidated right before you compare it with end().

Now, I think a sensible implementation would not crash here (in contrast to the first version), but it should give an error in debug mode. You could get around it by special-casing the last element.

Or use indices, which don't have this problem.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0