gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:33 26 4
gpt4 key购买 nike

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

我遗漏了代码的一些部分,一些变量定义,但是当我尝试运行此代码时,它给我一个错误,指出“屏幕”未定义。

这是因为我需要将其定义为函数的参数,然后将其传递给函数,还是我在这里完全遗漏了一些东西?

感谢您的浏览,很抱歉我提出了一个非常初学者的问题。

最佳答案

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

但是您也遇到了人工输入的问题。我会尝试将 DrawBoxCalc 定义为 DrawBoxCalc( humaninput, screen) ,并使用两个参数调用它。这意味着您必须将 main 定义为 main(peopleinput)。

此外,函数名称应以小写字母开头,Python 使用所谓的 Snake_case 表示小写字母,因此 draw_box_calc,类名称应以大写字母开头,并且可以使用驼峰式大小写:class MyBox

关于python - Pygame 初学者程序,屏幕未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com