问题描述
我正在使用 pygame 开展一个学校项目,主要目标是让许多对象随机出现和移动。所以我想让一些粒子产生并随机移动,我想出了这个。
import pygame,random
# -- Variables --
pygame.init()
clock = pygame.time.Clock()
fps_limit = 60.0
resx = 1600
resy = 900
screen = pygame.display.set_mode([resx,resy])
# -- Classes --
class Particule():
def __init__ (self,color,radius):
pygame.sprite.Sprite.__init__(self)
self.color = color
self.radius = radius
self.position_x = resx/2
self.position_y = resy/2
def update(self):
pygame.draw.circle(screen,self.color,(self.position_x,self.position_y),self.radius)
def random_movement(self):
self.position_x += random.randint(0,10)
self.position_y -= random.randint(0,5)
def life(self):
self.radius -= 1
# -- Objects --
particule1 = Particule((255,0),100)
# -- Game loop --
running = True
while running:
clock.tick(fps_limit)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0,0))
particule1.update()
particule1.random_movement()
particule1.life()
pygame.display.set_caption("Baguette")
pygame.display.flip()
pygame.quit()
我尝试了一些 while/if/for 循环,但只出现一个对象,然后没有
解决方法
为粒子创建一个列表:
particles = []
使用 pygame.time.get_ticks()
获取自调用 pygame.init()
以来的毫秒数。定义第一个粒子必须出现的时间。如果时间超过创建一个粒子并设置创建下一个粒子的时间:
next_particle_time = 0
running = True
while running:
# [...]
current_time = pygame.time.get_ticks()
if current_time > next_particle_time:
particles.append(Particule((255,0),100))
next_particle_time = current_time + 200 # 0.2 second interval
在循环中绘制并移动所有粒子:
running = True
while running:
# [...]
for p in particles[:]:
p.update()
p.random_movement()
p.life()
if p.radius < 1:
particles.remove(p)
完整示例
import pygame,random
# -- Variables --
pygame.init()
clock = pygame.time.Clock()
fps_limit = 60.0
resx = 1600
resy = 900
screen = pygame.display.set_mode([resx,resy])
pygame.display.set_caption("Baguette")
# -- Classes --
class Particule():
def __init__ (self,color,radius):
pygame.sprite.Sprite.__init__(self)
self.color = color
self.radius = radius
self.position_x = random.randint(radius,1600-radius)
self.position_y = random.randint(radius,900-radius)
def update(self):
pygame.draw.circle(screen,self.color,(self.position_x,self.position_y),self.radius)
def random_movement(self):
self.position_x += random.randint(-10,10)
self.position_y -= random.randint(-5,5)
def life(self):
self.radius -= 1
# -- Objects --
particles = []
next_particle_time = 0
# -- Game loop --
running = True
while running:
clock.tick(fps_limit)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
current_time = pygame.time.get_ticks()
if current_time > next_particle_time:
particles.append(Particule((255,100))
next_particle_time = current_time + 200 # 0.2 second interval
screen.fill((0,0))
for p in particles[:]:
p.update()
p.random_movement()
p.life()
if p.radius < 1:
particles.remove(p)
print(len(particles))
pygame.display.flip()
pygame.quit()