所以我正在尝试学习使用 pygame 模块和来自 javascript 背景的 python 制作游戏,我希望能够使用多个脚本构建一个程序。所以我尝试加载另一个脚本并使用它的一个函数以及在该脚本中声明的变量。我想要做的是从另一个脚本调用“更新”功能,但使用在这个脚本中声明的变量。有什么建议么?
编辑:好的,所以我显然没有很好地澄清我的问题。导入脚本不是我的问题,我可以让它很好地导入。我遇到的麻烦是,在我导入它之后,我需要能够从使用此脚本中的变量的主脚本中调用此脚本中的一个函数。
现在发生的事情是我在这个脚本中调用了更新函数,它给了我一个错误,说变量“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)
import pygame, sys, time, random
from pygame.locals import *
import animationScript
# Set up pygame
pygame.init()
mainClock = pygame.time.Clock()
# Set up window
screenW = 400
screenH = 400
windowSurface = pygame.display.set_mode((screenW, screenH), 0, 32)
pygame.display.set_caption('Sprites and sound')
# Set up the colors
black = (0,0,200)
# Set up music
pygame.mixer.music.load('testmidi.mid')
#pygame.mixer.music.play(-1,0.0)
# Run the game loop
while True:
# Check for the QUIT event
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
# Draw the background onto the surface
windowSurface.fill(black)
# Draw Player
animationScript.Update()
# Draw the window onto the screen
pygame.display.update()
mainClock.tick(40)