Blame | Last modification | View Log | RSS feed
#!/usr/bin/env python
__author__ = "Ira W. Snyder (devel@irasnyder.com)"
__copyright__ = "Copyright (c) 2006 Ira W. Snyder (devel@irasnyder.com)"
__license__ = "GNU GPL v2 (or, at your option, any later version)"
from Generator import Generator
class PuzzleGenerator (Generator):
EMPTY = 'E'
def get_children (self):
children = []
empty_pos = self.find_empty_pos ()
# Get the correct moves for this position
fn = { 0 : (self.move_down, self.move_right),
1 : (self.move_down, self.move_left, self.move_right),
2 : (self.move_down, self.move_left),
3 : (self.move_down, self.move_right, self.move_up),
4 : (self.move_down, self.move_left, self.move_right, self.move_up),
5 : (self.move_down, self.move_left, self.move_up),
6 : (self.move_right, self.move_up),
7 : (self.move_left, self.move_right, self.move_up),
8 : (self.move_left, self.move_up) }[empty_pos]
# Call each of the proper functions
for f in fn:
children.append (f (empty_pos))
# Return the created list
return children
def find_empty_pos (self):
for i in xrange (len (self.value)):
if self.value[i] == self.EMPTY:
return i
raise ValueError
def move_up (self, empty_pos):
copy = self.value[:]
copy[empty_pos] = copy[empty_pos - 3]
copy[empty_pos - 3] = self.EMPTY
return copy
def move_left (self, empty_pos):
copy = self.value[:]
copy[empty_pos] = copy[empty_pos - 1]
copy[empty_pos - 1] = self.EMPTY
return copy
def move_right (self, empty_pos):
copy = self.value[:]
copy[empty_pos] = copy[empty_pos + 1]
copy[empty_pos + 1] = self.EMPTY
return copy
def move_down (self, empty_pos):
copy = self.value[:]
copy[empty_pos] = copy[empty_pos + 3]
copy[empty_pos + 3] = self.EMPTY
return copy
def printpuz (state):
for i in xrange(3):
for j in xrange(3):
print '%s ' % (str(state[(3*i)+j]), ) ,
def main ():
#initial = [1, 2, 3, 4, PuzzleGenerator.EMPTY, 5, 6, 7, 8]
initial = [PuzzleGenerator.EMPTY, 2, 3, 4, 1, 5, 6, 7, 8]
print 'Initial State:'
printpuz (initial)
print 'Children:'
p = PuzzleGenerator(initial)
for c in p.get_children ():
printpuz (c)
if __name__ == '__main__':
main ()