2

我现在遇到的问题是将一堆声音文件作为它们自己的对象加载到 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')

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

谢谢!

4

3 回答 3

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

例如,现在 sound["sound1"] 等工作。

于 2013-03-15T00:51:50.840 回答
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.wavsound8.wav文件命名不同,您只需更改范围和/或字符串格式。

于 2013-03-15T00:52:04.937 回答
1

python中有两种循环,for循环和while循环。for 循环用于重复某件事 n 次。while循环用于重复直到发生某些事情。For-loops 对于游戏编程很有用,因为它们经常处理游戏显示的帧。每一帧通过一个循环运行一次。存储 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

于 2013-03-15T06:17:03.780 回答