用 Pygame 实现 15 puzzle
基于Tkinter版本,借助AI工具Trae将15puzzle移植为Pygame实现,调整界面与交互细节后完成代码编写,涵盖棋盘生成、随机打乱、点击移动及胜利判断等核心功能。
背景
在之前用 Tkinter 实现简单 15 puzzle 的文章中,我们完成了一个基本版本。但如果换成 Pygame 来做,界面显然可以做得更漂亮。于是决定在那篇基础上,用 Pygame 重新实现一次 15 puzzle。
正文
代码
关于 15 puzzle 的基本介绍和需要解决的问题,在之前那篇 Tkinter 版本的文章中已经详细说明,这里不再重复。对于 Pygame,刚开始接触,了解还比较有限,再加上当下 AI 工具的能力已经非常强大,所以决定先借助 trae 来完成从 Tkinter 到 Pygame 的转化,而自己只需要在生成的代码基础上做调整就好了。转化的过程如下图所示(trae 的回答内容有点长,下图只截取了一部分内容):
转化后的代码虽然不是百分之百准确,但质量已经相当高。在此基础上再调整了一些细节,最终代码如下:
复制代码import pygame
import randomclass FifteenPuzzle:
CELL_SIZE = 100
CELL_GAP = 5
N = 4
WINDOW_SIZE = N * CELL_SIZE + (N + 1) * CELL_GAP + 150
FONT_SIZE = 50 WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)
BLUE = (100, 149, 237)
GREEN = (60, 179, 113)
DARK_BLUE = (70, 130, 180) VALUE_FOR_EMPTY_POS = N * N def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((self.WINDOW_SIZE, self.WINDOW_SIZE))
pygame.display.set_caption("15 Puzzle")
self.clock = pygame.time.Clock()
self.font = pygame.font.Font(None, self.FONT_SIZE)
self.button_font = pygame.font.Font(None, 36) self.board = []
self.empty_pos = (self.N - 1, self.N - 1)
self.click_cnt = 0
self.game_won = False self.new_game_rect = pygame.Rect(
self.WINDOW_SIZE // 2 - 80,
self.WINDOW_SIZE - 60,
160,
40
) self.create_board()
self.shuffle_board() def create_board(self):
self.board = []
for row in range(self.N):
self.board.append([])
for col in range(self.N):
value = row * self.N + col + 1
self.board[row].append(value)
def is_inside_board(self, pos):
row, col = pos
return 0 <= row < self.N and 0 <= col < self.N def shuffle_board(self):
while True:
for _ in range(100):
row, col = self.empty_pos
candidates = [(row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1)]
while True:
candidate = random.choice(candidates)
if self.is_inside_board(candidate):
break
r, c = candidate
self.board[self.empty_pos[0]][self.empty_pos[1]] = self.board[r][c]
self.board[r][c] = self.VALUE_FOR_EMPTY_POS
self.empty_pos = candidate
if not self.all_at_original_position():
break def all_at_original_position(self):
for row in range(self.N):
for col in range(self.N):
target = row * self.N + col + 1
if self.board[row][col] != target:
return False
return True def get_cell_rect(self, row, col):
x = self.CELL_GAP + col * (self.CELL_SIZE + self.CELL_GAP)
y = self.CELL_GAP + row * (self.CELL_SIZE + self.CELL_GAP)
return pygame.Rect(x, y, self.CELL_SIZE, self.CELL_SIZE) def draw_cell(self, row, col, color, text_color=BLACK):
rect = self.get_cell_rect(row, col)
pygame.draw.rect(self.screen, color, rect, border_radius=8)
if (row, col) != self.empty_pos:
text = self.font.render(str(self.board[row][col]), True, text_color)
text_rect = text.get_rect(center=rect.center)
self.screen.blit(text, text_rect) def draw_button(self, text, rect, color, hover_color):
mouse_pos = pygame.mouse.get_pos()
if rect.collidepoint(mouse_pos):
pygame.draw.rect(self.screen, hover_color, rect, border_radius=8)
else:
pygame.draw.rect(self.screen, color, rect, border_radius=8)
text_surf = self.button_font.render(text, True, self.WHITE)
text_rect = text_surf.get_rect(center=rect.center)
self.screen.blit(text_surf, text_rect) def draw(self):
self.screen.fill(self.GRAY) for row in range(self.N):
for col in range(self.N):
if self.game_won:
self.draw_cell(row, col, self.GREEN)
elif (row, col) == self.empty_pos:
self.draw_cell(row, col, self.WHITE)
else:
self.draw_cell(row, col, self.BLUE) if self.game_won:
msg = f"You won after {self.click_cnt} clicks!"
else:
msg = f"Clicks: {self.click_cnt}"
click_text = self.button_font.render(msg, True, self.BLACK)
click_rect = click_text.get_rect(center=(self.WINDOW_SIZE // 2, self.WINDOW_SIZE - 105))
self.screen.blit(click_text, click_rect) self.draw_button("New Game", self.new_game_rect, self.BLUE, self.DARK_BLUE) pygame.display.flip() def handle_click(self, pos):
if self.new_game_rect.collidepoint(pos):
self.create_board()
self.shuffle_board()
self.click_cnt = 0
self.game_won = False
return if self.game_won:
return for row in range(self.N):
for col in range(self.N):
if self.get_cell_rect(row, col).collidepoint(pos):
row_diff = abs(row - self.empty_pos[0])
col_diff = abs(col - self.empty_pos[1])
if (row_diff == 1 and col_diff == 0) or (col_diff == 1 and row_diff == 0):
self.board[self.empty_pos[0]][self.empty_pos[1]] = self.board[row][col]
self.board[row][col] = self.VALUE_FOR_EMPTY_POS
self.empty_pos = (row, col)
self.click_cnt += 1
if self.all_at_original_position():
self.game_won = True
break def run(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
self.handle_click(event.pos) self.draw()
self.clock.tick(60) pygame.quit()if __name__ == "__main__":
game = FifteenPuzzle()
game.run()
运行效果
将完整的代码保存为 fifteen.py,然后在终端中执行:
复制代码python3 fifteen.py
运行效果如下图所示(在自己电脑上运行得到的开局很可能与图中不同):
此时点击空格旁边的 1、7、13 中的任意一个数字,就会发生交换。例如点击 1:
可以看到“空位置”和 1 互换了位置。
实际操作中,玩了一会儿就得到了预期的胜利局面——一共用了 104 次有效点击:
关于使用人工智能的思考
如果程序中有很大比例是用 AI 生成的,自己还能有进步吗?不妨换个角度看:对于 15 puzzle 这个游戏,在之前写 Tkinter 版本时,已经思考并解决了其中的关键问题:
- 整体布局
- 如何生成最终局面?
- 如何生成随机开局?
- 如何交换两个相邻的格子?
借助 AI 的主要目的,是不想在 Pygame 的入门和配置细节上耗费太多时间。在这个前提下,用 AI 辅助写程序——只要核心逻辑和算法还是自己独立实现——完全没有问题,而且依然能够从中获得进步。
参考资料
- TkDocs tutorial 中的
- A First (Real) Example
- Tk Concepts
- Basic Widgets
- 15 puzzle(Wolfram 中关于 15 puzzle 的介绍)
- 用 Tkinter 实现简单的 15 puzzle
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















