【问题标题】:Why is my group list only rendering 1 sprite at a time?为什么我的组列表一次只渲染 1 个精灵?
【发布时间】:2023-03-30 21:49:02
【问题描述】:

我最近观看了迈克的太空入侵者视频,我认为组列表很有趣。我试图用它制作一个粒子列表。它一直有效,直到颗粒落到底部,我在回收它们时遇到了麻烦。它不会渲染所有东西,只渲染一个立方体。

import pygame
import random
pygame.init()
win_height=600
win_width=800
win=pygame.display.set_mode((win_width,win_height))
pygame.display.set_caption("List practice")
white=(255,255,255)
black=(0,0,0)
clock=pygame.time.Clock()

class particle_class(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image=pygame.Surface((25,25))
        self.image.fill(white)
        self.rect=self.image.get_rect()
        self.speed=0
    def update(self):
        self.rect.y+=self.speed
        
particles=pygame.sprite.Group()

for i in range(100):
    particle=particle_class()
    particle.speed=random.randrange(5,11)
    particle.rect.y=0
    particle.rect.x=random.randrange(0,win_width+1)
    particles.add(particle)

while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
    win.fill(black)
    particles.update()
    particles.draw(win)
    pygame.display.update()
    for i in particles:
        if particle.rect.y>win_height:
            particle.rect.y=0

【问题讨论】:

    标签: python list pygame sprite render


    【解决方案1】:

    您想遍历particles 的列表。 for 循环在列表中的每个项目(可迭代)上运行,并允许您访问列表中的当前项目。如果你做for i in particles:i 是列表的一个元素。 i 只是引用列表中当前项目的变量的名称。你可以在这个地方使用任何你想要的名字(iparticlehugo,...)。您只需要在循环中使用相同的名称(变量)即可访问该项目。见for statements

    要么

    for i in particles:
       if i.rect.y > win_height:
           i.rect.y = 0
    

    for particle in particles:
        if particle.rect.y > win_height:
            particle.rect.y = 0
    

    【讨论】:

    • 那么 for 后面的词是否必须是用于包含该类的同一个变量?
    • @ree for 后面的标识符就是变量名。它可以是任何名称。例如for hugo in particles:if hugo.rect.y > .....。使用此变量,您可以访问列表的当前元素。
    • 这有帮助,我知道它说要避免感谢 cmets,但无论如何都要感谢。
    • @ree 谢谢。不客气。 (我不认为礼貌是错误的)
    猜你喜欢
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 2021-12-06
    • 2015-02-05
    • 2017-11-22
    • 1970-01-01
    相关资源
    最近更新 更多