【问题标题】:How to create infinite objects in a list in python如何在python的列表中创建无限对象
【发布时间】:2021-04-21 20:58:02
【问题描述】:

我在 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)

【问题讨论】:

  • 多个对象不是无限对象。
  • 怎么了?你有什么需要帮助的?请说明。

标签: python python-3.x pygame


【解决方案1】:

你必须创建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()

【讨论】:

    【解决方案2】:

    这里我们将一个对象无限地附加到一个列表中。然后我们为列表中的每个对象调用 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, screen):
            screen.blit(self.image, (self.x, self.y))
            self.y += 1
    Acorns = []
    while True:
       Acorns.append(Acorn(args))
       for ac in Acorns:
           ac.create(screen)
    

    【讨论】:

      猜你喜欢
      • 2017-09-29
      • 2013-08-27
      • 2022-11-05
      • 2010-09-25
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      相关资源
      最近更新 更多