Python - 无法使变量中的数字更高

Python - can't make number in variable higher

我正在 python 编写乒乓球游戏,我不希望每次球拍反弹时球都更快。所以我尝试添加

global SPEED
SPEED + 25

到函数 higher_speed 中,每次当球从球棒上弹起时都会触发。 游戏代码的简短版本:

...

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()

...


请帮忙。感谢您的宝贵时间 :).

这里有几件事:

首先,值没有被改变,因为它一开始就没有赋值,你的函数应该是这样的:

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

其次,如果你在函数的开头覆盖 x 并使用 SPEED 作为全局,为什么要传递它?:

def higher_speed():
    global SPEED
    SPEED += 25

第三,根据Python的PEP8标准,大写的单词只用于常量,对提速有好处,所以应该是这样的:

SPEED_INCREASE = 25

def higher_speed():
    global speed
    speed += SPEED_INCREASE 

最后,一般来说使用全局变量是个坏主意你可以检查this article或google它,所以尽量避免它,那么它应该是这样的:

def higher_speed(speed):
    return speed+SPEED_INCREASE

speed = higher_speed(speed)

或者您可以设置为内联:

speed += SPEED_INCREASE

希望对您有所帮助!