# pygame(十五)拼图游戏

## 内容详情

### 截取目标矩形图片

#### 代码

``````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
``````

#### 代码解析

``````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 range(3):
temp_rect = pygame.Rect(160 * j + 10 * j, 160 * i + 10 * i, 160, 160) # 位置矩形
imgs.append(rect_chop(image, temp_rect)) # 零乱图
temp_rect.move_ip(0, 120)
pos_rects.append(temp_rect)
return pos_rects, imgs

#### 代码解析

`````` temp_rect = pygame.Rect(160 * j + 10 * j, 160 * i + 10 * i, 160, 160)  # 位置矩形
``````

`````` imgs.append(rect_chop(image, temp_rect))  # 零乱图
``````

### 打乱顺序

#### 代码

``````
# 检测生成的随机序列是否有解
def check_can_do():
nums = [x for x in range(1, 9)]
while 1:
count = 0
shuffle(nums)
for i in range(8):
for j in range(i+1, 8):
if nums[j] < nums[i]:
count += 1
if count % 2 == 0:
return nums
``````

### 点击响应

#### 代码

`````` mouse_key = pygame.mouse.get_pressed()
if mouse_key[0]:
mouse_pos = pygame.mouse.get_pos()
for i in range(9):
# 检测鼠标有没有落在矩形内
if pos_list[i].collidepoint(mouse_pos):
# 检测该位置有没有图片
if not pos_list[i][1]:
move(pos_list, i)  # 调用移动方法
``````

#### 代码解析

``````mouse_key = pygame.mouse.get_pressed()
if mouse_key[0]:
``````

``````for i in range(9):
# 检测鼠标有没有落在矩形内
if pos_list[i].collidepoint(mouse_pos):
``````

### 移动方法

#### 代码:

``````def move(i):
l_list = [x for x in range(9) if x % 3 != 0] # 可以左移的位置
if i in l_list:
if pos_list[i - 1][1] == 0: # 可以左移
print(pos_list[i - 1][1], pos_list[i][1])
pos_list[i - 1][1] = pos_list[i][1]
pos_list[i][1] =  0
return
r_list = [x for x in range(9) if x % 3 != 2] # 可能右移0 1 3 4 6 7
if i in r_list:

if pos_list[i + 1][1] == 0: # 可以右移
pos_list[i + 1] [1] = pos_list[i][1]
pos_list[i][1] =  0
return
u_list = [x for x in range(9) if x > 2]  # 可以上移 3,4,5,6,7,8
if i in u_list:
if pos_list[i - 3][1] == 0: # 可以上移
pos_list[i - 3][1] =  pos_list[i][1]
pos_list[i][1] = 0
return
d_list = [x for x in range(9) if x < 6]  # 可以下移 0,1,2,3,4,5
if i in d_list:
if pos_list[i + 3][1] == 0: # 可以下移
pos_list[i + 3] [1] = pos_list[i][1]
pos_list[i][1] = 0
return
``````

### 判断胜利

#### 代码

``````def check_game():
for i in range(9):
if pos_list[i][1] != i:
return False
return True
``````

#### 画图程序

##### 代码
``````def draw():
screen.fill((0, 0, 0))
screen.blit(result_img, (200, 10))
for i in range(9):
nums = pos_list[i][1]
if nums:
screen.blit(img_list[nums], (pos_list[i][0].left, pos_list[i][0].top))
pygame.display.update()
``````