Search code examples
pythonvariablespong

Python - can't make number in variable higher


I'm programming game pong in python and I wan't the ball to be faster everytime it bounces of a bat. So I tried to add

global SPEED
SPEED + 25

into a function higher_speed which will trigger everytime when the ball bounces of the bat. short version of game code here:

...

BALL_SIZE = 20
BAT_WIDTH = 10
BAT_HEIGHT = 100
SPEED = 250  # (in pixels per second)
BAT_SPEED = SPEED * 1.5  # (in pixels per second)

...

def higher_speed(SPEED, x):
    x = 25
    global SPEED
    SPEED + x
    return SPEED

    # bounce left
    if ball_position[0] < BAT_WIDTH + BALL_SIZE / 2:
        if bat_min < bat_position[0] < bat_max:
            # bat bounces ball
            BALL_SPEED[0] = abs(BALL_SPEED[0])
            global SPEED
            higher_speed()
        else:
            # bat hadn't bounced the ball, player loses
            score[1] += 1
            reset()

    # bounce right
    if ball_position[0] > WIDTH7777 - (BAT_WIDTH + BALL_SIZE / 2):
        if bat_min < bat_position[1] < bat_max:
            BALL_SPEED[0] = -abs(BALL_SPEED[0])
            higher_speed()
        else:
            score[0] += 1
            reset()

...


Please help. I appreciate your time :).


Solution

  • Several things here:

    First of all, the value is not being changed because it is not assigned in the first place, your function should look like this:

    def higher_speed(SPEED, x):
        x=25
        global SPEED
        SPEED += x
    

    Second, if you're overwriting x at the beginning of the function and using SPEED as global, why pass it?:

    def higher_speed():
        global SPEED
        SPEED += 25
    

    Third, according to Python's PEP8 standards, capitalized words are only for constants, it would be a good use to the speed increase, so it should look like this:

    SPEED_INCREASE = 25
    
    def higher_speed():
        global speed
        speed += SPEED_INCREASE 
    

    And last, in general is a bad idea using global variables you can check this article or google it, so try to avoid it, then it should look like this:

    def higher_speed(speed):
        return speed+SPEED_INCREASE
    
    speed = higher_speed(speed)
    

    or you could set this inline:

    speed += SPEED_INCREASE
    

    I hope it helped!