I get a segmentation fault after x times i "die" (it varies) and if I decrement the lives each time the ball hits the bottom i get a segmentation fault after 1 time. It's very annoying and I can't find the error after trying multiple things. Can someone with a fresh mind take a look at my code and point out what I overlooked? Thank you.
Here is the full source code - this is my main function:
int main(void)
{
// seed pseudorandom number generator
srand48(time(NULL));
// instantiate window
GWindow window = newGWindow(WIDTH, HEIGHT);
// instantiate bricks
initBricks(window);
// instantiate ball, centered in middle of window
GOval ball = initBall(window);
// instantiate paddle, centered at bottom of window
GRect paddle = initPaddle(window);
// instantiate scoreboard, centered in middle of window, just above ball
GLabel label = initScoreboard(window);
// number of bricks initially
int bricks = COLS * ROWS;
// number of lives initially
int lives = 3;
// number of points initially
int points = 0;
// inital velocity
double velocityX = drand48() * 3.25;
double velocityY = drand48() * 3.25;
// middle/place of ball when started
double x = (getWidth(window) - getWidth(ball)) / 2;
double y = (getHeight(window) - getHeight(ball)) / 2;
// keep playing until game over
while (lives > 0 && bricks > 0)
{
// DONE
GEvent event = getNextEvent(MOUSE_EVENT);
move(ball, velocityX, velocityY);
// update points
char s[3];
sprintf(s, "%i", points);
setLabel(label, s);
// bounce off right edge of window
if (getX(ball) + getWidth(ball) >= getWidth(window))
{
velocityX = -velocityX;
}
// bounce off left edge of window
else if (getX(ball) <= 0)
{
velocityX = -velocityX;
}
// bounce off bottom edge of window
if (getY(ball) + getWidth(ball) >= getHeight(window))
{
GEvent click = getNextEvent(MOUSE_EVENT);
if (event != NULL)
{
if (getEventType(click) == MOUSE_CLICKED)
{
setLocation(ball, x, y);
//lives--;
}
}
}
// bounce off top edge of window
else if (getY(ball) <= 0)
{
velocityY = -velocityY;
}
// detects a collison and stores it as object
GObject object = detectCollision(window, ball);
// bounce of paddle
if (object == paddle)
{
velocityY = -velocityY;
}
if (object == NULL)
{
// Do nothing
}
else if (strcmp(getType(object), "GRect") == 0)
{
if (object != paddle)
{
removeGWindow(window, object);
velocityY = -velocityY;
points++;
}
}
if (event != NULL)
{
if (getEventType(event) == MOUSE_MOVED)
{
double x = getX(event) - getWidth(paddle) / 2;
double y = (getHeight(window) - getHeight(paddle)) / 1.25;
setLocation(paddle, x, y);
}
}
pause(10);
}
// wait for click before exiting
waitForClick();
// game over
closeGWindow(window);
return 0;
}