Python 数独游戏实战:用面向对象思想重构游戏代码
·
Python 数独游戏面向对象重构实战
下面是用面向对象思想重构数独游戏的完整实现,包含核心类设计和游戏逻辑:
1. 核心类设计
class SudokuCell:
"""表示单个数独单元格"""
def __init__(self, row, col, value=0):
self.row = row
self.col = col
self.value = value # 0 表示空单元格
self.editable = (value == 0) # 初始值是否可修改
def set_value(self, value):
"""设置单元格值(仅当可编辑时)"""
if self.editable:
self.value = value
class SudokuBoard:
"""表示整个数独棋盘"""
def __init__(self, initial_grid):
# 初始化9x9棋盘
self.cells = [
[SudokuCell(i, j, initial_grid[i][j])
for j in range(9)]
for i in range(9)
]
def get_cell(self, row, col):
"""获取指定位置单元格"""
return self.cells[row][col]
def is_valid_move(self, row, col, value):
"""验证移动是否合法"""
# 检查行
if any(self.cells[row][j].value == value for j in range(9)):
return False
# 检查列
if any(self.cells[i][col].value == value for i in range(9)):
return False
# 检查3x3宫格
box_row, box_col = row // 3 * 3, col // 3 * 3
for i in range(3):
for j in range(3):
if self.cells[box_row + i][box_col + j].value == value:
return False
return True
def is_solved(self):
"""检查是否完成游戏"""
for row in self.cells:
if any(cell.value == 0 for cell in row):
return False
return True
class SudokuGame:
"""游戏主控制器"""
def __init__(self, puzzle):
self.board = SudokuBoard(puzzle)
self.moves = [] # 记录操作历史
def make_move(self, row, col, value):
"""玩家移动操作"""
cell = self.board.get_cell(row, col)
if not cell.editable:
return False
if self.board.is_valid_move(row, col, value):
self.moves.append((row, col, cell.value)) # 保存历史
cell.set_value(value)
return True
return False
def undo_move(self):
"""撤销上一步操作"""
if self.moves:
row, col, prev_value = self.moves.pop()
self.board.get_cell(row, col).set_value(prev_value)
return True
return False
def check_win(self):
"""检查胜利条件"""
return self.board.is_solved()
2. 游戏初始化示例
# 示例数独谜题(0表示空格)
sample_puzzle = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
# 初始化游戏
game = SudokuGame(sample_puzzle)
3. 游戏操作示例
# 玩家在(0,2)位置填入4(合法移动)
game.make_move(0, 2, 4) # 返回True
# 玩家在(0,3)位置填入4(非法移动,同一行已有4)
game.make_move(0, 3, 4) # 返回False
# 撤销操作
game.undo_move() # 撤销(0,2)位置的移动
# 检查游戏状态
print("游戏完成:", game.check_win()) # 输出False
4. 面向对象设计优势
-
封装性:
SudokuCell封装单元格状态SudokuBoard封装棋盘验证逻辑SudokuGame封装游戏流程控制
-
可扩展性:
- 轻松添加新功能(如提示系统)
- 支持不同难度谜题生成器
- 可集成GUI界面而不修改核心逻辑
-
可维护性:
- 各模块职责清晰
- 修改棋盘逻辑不影响游戏控制
- 单元测试可针对每个类单独进行
5. 进阶扩展建议
class SudokuGenerator:
"""数独谜题生成器(策略模式实现)"""
def generate_puzzle(self, difficulty):
# 实现不同难度谜题生成算法
pass
class HintSystem:
"""提示系统"""
def __init__(self, game):
self.game = game
def get_hint(self):
# 分析当前棋盘提供提示
pass
重构要点总结:
- 将游戏元素抽象为独立对象(单元格/棋盘/游戏)
- 每个类封装自身状态和行为
- 通过方法调用实现交互(避免直接操作数据)
- 保留操作历史支持撤销功能
- 验证逻辑集中在棋盘类中维护
这种设计使代码结构更清晰,功能扩展更灵活,符合面向对象设计的SOLID原则。
更多推荐



所有评论(0)