问题描述
我想通过单击按钮绘制一个矩形,但问题是每次循环都会更新显示,显示填充了一种颜色 所以矩形只能看到很短的一段时间。 如何解决这个问题。
while not run:
display.fill((130,190,255) )
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_game = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
p_x -= 30
if event.key == pygame.K_p:
p_x += 30
if event.key == pygame.K_g:
pygame.draw.rect(display,(0,0),((p_x + 25),1309,20,30))
解决方法
您必须在应用程序循环中绘制矩形。例如,当按下 g 时,将一个新矩形添加到列表中。在应用程序循环中绘制列表中的每个矩形
rectangles = []
exit_game = False
while not exit_game:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_game = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
p_x -= 30
if event.key == pygame.K_p:
p_x += 30
if event.key == pygame.K_g:
rectangles.append((p_x + 25,1309,20,30))
display.fill((130,190,255))
pygame.draw.rect(display,(0,0),(p_x + 25,30),1)
for rect in rectangles:
pygame.draw.rect(display,rect)
pygame.display.update()