I'm trying to implement a space invader game, now I'm trying to check if bullets hit an invader, then I remove it.
I'm ONLY get an exception when I try to shoot the last invader in the row.
For e.g If I have just one row and 8 invaders, the last one, when the bullet hits it, I got a strange boundary out of exception.
The initialization is like that, in pseudo code:
struct Invaders_t
{
vector<Invader*> *invaders;
}
for (int j = 0; j < 1; j++)
{
x_spacing = 15;
for (int i = 0; i < 8; i++)
{
Invader *invader = new Invader();
g_Invaders.invaders->push_back(invader);
}
for each frame:
for (int x = 0; x < 1; x++)
{
for (int y = 0; y < 8; y++)
{
Invader *pInvader = (*(g_Invaders.invaders))[x*8 + y];
if (pInvader != nullptr && pInvader->AlienAtals->GetImage() != nullptr)
{
for (list<Bullet*>::iterator it = ship->Bullets->begin(); it != ship->Bullets->end(); it++)
{
float left = (*it)->Position.x - 5;
float top = (*it)->Position.y - 13;
if (CheckCollision(left, top, pInvader->AlienSprite->m_X, pInvader->AlienSprite->GetImage()->GetWidth()/4
, pInvader->AlienSprite->m_Y, pInvader->AlienSprite->GetImage()->GetHeight()/4))
{
std::vector<Invader*>::iterator iter = g_Invaders.invaders->begin();
std::advance(iter, (x *8) + y);
Invader *invader = *iter;
g_Invaders.invaders->erase(iter);
delete invader;
}
}
}
}
}
When you delete an invader (g_Invaders.invaders->erase(iter);), the size of the vector decreases by 1 (all vector's elements after iter shift by 1 position to the beginning, filling the vacant space). Your code doesn't expect this and continues iterating over the vector as if still had the full set of elements.
Related
I'm building Space Invaders in C++ (using the MBed platform) for a microcontroller. I've used a 2D Vector of object pointers to organise the invaders.
The movement algorithm is below, and runs in the main while loop for the game. Basically, I get the highest/lowest x and y values of invaders in the vector, and use those to set bounds based on screensize (the HEIGHT variable);
I also get the first invader's position, velocity, and width, which I apply changes to based on the bounds above.
Then I iterate through the whole vector again and apply all those changes. It sort of works – the invaders move – but the bounds don't seem to take effect, and so they fly off screen. I feel like I'm missing something really dumb, thanks in advance!
void Army::move_army() {
int maxy = HEIGHT - 20;
int Ymost = 0; // BOTTOM
int Yleast = 100; // TOP
int Xmost = 0; // LEFT
int Xleast = 100; // RIGHT
int first_row = _rows;
int first_column = _columns;
int firstWidth = 0;
Vector2D firstPos;
Vector2D firstVel;
for (int i = 0; i < _rows; i++) {
for (int n = 0; n < _columns; n++) {
bool state = invaders[i][n]->get_death();
if (!state) {
if (i < first_row && n < first_column) {
firstPos = invaders[i][n]->get_pos();
firstVel = invaders[i][n]->get_velocity();
firstWidth = invaders[i][n]->get_width();
}
Vector2D pos = invaders[i][n]->get_pos();
if (pos.y > Ymost) {Ymost = pos.y;} // BOTTOM
else if (pos.y < Yleast) {Yleast = pos.y;} // TOP
else if (pos.x > Xmost) {Xmost = pos.x;} // LEFT
else if (pos.x < Xleast) {Xleast = pos.x;} // RIGHT
}
}
}
firstVel.y = 0;
if (Xmost >= (WIDTH - 8) || Xleast <= 2) {
firstVel.x = -firstVel.x;
firstPos.y += _inc;
// reverse x velocity
// increment y position
}
else if (Ymost > maxy) {
_inc = -_inc;
// reverse increment
}
else if (Yleast < 2) {
_inc = -_inc;
// reverse increment
}
for (int i = 0; i < _rows; i++) {
int setx = firstPos.x;
if (i > 0) {firstPos.y += 9;}
for (int n = 0; n < _columns; n++) {
invaders[i][n]->set_velocity(firstVel);
invaders[i][n]->set_pos(setx,firstPos.y);
setx += firstWidth + 2;
}
}
It looks like you have your assignment cases reversed. Assignment always goes: right <- left, so in the first case you're changing the YMost value, not pos.y. It looks like if you swap those four assignments in your bounds checking it should work. Good luck!
I am working with a dynamic square 2D array that I sometimes need to enlarge for my needs. The enlarging part consist in adding a new case on each border of the array, like this:
To achieve this, I first copy the content of my actual 2D array in a temporary other 2D array of the same size. Then I create the new 2D array with the good size, and copy the original content of the array in the middle of the new one.
Is there any quick way to copy the content of the old array in the middle of my new array? The only way I have found so far is only by using two for sections:
for(int i = 1; i < arraySize-1; i++)
{
for(int j = 1; j < arraySize-1; j++)
{
array[i][j] = oldArray[i-1][j-1];
}
}
But I'm wondering if there is no quicker way to achieve this. I thought about using std::fill, but I don't see how it would be possible to use it in this particular case.
My EnlargeArray function:
template< typename T >
void MyClass<T>::EnlargeArray()
{
const int oldArraySize = tabSize;
// Create temporary array
T** oldArray = new T*[oldArraySize];
for(int i = 0; i < oldArraySize; i++)
{
oldArray[i] = new T[oldArraySize];
}
// Copy old array content in the temporary array
for(int i = 0; i < arraySize; i++)
{
for(int j = 0; j < arraySize; j++)
{
oldArray[i][j] = array[i][j];
}
}
tabSize+=2;
const int newArraySize = arraySize;
// Enlarge the array
array= new T*[newArraySize];
for(int i = 0; i < newArraySize; i++)
{
array[i] = new T[newArraySize] {0};
}
// Copy of the old array in the center of the new array
for(int i = 1; i < arraySize-1; i++)
{
for(int j = 1; j < arraySize-1; j++)
{
array[i][j] = oldArray[i-1][j-1];
}
}
for(int i = 0; i < oldArraySize; i++)
{
delete [] oldArray[i];
}
delete [] oldArray;
}
Is there any quick way to copy the content of the old array in the middle of my new array?
(Assuming the question is "can I do better than a 2D for-loop?".)
Short answer: no - if your array has R rows and C columns you will have to iterate over all of them, performing R*C operations.
std::fill and similar algorithms still have to go through every element internally.
Alternative answer: if your array is huge and you make sure to avoid
false sharing, splitting the copy operation in multiple threads that deal with a independent subset of the array could be beneficial (this depends on many factors and on the hardware - research/experimentation/profiling would be required).
First, you can use std::make_unique<T[]> to manage the lifetime of your arrays. You can make your array contiguous if you allocate a single array of size row_count * col_count and perform some simple arithmetic to convert (col, row) pairs into array indices. Then, assuming row-major order:
Use std::fill to fill the first and last rows with zeros.
Use std::copy to copy the old rows into the middle of the middle rows.
Fill the cells at the start and end of the middle rows with zero using simple assignment.
Do not enlarge the array. Keep it as it is and allocate new memory only for the borders. Then, in the public interface of your class, adapt the calculation of the offets.
To the client of the class, it will appear as if the array had been enlarged, when in fact it wasn't really touched by the supposed enlargement. The drawback is that the storage for the array contents is no longer contiguous.
Here is a toy example, using std::vector because I cannot see any reason to use new[] and delete[]:
#include <vector>
#include <iostream>
#include <cassert>
template <class T>
class MyClass
{
public:
MyClass(int width, int height) :
inner_data(width * height),
border_data(),
width(width),
height(height)
{
}
void Enlarge()
{
assert(border_data.empty()); // enlarge only once
border_data.resize((width + 2) * 2 + (height * 2));
width += 2;
height += 2;
}
int Width() const
{
return width;
}
int Height() const
{
return height;
}
T& operator()(int x, int y)
{
assert(x >= 0);
assert(y >= 0);
assert(x < width);
assert(y < height);
if (border_data.empty())
{
return inner_data[y * width + x];
}
else
{
if (y == 0)
{
return border_data[x]; // top border
}
else if (y == height - 1)
{
return border_data[width + x]; // bottom border
}
else if (x == 0)
{
return border_data[width + height + y]; // left border
}
else if (x == width - 1)
{
return border_data[width * 2 + height * 2 + y]; // right border
}
else
{
return inner_data[(y - 1) * (width - 2) + (x - 1)]; // inner matrix
}
}
}
private:
std::vector<T> inner_data;
std::vector<T> border_data;
int width;
int height;
};
int main()
{
MyClass<int> test(2, 2);
test(0, 0) = 10;
test(1, 0) = 20;
test(0, 1) = 30;
test(1, 1) = 40;
for (auto y = 0; y < test.Height(); ++y)
{
for (auto x = 0; x < test.Width(); ++x)
{
std::cout << test(x, y) << '\t';
}
std::cout << '\n';
}
std::cout << '\n';
test.Enlarge();
test(2, 0) = 50;
test(1, 1) += 1;
test(3, 3) = 60;
for (auto y = 0; y < test.Height(); ++y)
{
for (auto x = 0; x < test.Width(); ++x)
{
std::cout << test(x, y) << '\t';
}
std::cout << '\n';
}
}
Output:
10 20
30 40
0 0 50 0
0 11 20 0
0 30 40 0
0 0 0 60
The key point is that the physical representation of the enlarged "array" no longer matches the logical one.
I have a problem to get access to the second position of a three-dimensional array.
See code:
int qtdMosquitos = 2500000;
int altura = 500, largura = 500, i, j, k, qtdMosquitoPorCelula = qtdMosquitos /(altura*largura);
long id = 1;
Mosquito* mosquitos[qtdMosquitos][qtdMosquitos][qtdMosquitoPorCelula];
Mosquito* listaMosquitos[qtdMosquitoPorCelula];
for (i = 0; i < altura; i++) {
for (j = 0; j < largura; j++) {
for (k = 0; k < qtdMosquitoPorCelula; k++) {
Mosquito* mosquito = new Mosquito();
mosquito->setId(id);
mosquito->setState("S");
listaMosquitos[k] = mosquito;
}
mosquitos[i][j] = listaMosquitos;
}
}
Line mosquitos[i][j] = listaMosquitos; displays the following error:
main.cpp|24|error: invalid array assignment|
I understand what error says, but I can not find the cause, we already created the instance of the 3D matrix with the same variable that is created the simple array, variable qtdMosquitoPorCelula.
Could you help me set a value for the 3D array?
As follows: matrix[0][1] = arraySimples;
Since the array in C is the pointer of the first element of the array. Therefore, the code
mosquitos[i][j] = listaMosquitos;
means assigning the pointer of listaMosquitos[0] to mosquitos[i][j][0] which will cause memory issue and the compile will prohibit it.
In the code sample, we can do the same thing with the following code sample:
.....
for (i = 0; i < altura; i++) {
for (j = 0; j < largura; j++) {
for (k = 0; k < qtdMosquitoPorCelula; k++) {
Mosquito* mosquito = new Mosquito();
mosquito->setId(id);
mosquito->setState("S");
listaMosquitos[k] = mosquito;
mosquitos[i][j][k] = mosquito;
}
}
}
To represent all the cells I'm using a variable std::vector<bool> cells to represent the cells where true represents a live cell. To update the canvas, I have a variable std::vector<int> neighborCounts, where neighborCounts[i] represents how many live neighbors cell[i] has. In the update loop, I loop through all the cells, and if its a live cell, I add 1 to the neighborCounts of all the adjacent cells. Then after determining all of the neighbors, I once again loop through all the cells and perform the updates based on the number of neighbors it has.
std::vector<int> neighborCounts(NUM_ROWS * ROW_SIZE, 0);
for (int x = 0; x < ROW_SIZE; x++)
{
for (int y = 0; y < NUM_ROWS; y++)
{
if (cells[convertCoord(x, y)])
{
for (int m = x - 1; m <= x + 1; m++)
{
for (int n = y - 1; n <= y + 1; n++)
{
if (!(m == x && n == y) && m >= 0 && m < ROW_SIZE && n >= 0 && n < NUM_ROWS)
{
neighborCounts[convertCoord(m, n)] += 1;
}
}
}
}
}
}
for (int x = 0; x < ROW_SIZE; x++)
{
for (int y = 0; y < NUM_ROWS; y++)
{
int coord = convertCoord(x, y);
int numNeighbors = neighborCounts[coord];
if (cells[coord])
{
if (numNeighbors < 2)
{
cells[coord] = false;
}
else if (numNeighbors > 3)
{
cells[coord] = false;
}
}
else
{
if (numNeighbors == 3)
{
cells[coord] = true;
}
}
}
}
Then in the render function, I loop through all the cells and if its alive I draw it to the screen.
This seems to be the most straightforward way to do this, but there's definitely room for further optimization. How do powder toys and other apps manage a huge array of particles and yet still manage to run amazingly smooth? What is the most efficient way to manage all the cells in Conway's Game of Life?
I'm making a 2D game in c++ and am trying to shoot enemies. When a bullet collides with the first enemy rendered then the enemy is killed fine, and it is removed from the enemys vector. However after the first enemy has been killed, other enemies no longer die.
This is where the check is carried out in the update function.
size = enemys.size();
for (int i = 0; i<size; i++)
{
double x = enemys[i].getEnemyX();
double y = enemys[i].getEnemyY();
bool isShot = enemyShot(x,y);
if(isShot == true){
enemys.erase(enemys.begin()+i);
size = size - 1;
}
}
This is the enemyShot function.
bool GameActivity::enemyShot(double enemyX, double enemyY)
{
int size = bullets.size();
for (int i = 0; i<size; i++)
{
double x = bullets[i].getX();
double y = bullets[i].getY();
if (x >= enemyX-5.0 && x <= enemyX+5.0 && y >= enemyY-5.0 && y <= enemyY + 5.0){
return true;
}
else{
return false;
}
}
}
The problem is that your vector of enemies is updated after each erasure - thus, the current index is no longer correct.
A better way to iterate the enemys vector is to start from the end of the enemys vector. That way, when you erase an element, the index is still correct:
for (size_t i = enemys.end (); i> 0; --i) {
double x = enemys[i].getEnemyX();
double y = enemys[i].getEnemyY();
bool isShot = enemyShot(x,y);
if(isShot == true){
enemys.erase(enemys.begin()+i);
}
}