因此,我正在尝试使用pygame模块学习用python制作游戏,我希望能够从javascript背景中学习如何使用多个脚本来构建程序。所以我尝试加载另一个脚本并使用它的一个函数以及该脚本中声明的变量。我想做的是从另一个脚本调用“update”函数,但是使用这个脚本中声明的变量。有什么建议吗?在
编辑: 好吧,所以我显然没有很好地澄清我的问题。导入脚本不是我的问题,我可以让它很好地导入。我遇到的问题是,在我导入它之后,我需要能够从这个脚本调用一个函数,而这个脚本使用这个脚本中的变量。在
现在发生的是,我在这个脚本中调用update函数,它给我一个错误,说明变量“animTimer”在声明之前被调用。这就是我需要解决的问题。在
import pygame, sys, time, random
from pygame.locals import *
# Create animation class
class animation2D:
"a class for creating animations"
frames = []
speed = 3
cFrame = 0
player = pygame.Rect(300, 100, 40, 40)
playerImg1 = pygame.image.load('player1.png')
playerImgS = pygame.transform.scale(playerImg1, (40,40))
playerImg2 = pygame.image.load('player2.png')
playerImg3 = pygame.image.load('player3.png')
playerImg4 = pygame.image.load('player4.png')
playerImg5 = pygame.image.load('player5.png')
playerImg6 = pygame.image.load('player6.png')
playerAnim = animation2D
playerAnim.frames = [playerImg1, playerImg2, playerImg3, playerImg4, playerImg5, playerImg6]
animTimer = 0
print(animTimer)
def Update():
# Draw Player
if animTimer < playerAnim.speed:
animTimer += 1
else:
animTimer = 0
playerImgS = pygame.transform.scale((playerAnim.frames[playerAnim.cFrame]), (40,40))
if playerAnim.cFrame < len(playerAnim.frames)-1:
playerAnim.cFrame += 1
else:
playerAnim.cFrame = 0
windowSurface.blit(playerImgS, player)
编辑:在我看来,你好像在做这样的事情:
当您应该传入参数时,如下所示:
^{pr2}$Python不喜欢把全局名称空间搞得一团糟。这是件好事,我保证!确保将变量分配给函数的结果,就像我在
a = inc(a)
行中所做的那样。否则,您将不得不处理全局变量,这不是很好的实践。在在您的例子中,
Update()
应该接受它想要修改的参数,并返回它们的新值。在您可以^{} 将此模块放入另一个脚本中。这将允许您使用语法访问所有模块级函数、变量等
mymodulename.functionname()
或者
mymodulename.varname
。在如果你想访问一个模块中的类,同样的语法仍然有效!在
mymodulename.classname.classmember
例如:
如果模块不在同一目录中,则需要将要从中导入的目录添加到路径中。不过,我建议暂时将它们放在同一个目录中,因为您似乎正在学习Python。在
可以使用import,但需要将脚本的路径添加到PYTHONPATH环境变量中,或者在导入之前添加一行代码,如下所示:
然后,您可以使用以下方法导入整个模块:
^{pr2}$并引用函数模块功能()或者可以导入特定函数,直接调用函数名:
相关问题 更多 >
编程相关推荐