设计一个4*4的华容道游戏。 每个方块上显示1小块图片,顺序无误后拼成完整图片。写出python代码
时间: 2024-03-06 17:50:21 浏览: 128
好的,以下是一个简单的Python代码实现:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小和标题
WINDOW_SIZE = (400, 400)
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("华容道游戏")
# 加载图片
image = pygame.image.load("image.png")
# 设置方块大小和间距
BLOCK_SIZE = 80
BLOCK_SPACING = 5
# 定义方块类
class Block:
def __init__(self, image, x, y, row, col):
self.image = image
self.x = x
self.y = y
self.row = row
self.col = col
# 绘制方块
def draw(self):
screen.blit(self.image, (self.x, self.y))
# 检查方块是否可以移动
def is_movable(self, empty_block):
if self.row == empty_block.row and abs(self.col - empty_block.col) == 1:
return True
if self.col == empty_block.col and abs(self.row - empty_block.row) == 1:
return True
return False
# 移动方块
def move(self, empty_block):
if self.is_movable(empty_block):
# 交换位置
self.row, empty_block.row = empty_block.row, self.row
self.col, empty_block.col = empty_block.col, self.col
self.x, empty_block.x = empty_block.x, self.x
self.y, empty_block.y = empty_block.y, self.y
# 创建方块数组
blocks = []
for row in range(4):
for col in range(4):
x = col * (BLOCK_SIZE + BLOCK_SPACING)
y = row * (BLOCK_SIZE + BLOCK_SPACING)
# 最后一个方块为空白方块
if row == 3 and col == 3:
blocks.append(Block(None, x, y, row, col))
else:
# 从完整图片中随机选择一小块
sub_image = image.subsurface(pygame.Rect(col * BLOCK_SIZE, row * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
blocks.append(Block(sub_image, x, y, row, col))
# 随机打乱方块顺序
random.shuffle(blocks)
# 获取空白方块
def get_empty_block(blocks):
for block in blocks:
if block.image == None:
return block
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# 获取鼠标点击位置
mouse_pos = pygame.mouse.get_pos()
# 查找被点击的方块
for block in blocks:
if block.image != None and block.x <= mouse_pos[0] < block.x + BLOCK_SIZE and block.y <= mouse_pos[1] < block.y + BLOCK_SIZE:
# 移动方块
empty_block = get_empty_block(blocks)
block.move(empty_block)
break
# 绘制游戏界面
screen.fill((255, 255, 255))
for block in blocks:
block.draw()
pygame.display.update()
# 退出pygame
pygame.quit()
```
请将代码保存为`puzzle.py`文件,并将`image.png`文件(完整图片)放在同一目录下。运行代码后,即可开始游戏。
阅读全文