class SlidePuzzle(object):
def __init__(self, state = None):
if state == None: state = [[1,2,3],[4,'N',5],[6,7,8]]
self.puzzle_state = list(state)
def isValidMove(self, move):
x,y = self.getBlank()
if move == 'up':
return y != 0
elif move == 'down':
return y != 2
elif move == 'left':
return x != 0
elif move == 'right':
return x != 2
else:
print "Invalid Move"
return 0
def getValidMoves(self):
validMoves = ['up', 'down', 'left', 'right']
if not self.isValidMove('down'):
validMoves.remove('down')
if not self.isValidMove('up'):
validMoves.remove('up')
if not self.isValidMove('right'):
validMoves.remove('right')
if not self.isValidMove('left'):
validMoves.remove('left')
return validMoves
def generateChildren(self):
return [SlidePuzzle(self.puzzle_state).move(m) for m in self.getValidMoves()]
如果我运行这些命令:
- p = SlidePuzzle()
- print p
- p.move('up')
- print p
- print p.generateChildren()
- print p
这是输出。我没有包含我的所有源代码,但您可以看到移动功能根据需要工作。我不明白为什么 generateChildren 函数不仅似乎没有创建任何新的幻灯片拼图对象,而且还与调用对象的拼图状态相混淆。
- [1, 2, 3]
- [4, 'N', 5]
- [6, 7, 8]
- [1, 'N', 3]
- [4, 2, 5]
- [6, 7, 8]
- [None, None, None]
- [1, 2, 3]
- [4, 'N', 5]
- [6, 7, 8]