pygame(十五)拼图游戏
前情提要
本节提要
内容详情
截取目标矩形图片
上节课,我们学到一个裁剪图片的方法: chop()
这个方法是将原截掉一个十字形的位置,将剩下的四个矩形合并成一个新的矩形图片.这样非常不利于我们截取图片.
因此,我们将这个方法进行改进,变成截取矩形位置的图片的方法rect_chop()
代码
def rect_chop(img:pygame.Surface, rect:pygame.Rect):
'''截取指定位置的图形'''
result_surface = pygame.transform.chop(img, (0, 0, rect.left, rect.top))
rect = pygame.Rect(0, 0, rect.width, rect.height)
result_surface = pygame.transform.chop(result_surface, (rect.width, rect.height, result_surface.get_width(), result_surface.get_height()))
return result_surface
代码解析
根据我们chop()方法的逻辑,任何的图片,都是裁掉一个十字形的内容
因此,根据这个逻辑,我们先裁掉上边与左边
result_surface = pygame.transform.chop(img, (0, 0, rect.left, rect.top))
再将裁取的图片,再裁掉右边与下边
result_surface = pygame.transform.chop(result_surface, (rect.width, rect.height, result_surface.get_width(), result_surface.get_height()))
生成子图片
将一个游戏图片,截成九个子图片
代码
def creat_imgs(image):
imgs = []
pos_rects = []
for i in range(3):
for j in r