I am working on a brick breaker game, and I have a bug in my code that I’m trying to fix. I made a vector of 5 bricks that are rendered to the console. When the ball hits a brick it changes color. On the third hit, the color turns black and it is removed from the vector. My problem is, when a brick is removed, I get an error message saying for a read access violation that brings me to this code snippet from the vector class:
_CONSTEXPR20 _Vector_const_iterator& operator++() noexcept {
#if _ITERATOR_DEBUG_LEVEL != 0
const auto _Mycont = static_cast<const _Myvec*>(this->_Getcont());
_STL_VERIFY(_Ptr, “can’t increment value-initialized vector iterator”);
_STL_VERIFY(_Ptr < _Mycont->_Mylast, “can’t increment vector iterator past end”);
#endif // _ITERATOR_DEBUG_LEVEL != 0
++_Ptr;
return *this;
}
I imagine this has something to do with my CheckCollision method and the fact that my program still tried checking for bricks once they get deleted. I am at a loss as to how to update my CheckCollision method to stop checking for bricks once they get deleted and could use some help.
void Game::CheckCollision()
{
iter = wall.begin();
// TODO #4 – Update collision to check all bricks
for (iter; iter != wall.end(); iter++)
{
if (iter[0].Contains(ball.x_position + ball.x_velocity, ball.y_position + ball.y_velocity) && iter[0].color != Black)
{
iter[0].color = ConsoleColor(iter[0].color – 1);
ball.y_velocity *= -1;
}
// TODO #5 – If the ball hits the same brick 3 times (color == black), remove it from the vector
else if (iter[0].color == Black)
{
wall.erase(iter);
}
}
if (wall.size() == 0)
{
ball.x_velocity = 0;
ball.y_velocity = 0;
system(“cls”);
std::cout << “\n\n\n\n\n\t\t\t\tVictory, You Win! =D” << std::endl;
std::cout << “\t\t\t\tEnter ‘R’ to reset” << std::endl;
std::cin.get();
}
if (paddle.Contains(ball.x_position + ball.x_velocity, ball.y_velocity + ball.y_position))
{
ball.y_velocity *= -1;
}
// TODO #7 – If ball touches bottom of window, pause ball and display defeat text with R to reset
if (ball.moving && ball.y_position > paddle.y_position)
{
ball.x_velocity = 0;
ball.y_velocity = 0;
system(“cls”);
std::cout << “\n\n\n\n\n\t\t\t\tDefeat, You Lose! D=” << std::endl;
std::cout << “\t\t\t\tEnter ‘R’ to reset” << std::endl;
std::cin.get();
}
}