下面是用python的pygame库实现九宫格拼图游戏,以及添加BFS算法实现自动复原的代码:
import pygame
import random
# 游戏窗口大小
WINDOW_SIZE = WIDTH, HEIGHT = 300, 300
# 行列数
ROWS, COLS = 3, 3
# 方块大小
BLOCK_SIZE = BLOCK_WIDTH, BLOCK_HEIGHT = WIDTH // COLS, HEIGHT // ROWS
# 方块颜色
BLOCK_COLOR = (255, 255, 255)
# 边框颜色
BORDER_COLOR = (0, 0, 0)
# 初始化pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode(WINDOW_SIZE)
# 设置窗口标题
pygame.display.set_caption("九宫格拼图游戏")
# 创建时钟对象,控制游戏循环刷新频率
clock = pygame.time.Clock()
class Block:
def __init__(self, row, col, number):
self.row = row
self.col = col
self.number = number
self.rect = pygame.Rect(col * BLOCK_WIDTH, row * BLOCK_HEIGHT, BLOCK_WIDTH, BLOCK_HEIGHT)
def draw(self):
pygame.draw.rect(window, BLOCK_COLOR, self.rect)
pygame.draw.rect(window, BORDER_COLOR, self.rect, 1)
font = pygame.font.SysFont(None, BLOCK_WIDTH)
text = font.render(str(self.number), True, (0, 0, 0))
text_rect = text.get_rect(center=self.rect.center)
window.blit(text, text_rect)
# 创建九宫格方块对象
blocks = []
for row in range(ROWS):
for col in range(COLS):
if row == ROWS - 1 and col == COLS - 1:
number = None
else:
number = row * COLS + col + 1
block = Block(row, col, number)
blocks.append(block)
def draw_blocks():
window.fill((0, 0, 0))
for block in blocks:
block.draw()
pygame.display.update()
# 随机打乱方块顺序
def shuffle_blocks():
random.shuffle(blocks)
draw_blocks()
# 判断拼图是否完成
def is_finished():
for i, block in enumerate(blocks):
if block.number is not None and block.number != i + 1:
return False
return True
# 拖拽方块
def drag_block(block):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.MOUSEMOTION:
x, y = pygame.mouse.get_pos()
block.rect.x = x - BLOCK_WIDTH // 2
block.rect.y = y - BLOCK_HEIGHT // 2
if event.type == pygame.MOUSEBUTTONUP:
x, y = pygame.mouse.get_pos()
row = y // BLOCK_HEIGHT
col = x // BLOCK_WIDTH
if exchange_block(block, row, col):
return
# 交换方块
def exchange_block(block, row, col):
if row >= 0 and row < ROWS and col >= 0 and col < COLS and not (row == block.row and col == block.col):
target_index = row * COLS + col
empty_index = ROWS * COLS - 1
# 判断目标位置是否为空
if blocks[target_index].number is None:
blocks[target_index].number, block.number = block.number, blocks[target_index].number
blocks[empty_index], blocks[block.row * COLS + block.col] = blocks[block.row * COLS + block.col], blocks[empty_index]
block.row, block.col = row, col
return True
return False
# 使用BFS算法自动复原拼图
def auto_solve():
target_blocks = blocks[:]
shuffle_blocks()
queue = [(blocks, [])]
visited = set()
visited.add(tuple((block.number for block in blocks)))
while queue:
curr_blocks, curr_path = queue.pop(0)
if curr_blocks == target_blocks:
for block, (row, col) in zip(curr_blocks, ((i // COLS, i % COLS) for i in range(ROWS * COLS))):
block.row, block.col = row, col
for i in range(len(curr_path)):
row, col = curr_path[i]
block = curr_blocks[row * COLS + col]
draw_blocks()
pygame.draw.rect(window, (255, 255, 0), block.rect, 1)
pygame.display.update()
pygame.time.wait(500)
exchange_block(block, row + 1, col)
break
empty_index = curr_blocks.index(None)
row, col = divmod(empty_index, COLS)
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dx, dy in directions:
new_row, new_col = row + dx, col + dy
if new_row >= 0 and new_row < ROWS and new_col >= 0 and new_col < COLS and (new_row, new_col) not in curr_path:
new_index = new_row * COLS + new_col
new_blocks = curr_blocks[:]
new_blocks[empty_index], new_blocks[new_index] = new_blocks[new_index], new_blocks[empty_index]
if tuple((block.number for block in new_blocks)) not in visited:
queue.append((new_blocks, curr_path + [(new_row, new_col)]))
visited.add(tuple((block.number for block in new_blocks)))
# 游戏循环
def game_loop():
shuffle_blocks()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
col = x // BLOCK_WIDTH
row = y // BLOCK_HEIGHT
index = row * COLS + col
if blocks[index].number is None:
continue
block = blocks[index]
drag_block(block)
draw_blocks()
if is_finished():
pygame.time.wait(1000)
auto_solve()
draw_blocks()
clock.tick(60)
if __name__ == '__main__':
game_loop()
在上面的代码中,首先定义了Block类表示每个方块,在Block类中包含row、col和number属性,分别表示方块的行号、列号和数字。draw方法用于绘制方块。
然后创建了blocks列表来存储九宫格方块对象,并在shuffle_blocks函数中实现了随机打乱方块顺序的功能。
exchange_block函数用于交换两个方块的位置,drag_block函数用于通过鼠标拖拽方块进行交换。
is_finished函数用于判断拼图是否完成,当所有方块按照从上到下、从左到右的顺序排列时,拼图完成。
auto_solve函数使用BFS算法自动复原拼图,在函数中保存了当前方块列表curr_blocks和当前路径curr_path,使用queue列表存储待遍历的方块组合状态,使用visited集合记录已经遍历的方块组合,通过遍历方块状态的所有可能交换情况,如果遍历到了目标状态,则还原方块到正确位置。
最后,在游戏循环中,通过判断鼠标点击事件,实现了拖拽方块和判断拼图完成的逻辑,同时添加了自动复原的功能。
希望对你有帮助!