微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在python的列表中创建无限对象

如何解决如何在python的列表中创建无限对象

我正在 pygame 中制作一个游戏,我希望橡子从天而降。

class Acorn:
    def __init__(self):
        self.x  = random.randrange(0,450)
        self.y = 0
        self.image = pygame.image.load("Images/acorn.png")

    def create(self,screen):
        screen.blit(self.image,(self.x,self.y))
        self.y += 1

acorns.append(Acorn)

在我的游戏循环中,我尝试创建多个橡子

for x in acorns:
    x.create(screen,screen)
    acorns.append(Acorn)

解决方法

您必须创建 Acorn 类的 Instance Objects

acron = Acron()

在随机位置一个接一个地创建 acorns,延迟一个时间间隔。使用 pygame.time.get_ticks() 测量时间并计算必须生成下一个对象的时间:

acorn_image = pygame.image.load("Images/acorn.png")

class Acorn:
    def __init__(self):
        self.x  = random.randrange(0,450)
        self.y = 0
        self.image = acorn_image 

    def move(self):
        self.y += 1

    def draw(self,screen):
        screen.blit(self.image,(self.x,self.y))
next_acorn_time = 0
acorn_time_interval = 100 # 100 milliseconds = 0.1 seconds

# applicaiton loop
clock = pygame.time.Clock()
run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    current_time = pygame.time.get_ticks()
    if current_time >= next_acorn_time:
        next_acorn_time += acorn_time_interval 
        new_acorn = Acorn() 
        acorns.append(new_acorn)

    # [...]

    for acron in acorns[:]:
        acron.move()
        if acron.y > screen.get_height():
            acorns.remove(acorn)

    for acron in acorns[:]:
        acron.draw(screen)
        if acron.y > screen.get_height():
            acorns.remove(acorn)
    pygame.display.flip()
,

这里我们无限地将一个对象附加到一个列表中。然后我们为列表中的每个对象调用 create 函数。

class Acorn:
    def __init__(self):
        self.x  = random.randrange(0,450)
        self.y = 0
        self.image = pygame.image.load("Images/acorn.png")

    def create(self,self.y))
        self.y += 1
Acorns = []
while True:
   Acorns.append(Acorn(args))
   for ac in Acorns:
       ac.create(screen)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。