在pygam中加载图像时,使用range的正确方法是什么

2024-09-28 01:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧。。我重写了它,但我还是有问题的随机选择 我明白它想做什么,我真的想要雷达天线选择当精灵离开屏幕时重置,但不是随机的。。。你知道吗

class Planets(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self)
            imageFiles = ["planet_{}.gif".format(num) for num in range (1,4)]
            for files in imageFiles:
                self.image = pygame.image.load(files)    
            self.image.convert()
            self.rect = self.image.get_rect()
            self.x = 700
            self.y = 50
            self.dx = -5

        def update(self):
            self.rect.center = (self.x, self.y)
            self.x += self.dx
            if self.x <= -800:
                self.reset()

        def reset(self):
            self.x = 800
            self.image = random.choice(files)
            self.y = random.randrange(0, screen.get_height())

Tags: inrectimageselfforgetinitdef
2条回答

此代码:

for files in imageFiles:
    self.image = pygame.image.load(files)   

将一个图像加载到self.image,然后依次用其他图像替换它。我不知道你想要什么,但这个循环没有任何用处。你知道吗

这个代码:self.image = random.choice(files)-应该完全失败,因为files在这个函数中不存在。即使它引用了init函数中的files变量,它也只是一个字符串,所以自我形象最终会变成一个字符,而不是一个实际的图像。你知道吗

我会尝试这样的方法(遗漏一些代码):

(in __init__)
self.files = []
for files in imageFiles:
    self.files.append(pygame.image.load(files))
for img in self.files:
    img.convert()
self.reset()

(in reset)
self.image = random.choice(self.files)
self.rect = self.image.get_rect()

我会这么做:

files = ["planet_{}.gif".format(num) for num in range (1,4)]
for filename in files:
    f = open (filename) .... and so on

当你有一张所有图片的列表时

image_to_display = random.choice (image_list)

相关问题 更多 >

    热门问题