如何删除pygame表面?
在下面的代码中,屏幕上并不只显示一个圆圈。 我想解决这个问题,让它看起来只有一个圆圈,而不是在鼠标光标移动的地方留下一个模糊的轨迹。
import pygame,sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,400),0,32)
radius = 25
circle = pygame.Surface([radius*2]*2,SRCALPHA,32)
circle = circle.convert_alpha()
pygame.draw.circle(circle,(25,46,100),[radius]*2,radius)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.blit(circle,(pygame.mouse.get_pos()[0],100))
pygame.display.update()
pygame.time.delay(10)
1 个回答
6
在你重新绘制圆圈之前,必须先把它擦掉。根据你的场景复杂程度,可能需要尝试不同的方法。一般来说,我会有一个“背景”表面,每帧都把它绘制到屏幕上,然后再把精灵或其他表面绘制到它们的新位置上(在Pygame中,绘制操作非常快,所以即使在比较大的屏幕上,我也没有遇到速度问题)。对于你上面的代码,简单的方法就是使用 surface.fill(COLOR)
,其中 COLOR
是你的背景颜色;比如,白色就是 (255,255,255):
# ...
screen = pygame.display.set_mode((640,400),0,32)
backgroundColor = (255,255,255)
# ...
while True:
# ...
screen.fill(backgroundColor)
screen.blit(circle,(pygame.mouse.get_pos()[0],100))
pygame.display.update()
pygame.time.delay(10)
编辑:针对你的评论,实际上可以用更面向对象的方式来做。
你需要有一个与屏幕关联的背景表面(我通常会有一个显示或地图类,具体取决于游戏类型)。然后,把你的对象设置为 pygame.sprite
的子类。这要求你有 self.image
和 self.rect
属性(image 是你的表面,rect 是一个 Pygame.rect,表示位置)。把所有的精灵添加到一个 pygame.group
对象中。现在,每帧你都调用这个组的 draw
方法,然后在更新显示后(也就是用 pygame.display.update()),调用这个组的 clear
方法。这个方法需要你提供目标表面(也就是上面的 screen
)和一个背景图像。
例如,你的主循环可能看起来像这样:
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
circle.rect.center = (pygame.mouse.get_pos()[0],100)
circleGroup.draw(screen)
pygame.display.update()
circleGroup.clear(screen, backgroundSurface)
pygame.time.delay(10)
想了解更多信息,可以查看 文档,了解 Sprite 和 Group 类。