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

2024-06-16 13:17:29 发布

您现在位置: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)

Tags: imageself游戏initdefcreaterandomscreen
2条回答

您必须创建类AcornInstance Objects

acron = Acron()

在随机位置一个接一个地创建acorns,延迟一个时间间隔。使用^{}测量时间并计算必须生成下一个对象的时间:

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

相关问题 更多 >