Pygame初学者程序,屏幕未定义

2024-10-02 20:43:52 发布

您现在位置:Python中文网/ 问答频道 /正文

AMOUNT = 1
x = 175
y = 175

def main():
    screen = pygame.display.set_mode((600,600))
    screen.fill( (251,251,251) )
    BoxAmountCalc(humaninput)
    DrawBoxCalc()
    pygame.display.flip()

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                return

def BoxAmountCalc(x):
    x = (2**humaninput) * (2**humaninput)
    size = 600/x
    return size
def DrawBoxCalc():
    while True:
        pygame.draw.rect(screen,(0,0,0), (x,y,size,size))
        AMOUNT += 1
        x = x + size
        x = y + size
        pygame.display.flip()
        if AMOUNT > humaninput:
            break

我省略了代码的一些部分,一些变量定义,但是当我尝试运行这段代码时,它会给我一个错误,说“screen”没有定义。你知道吗

这是因为我需要将它定义为函数的一个参数,然后将它传递给函数,还是我在这里完全遗漏了什么?你知道吗

感谢您的关注,我很抱歉有一个非常初级的问题。你知道吗


Tags: eventtruesizeif定义defdisplayamount
1条回答
网友
1楼 · 发布于 2024-10-02 20:43:52

Is this because I need it to be defined as a parameter for the function and then pass it into the function.

是的。一旦函数完成执行,其中创建的变量就会被销毁。举个例子:

def go():
    x = 10

go()
print(x)

 output: 
Traceback (most recent call last):
  File "1.py", line 5, in <module>
    print(x)
NameError: name 'x' is not defined

同样的道理:

def go():
    x = 10


def stay():
    print(x) 

go()
stay()

 output: 
 File "1.py", line 9, in <module>
    stay()
  File "1.py", line 6, in stay
    print(x) 
NameError: name 'x' is not defined

但是:

x = 10

def go():
    print(x)

go()

 output: 
10

更好的是:

def go(z):
    print(z)

x = 10
go(x)

 output: 
10

尽量保持函数的自包含性,这意味着它们应该接受一些输入并生成一些输出,而不使用函数外的变量。你知道吗

在代码中,可以执行以下操作:

DrawBoxCalc(screen)def DrawBoxCalc(screen)

但是你也对humaninput有问题。我会尝试将DrawBoxCalc定义为DrawBoxCalc(humaninput,screen),并用这两个参数调用它。这意味着您必须将main定义为main(humaninput)。你知道吗

此外,函数名应该以小写字母开头,python使用所谓的snake大小写作为小写名称,因此draw_box_calc,类名应该以大写字母开头,并且可以使用camel大小写:class MyBox。你知道吗

相关问题 更多 >