PyGame 在每个循环中创建精灵的循环不更新

PyGame Loop with sprite creation in each loop not updating

我正在创建一个模拟卢瑟福散射实验的物理模拟。每次循环 运行 时我都试图创建一个 alpha 粒子(精灵)并且我能够创建它(显示在屏幕上)但它不会向前移动,而如果我只创建一个粒子,它工作正常。

我已经附加了精灵的 class 和关于它的创建位置的循环。

循环:

while running:
    clock.tick(20)
    allparticles = pygame.sprite.Group(Particle(speed, bwidthmin, bwidthmax, background))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    allparticles.clear(screen, background)
    nucgroup.draw(screen)
    allparticles.update()
    allparticles.draw(screen)
    pygame.display.flip()

雪碧Class:

class Particle(pygame.sprite.Sprite):
def __init__(self, speed, bwidthmin, bwidthmax, background):
    pygame.sprite.Sprite.__init__(self)
    self.background = background
    self.image = pygame.Surface((16,16))
    self.rect = self.image.get_rect()
    currenty = random.randint(bwidthmin,bwidthmax)
    self.rect.centery = currenty
    self.rect.centerx = 0
    pygame.draw.circle(self.image, yellow, (8,8), 5)

    self.dx=speed
    self.dy = 0
def update(self):
    c1 = (self.rect.centerx,self.rect.centery)
    self.rect.centerx += self.dx
    if self.rect.right >= 570:
        pygame.sprite.Sprite.kill(self)
    pygame.draw.line(self.background, white, c1, (self.rect.centerx,self.rect.centery), 1)

我哪里错了?

我的 tkinter window 也有问题,其中 pygame 嵌入悬挂(按钮未按下,选项卡未更改,在 pygame 停止之前无法执行任何操作).循环 运行ning 是否永远导致这种情况发生?我希望能够在 运行 时间内更新变量以影响模拟,或者这不可能吗?

感谢您的帮助。

一个问题是您每次都在循环中覆盖 allparticles。也许您的意思是继续创建粒子并附加到列表?

试试这个:

allparticles = []
while running:
    clock.tick(20)
    allparticles.append(pygame.sprite.Group(Particle(speed, bwidthmin, bwidthmax, background)))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    for particle in allparticles:  # loop over all particles each time
       particle.clear(screen, background)
       nucgroup.draw(screen)
       particle.update()
       particle.draw(screen)
    pygame.display.flip()