Python:使用代码编写代码 - 适合初学者

时间:2013-03-15 00:49:18

标签: python pygame getattr

我现在遇到的问题是在Pygame中加载一堆声音文件作为自己的对象。您使用以下语法加载声音:

sound1 = pygame.mixer.Sound('file.wav')

假设我有七个文件,我希望它们已加载并命名为sound1 - sound7。而且我不想单独加载它们。如果我不知道它有缺陷,我会尝试这样的事情:

for i in range(1, 8):
    new = 'sound' + str(i)
    new = pygame.mixer.Sound(str(new) + 'wav')

我如何制作'new'它自己的变量,而不是字符串?我读过有关getattr的内容,但令人困惑。我真的想知道如何使用函数和循环来动态创建代码,但到目前为止,我找不到像我这样的初学者有用的东西。以此为例,是否有人愿意以简单的方式解释在代码中创建代码并将字符串转换为可用变量/对象的方法?

谢谢!

3 个答案:

答案 0 :(得分:6)

sounds = [] # list
for i in range(1, 8):
    sounds.append(pygame.mixer.Sound('sound' + str(i) + 'wav'))

或者

sounds = {} # dictionary
for i in range(1, 8):
    sounds[i] = pygame.mixer.Sound('sound' + str(i) + 'wav')

首先,您似乎使用与列表方法相同的字典方法,例如声音[1]听起来[2]等等,但你也可以这样做:

sounds = {} # dictionary
for i in range(1, 8):
    sounds['sound' + str(i)] = pygame.mixer.Sound('sound' + str(i) + 'wav')

现在声音[“sound1”]等工作,例如。

答案 1 :(得分:1)

您可以使用数组:

sound = []
for i in range(1,8):
    sound.append (pygame.mixer.Sound("sound%d.wav" % i))
# Now use sound[0..6] to reference sound[1..7].wav

这会将文件sound1.wav加载到sound8.wav - 如果您的文件名称不同,则只需更改范围和/或字符串格式。

答案 2 :(得分:1)

python中有2种循环,for循环和while循环。 for循环用于重复多次。 while循环用于重复直到发生某些事情。 For循环对于游戏编程很有用,因为它们经常处理游戏显示的帧。每个帧通过一个循环运行一次。存储for循环的方式是使用列表。以下是您可以熟悉的基本循环示例:

he_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

# this first kind of for-loop goes through a list
for number in the_count:
    print "This is count %d" % number

# same as above
for fruit in fruits:
    print "A fruit of type: %s" % fruit

# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
    print "I got %r" % i

# we can also build lists, first start with an empty one
elements = []

# then use the range function to do 0 to 5 counts
for i in range(0, 6):
    print "Adding %d to the list." % i
    # append is a function that lists understand
    elements.append(i)

# now we can print them out too
for i in elements:
    print "Element was: %d" % i

您可以在此处了解有关python中循环和游戏编程的更多信息: programarcadegames.com/index.php?lang=en&chapter=loops