Python-can';t使变量中的数字更高

Python-can';t使变量中的数字更高,python,variables,pong,Python,Variables,Pong,我正在用python编程游戏pong,我不希望球每次反弹都更快。所以我试着加上 global SPEED SPEED + 25 进入一个更高速度的功能,每当球从球棒反弹时就会触发。 游戏代码的简短版本如下: ... BALL_SIZE = 20 BAT_WIDTH = 10 BAT_HEIGHT = 100 SPEED = 250 # (in pixels per second) BAT_SPEED = SPEED * 1.5 # (in pixels per second) ...

我正在用python编程游戏pong,我不希望球每次反弹都更快。所以我试着加上

global SPEED
SPEED + 25
进入一个更高速度的功能,每当球从球棒反弹时就会触发。 游戏代码的简短版本如下:

...

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

...


。。。
钢球尺寸=20
BAT_宽度=10
蝙蝠高度=100
速度=250#(以像素每秒为单位)
BAT_速度=速度*1.5(以像素每秒为单位)
...
def较高_速度(速度,x):
x=25
全球速度
速度+x
回程速度
#向左弹跳
如果球的位置[0]<球拍宽度+球的大小/2:
如果bat_最小值宽度7777-(球拍宽度+球的大小/2):
如果bat_最小值
请帮忙。感谢您的时间:)。

这里有几件事:

首先,值没有被更改,因为它在第一个位置没有赋值,您的函数应该如下所示:

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

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

speed = higher_speed(speed)
其次,如果要在函数开头覆盖
x
,并将
SPEED
用作全局,为什么要传递它

def higher_speed():
    global SPEED
    SPEED += 25
第三,根据Python的标准,大写的单词只用于常量,这对于速度的提高是一个很好的用途,所以它应该是这样的:

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

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

speed = higher_speed(speed)
最后,一般来说,使用全局变量是一个坏主意,你可以检查或谷歌它,所以尽量避免它,然后它应该是这样的:

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

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

speed = higher_speed(speed)
或者您可以将此设置为内联:

speed += SPEED_INCREASE

我希望有帮助

您可能是指
SPEED+=x
,而不是
SPEED+x
——这没有任何作用。