Home > Enterprise >  How to correctly initialize a Boolean as a variable for use as a "switch"
How to correctly initialize a Boolean as a variable for use as a "switch"

Time:05-26

#Bounce bullet when it reaches corners.
def bullet_bounce(rect):
    bottom_corner = False
    if bottom_corner == False:
        rect.y  =5
        if rect.bottom == 400:
            bottom_corner = True
    if bottom_corner == True:
        rect.y -=5
        if rect.top == 0:
            bottom_corner = False

While working with pygame to create Pong I want to make a rectangle bounce every time it reaches the corner of the screen. I came up with this code and it works as intented when I initialize bottom_corner outside the game loop and then run the rest of the code inside the loop. But since it would look much cleaner I want to implement this code inside as a function. The problem is since the function is called inside the loop bottom_corner is initialized as False every time the loop runs which leads to only the first half of the code being iterated. Do you have any recommendations on how to fix this issue?

CodePudding user response:

You should define variable outside function and send to function as parameter and get it back with return

def bullet_bounce(rect, bottom_corner):
    if not bottom_corner:
        rect.y  =5
        if rect.bottom == 400:
            bottom_corner = True
    else:
        rect.y -=5
        if rect.top == 0:
            bottom_corner = False

    return bottom_corner

# --- start program ---

bottom_corner = False

# --- some loop ---

while True:

    bottom_corner = bullet_bounce(rect, bottom_corner)

CodePudding user response:

I am not sure if I understood your question. But I recommend you avoid making equality comparisons between boolean values(True, False) and boolean variables. Instead of saying if bottom_corner == True use if bottom_corner: and else:

And to switch boolean variables you can use the not operator

#Bounce bullet when it reaches corners.
def bullet_bounce(rect):
    if bottom_corner: rec.y -=5 
    else rec.y  = 5
    if (rec.bottom == 400) or (rect.top == 0): 
        # switch it based on previous value
        bottom_corner = not bottom_corner
  • Related