从draw方法中移除新方块的生成:
class Squares:
def __init__(self, x, y, width):
self.x = x
self.y = y
self.width = width
self.height = width
def draw(self):
pygame.draw.rect(window, (255, 0, 0), (self.x, self.y, self.width, self.height))
您必须在应用程序循环的每一帧中重新绘制整个场景。绘制方块前清除显示,然后绘制列表中的所有方块,最后更新显示:
while run:
# [...]
a = Squares(random.choice(x_axis), random.choice(y_axis),
random.choice(sq_width), random.choice(sq_width))
sq_display.append(a)
if len(sq_display) > 3:
sq_display.remove(sq_display[0])
window.fill(0)
for r in sq_display:
r.draw()
pygame.display.flip()
如果您想保持应用程序响应,那么您不能将应用程序循环延迟time.sleep。使用pygame.time.get_ticks() 获取自pygame.init() 以来的当前毫秒数,并在经过随机时间后创建一个新正方形:
next_square_time = 0
while run:
# [...]
current_time = pygame.time.get_ticks()
if next_square_time <= current_time:
next_square_time += random.choice(sec) * 1000
# create new square
# [...]
小例子:
import pygame
import random
pygame.init()
x_axis = [500, 650, 350, 400]
y_axis = [100, 50, 450, 300]
sq_width = [10, 15, 20, 25, 30]
sec = [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
sq_display = []
class Squares:
def __init__(self, x, y, width):
self.x = x
self.y = y
self.width = width
self.height = width
def draw(self):
pygame.draw.rect(window, (255, 0, 0), (self.x, self.y, self.width, self.height))
window = pygame.display.set_mode((800, 600))
next_square_time = 0
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
current_time = pygame.time.get_ticks()
if next_square_time <= current_time:
next_square_time += random.choice(sec) * 1000
a = Squares(random.choice(x_axis), random.choice(y_axis), random.choice(sq_width))
sq_display.append(a)
if len(sq_display) > 3:
sq_display.remove(sq_display[0])
window.fill(0)
for r in sq_display:
r.draw()
pygame.display.flip()