游戏原理如下(类似拼图游戏):初始状态,移动表中方块的0,每次移动都跟对应数字交换,使其最终能到胜利状态。
初始状态:
1 | 2 | 3 |
---|---|---|
4 | 5 | 6 |
0 | 7 | 8 |
向右移动变成:
1 | 2 | 3 |
---|---|---|
4 | 5 | 6 |
7 | 0 | 8 |
再向右移动变成如下状态,即胜利状态:
1 | 2 | 3 |
---|---|---|
4 | 5 | 6 |
7 | 8 | 0 |
代码如下:
# -*- coding: utf-8 -*-
# !/usr/bin/env python
from enum import Enum
Moving = Enum('Moving', ('LEFT', 'RIGHT', 'UP', 'DOWN'))
# 深度优先搜索
class HuaRongDao(object):
def __init__(self, numlist):
self.numlist = numlist
self.findZero()
self.movelist = [] # 移动步骤
self.winState = '[[1, 2, 3], [4, 5, 6], [7, 8, 0]]' # 正确结果
self.allState = set() # 每一步移动后的矩阵的状态
# 找到0所在行列
def findZero(self):
for i in self.numlist:
if 0 in i:
self.x = self.numlist.index(i)
self.y = i.index(0)
else:
pass
# 打印矩阵
def printNumlist(self):
for i in self.numlist:
print(i)
print("================")
# 判断是否可以向某个方向移动
def canMove(self, direction):
if Moving.LEFT.value == direction:
return self.y>0
if Moving.RIGHT.value == direction:
return self.y<2
if Moving.UP.value == direction:
return self.x>0
if Moving.DOWN.value == direction:
return self