Subversion Repositories programming

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
383 ira 1
#!/usr/bin/env python
2
 
3
__author__    = "Ira W. Snyder (devel@irasnyder.com)"
4
__copyright__ = "Copyright (c) 2006 Ira W. Snyder (devel@irasnyder.com)"
5
__license__   = "GNU GPL v2 (or, at your option, any later version)"
6
 
7
from Generator import Generator
8
 
9
 
10
class PuzzleGenerator (Generator):
11
 
12
	EMPTY = 'E'
13
 
384 ira 14
	def __init__ (self, value):
15
		self.value = value
16
 
383 ira 17
	def get_children (self):
18
		children = []
19
		empty_pos = self.find_empty_pos ()
20
 
21
		# Get the correct moves for this position
22
		fn = {	0 : (self.move_down,  self.move_right),
23
			1 : (self.move_down,  self.move_left,  self.move_right),
24
			2 : (self.move_down,  self.move_left),
25
			3 : (self.move_down,  self.move_right, self.move_up),
26
			4 : (self.move_down,  self.move_left,  self.move_right, self.move_up),
27
			5 : (self.move_down,  self.move_left,  self.move_up),
28
			6 : (self.move_right, self.move_up),
29
			7 : (self.move_left,  self.move_right, self.move_up),
30
			8 : (self.move_left,  self.move_up) }[empty_pos]
31
 
32
		# Call each of the proper functions
33
		for f in fn:
34
			children.append (f (empty_pos))
35
 
36
		# Return the created list
37
		return children
38
 
39
	def find_empty_pos (self):
40
		for i in xrange (len (self.value)):
41
			if self.value[i] == self.EMPTY:
42
				return i
43
 
44
		raise ValueError
45
 
46
	def move_up (self, empty_pos):
47
		copy = self.value[:]
48
		copy[empty_pos] = copy[empty_pos - 3]
49
		copy[empty_pos - 3] = self.EMPTY
50
		return copy
51
 
52
	def move_left (self, empty_pos):
53
		copy = self.value[:]
54
		copy[empty_pos] = copy[empty_pos - 1]
55
		copy[empty_pos - 1] = self.EMPTY
56
		return copy
57
 
58
	def move_right (self, empty_pos):
59
		copy = self.value[:]
60
		copy[empty_pos] = copy[empty_pos + 1]
61
		copy[empty_pos + 1] = self.EMPTY
62
		return copy
63
 
64
	def move_down (self, empty_pos):
65
		copy = self.value[:]
66
		copy[empty_pos] = copy[empty_pos + 3]
67
		copy[empty_pos + 3] = self.EMPTY
68
		return copy
69
 
70
 
71
 
72
def printpuz (state):
73
	for i in xrange(3):
74
		for j in xrange(3):
75
			print '%s ' % (str(state[(3*i)+j]), ) ,
76
 
77
		print
78
 
79
def main ():
80
 
81
	#initial = [1, 2, 3, 4, PuzzleGenerator.EMPTY, 5, 6, 7, 8]
82
	initial = [PuzzleGenerator.EMPTY, 2, 3, 4, 1, 5, 6, 7, 8]
83
 
84
	print 'Initial State:'
85
	printpuz (initial)
86
	print
87
 
88
	print 'Children:'
89
	p = PuzzleGenerator(initial)
90
	for c in p.get_children ():
91
		printpuz (c)
92
		print
93
 
94
if __name__ == '__main__':
95
	main ()
96