I'm implementing part 9 of 10 in pset 4 when I found a flaw in my code. First, pseudo-code:

If ball is below the screen

  • remove ball
  • Refer to initBall function to create new ball which is centered.
  • reduce lives by 1

The issue is that my code seems to think the ball stays at the bottom of the window. A new ball centres, but my lives go to 0 and the code exits -- It WaitsFor Click and Exits.

I don't know how to gdb it because it requires switching from the breakout window to the terminal.

Feel free to delete this if 'unreasonable':

while(lives > 0)

   detect mouse events...
   move ball

    if(getY(ball) >= getHeight(window))
                    removeGWindow(window, ball); 
                    GOval ball = initBall(window);
                    printf("%d", lives);   

Thank you so so much, hope it's clear, spent all day on this! Guy

2 Answers 2


The key solution to this is to reuse the variable that's named ball and declared in main() (before the loop).

What you're basically doing here is that you're creating a new variable with the same name as the original variable (i.e., ball) within the body of the if statement. This variable shadows the original one and goes out of scope as soon as you exit the body of the if statement. And that's why you're not getting what you expect.

The solution is simply to remove the word GOval the statement

GOval ball = initBall(window);

An alternative method to do the same would be to avoid deletion and addition of new objects altogether. You can simply reduce the lives by one and set the location of the ball to the center of the screen. Also you should take into consideration the width of the ball in your "if" condition as that is the correct way according to the cs50 team's implementation of breakout. With your code the ball will go to the bottom of the screen and disappear from view before the game stops which should not actually happen.

You can try something like this,

if (getY(ball) + getHeight(ball) >= getHeight(window))
    setLocation(ball, (WIDTH/2)-RADIUS, (HEIGHT/2)-RADIUS);

I hope this helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .