Reputation: 23
I'm doing a simple Zombie island game in the console and I'm trying to make the zombies die when the human lands on them.
To create the zombies I used my Zombie class like this:
Zombies *zombie = new Zombies[4];
To check if the human and the zombie are on the same place I used a simple for loop:
int zombieCount = 4;
for (int i = 0; i < 4; i++)
{
if (player.getPosX() == zombie[i].getPosX() && player.getPosY() == zombie[i].getPosY())
{
zombieCount--;
}
}
Besides decreasing the zombieCount, the zombie I hit should disappear from the game. How do I do that?
Upvotes: 1
Views: 248
Reputation: 31
In C++11, you can use std::remove(first, last, value)
to remove certain elements in an array. The function returns the new array ending, e.g. use:
auto end = std::remove(std::begin(zombie), std::end(zombie), zombie[i]);
I'd suggest to use std::vector
which is a dynamic array which suits more your needs.
References: std::remove and std::vector.
Suggested std::vector example:
std::vector<Zombies> zombies;
// init with zombies.push_back(someZombie);
for (vector<Zombies>::iterator it = zombies.begin(); it != zombies.end(); /*no ++it*/) {
if (player.getPosX() == it->getPosX() && player.getPosY() == it->getPosY())
it = zombies.erase(it);
else
++it;
}
int zombieCount = zombies.size();
Upvotes: 2
Reputation: 881
You can use std::erase-remove_if with lambda as in following one-liner:
zombies.erase(std::remove_if(zombies.begin(), zombies.end(),
[& player](const Zombie& z){return player.getPosX() == z.getPosX() && player.getPosY() == z.getPosY();}),
zombies.end());
Supposed you have a vector<Zombie> zombies
or list<Zombie>
or another container that can be reordered.
Upvotes: 1
Reputation: 25516
NathanOliver recommended in a comment to use std::remove_if
- in my eyes best of the so far proposed solutions, unfortunately it is just a comment, so I illustrate here how it could look like (a little shortened by just comparing the X-coordinate...):
Person p;
std::vector<Zombie> zombies(4);
auto end = std::remove_if
(
zombies.begin(), zombies.end(),
[&p](Zombie const& zombie) { return (zombie.getPosX() == p.getPosX()) && (zombie.getPosY() == p.getPosY()); }
);
zombies.erase(end, zombies.end());
Upvotes: 0
Reputation: 3305
Use a vector
container:
Zombies zombieModel;
std::vector<Zombies> zombieVec(10, zombieModel);
int zombieCount = zombieVec.size();
for (int i = 0; i < zombieVec.size(); i++)
{
if (player.getPosX() == zombieVec[i].getPosX() && player.getPosY() == zombieVec[i].getPosY())
{
zombieCount--;
zombieVec.erase(zombieVec.begin()+i);
i--;
}
}
Upvotes: 0