-
Notifications
You must be signed in to change notification settings - Fork 8
/
8puzzle.py
executable file
·328 lines (258 loc) · 10.2 KB
/
8puzzle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#!/usr/bin/python
# Christine Cheung
# CS170 Project 1 (8-Puzzle)
import sys, copy
goal = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', ' ']]
def main():
input = puzzleInput() # puzzle input
algoChoice = algorithm() # algorithm input
puzzleSearch(input, algoChoice) # and searching for puzzle solution
def puzzleInput():
# the default puzzle to use
default = [['1', '2', '3'], ['4', ' ', '6'], ['7', '5', '8']]
# set our main puzzle
puzzle = []
print "Greetings, this is Christine's 8-puzzle solver."
# loop until we get correct input
while 1:
startinput = raw_input("Type 1 to use the default puzzle, 2 to enter your own, or 3 to quit.\n")
# 1: default puzzle
if (startinput == "1"):
print "Using default puzzle...\n"
puzzle = default
return puzzle
# 2: user defined puzzle
elif (startinput == "2"):
print "Enter your puzzle, use a zero to represent the blank:\n"
firstrow = raw_input("Enter the first row, use a space between numbers ")
# FIRST row
firstrow = firstrow.split(' ')
# change 0 to space
if (firstrow.count('0') == 1):
firstrow[firstrow.index('0')] = ' '
# SECOND row
secondrow = raw_input("Enter the second row, use a space between numbers ")
secondrow = secondrow.split(' ')
# change 0 to space
if (secondrow.count('0') == 1):
secondrow[secondrow.index('0')] = ' '
# THIRD row
thirdrow = raw_input("Enter the third row, use a space between numbers ")
thirdrow = thirdrow.split(' ')
# change 0 to space
if (thirdrow.count('0') == 1):
thirdrow[thirdrow.index('0')] = ' '
# add the input to the puzzle
puzzle.append(firstrow)
puzzle.append(secondrow)
puzzle.append(thirdrow)
print "\n"
return puzzle
# 3: quit puzzle
elif (startinput == "3"):
sys.exit(0)
def algorithm():
print "Choice of algorithms to use:"
print "1. Uniform Cost Search"
print "2. A* with misplaced tile heuristic"
print "3: A* with Manhattan distance heuristic\n"
# infinite loop until correct input of algorithm choice
while 1:
pickAlgo = raw_input("Enter: ")
if(pickAlgo == '1'):
return "costSearch"
elif(pickAlgo == '2'):
return "misplacedTile"
elif(pickAlgo == '3'):
return "manhattan"
return pickAlgo
def expand(puzzle):
expandList = []
puzzleLeft = copy.deepcopy(puzzle)
# move the tile left
# search through the puzzle
for x in puzzleLeft:
# check where the blank tile is
if (x.count(' ') == 1):
# make sure it's not on the left side
# so we can actually move it legally
if (x.index(' ') != 0):
spaceindex = x.index(' ')
# set space to equal left tile
x[spaceindex] = x[spaceindex - 1]
x[spaceindex - 1] = ' '
expandList.append(puzzleLeft)
puzzleRight = copy.deepcopy(puzzle)
# move the tile right
for x in puzzleRight:
# check where the blank tile is print puzzle
if (x.count(' ') == 1):
# make sure it's not on the right side
# so we can actually move it legally
if (x.index(' ') != 2):
spaceindex = x.index(' ')
# set space to equal right tile
x[spaceindex] = x[spaceindex + 1]
x[spaceindex + 1] = ' '
expandList.append(puzzleRight)
puzzleUp = copy.deepcopy(puzzle)
# move the tile up
for x in puzzle:
# check where the blank tile is
if (x.count(' ') == 1):
# make sure it's not on the top (first row)
# so we can actually move it legally
if (x != puzzleUp[0]):
spaceindex = x.index(' ')
# on second row?
if(x == puzzle[1]):
puzzleUp[1][spaceindex] = puzzleUp[0][spaceindex]
puzzleUp[0][spaceindex] = ' '
expandList.append(puzzleUp)
# or third
else:
puzzleUp[2][spaceindex] = puzzleUp[1][spaceindex]
puzzleUp[1][spaceindex] = ' '
expandList.append(puzzleUp)
puzzleDown = copy.deepcopy(puzzle)
# move the tile down
for x in puzzle:
# check where the blank tile is
if (x.count(' ') == 1):
# make sure it's not on the bottom (third row)
# so we can actually move it legally
if (x != puzzle[2]):
spaceindex = x.index(' ')
# on first row?
if(x == puzzle[0]):
puzzleDown[0][spaceindex] = puzzleDown[1][spaceindex]
puzzleDown[1][spaceindex] = ' '
expandList.append(puzzleDown)
# or second
else:
puzzleDown[1][spaceindex] = puzzleDown[2][spaceindex]
puzzleDown[2][spaceindex] = ' '
expandList.append(puzzleDown)
return expandList
# create our node class for enqueuing puzzle states
class node:
def __init__(self):
self.heuristic = 0
self.depth = 0
def printPuzzle(self):
print ''
print self.puzzleState[0][0], self.puzzleState[0][1], self.puzzleState[0][2]
print self.puzzleState[1][0], self.puzzleState[1][1], self.puzzleState[1][2]
print self.puzzleState[2][0], self.puzzleState[2][1], self.puzzleState[2][2]
def setPuzzle(self, puzzle):
self.puzzleState = puzzle
def checkGoal(puzzle):
# check if puzzle has been solved (equals goal state)
return goal == puzzle
def misplacedTiles(puzzle):
misplace = 0
for x in range(3):
for y in range(3):
# make sure we don't check blank
if (puzzle[x][y] != ' '):
# if it's not at it's proper place, it's misplaced
if (puzzle[x][y] != goal[x][y]):
misplace += 1
return misplace
def manhattan(puzzle):
mDistance = 0
puzzleContents = ['1', '2', '3', '4', '5', '6', '7', '8']
# search through the numbers in the puzzle
for x in puzzleContents:
for i in range(3):
for j in range(3):
# get where the number should be
if (x == goal[i][j]):
goalRow = i
goalCol = j
# get where the number is now
if (x == puzzle[i][j]):
puzzleRow = i
puzzleCol = j
# calculate the Manhattan Distance based on the points (row/col)
mDistance += ( abs(goalRow - puzzleRow) + abs(goalCol - puzzleCol) )
return mDistance
# from http://en.wikipedia.org/wiki/Bubble_sort
def bubblesort(queue):
for passesLeft in xrange(len(queue)-1, 0, -1):
for index in xrange(passesLeft):
if (queue[index].heuristic + queue[index].depth) > \
(queue[index + 1].heuristic + queue[index + 1].depth):
queue[index], queue[index + 1] = queue[index + 1], queue[index]
return queue
def puzzleSearch(puzzle, algorithm):
nodesExpanded = 0
maxQueueSize = 0
queue = []
# make the new node (set to intial puzzle)
puzzleNode = node()
puzzleNode.setPuzzle(puzzle)
# the initial depth
puzzleNode.depth = 0
# pick our heuristics
if (algorithm == "costSearch"):
puzzleNode.heuristic = 1
if (algorithm == "misplacedTile"):
puzzleNode.heuristic = misplacedTiles(puzzleNode.puzzleState)
if (algorithm == "manhattan"):
puzzleNode.heuristic = manhattan(puzzleNode.puzzleState)
# append first node (initial state) to the queue
queue.append(puzzleNode)
# infinite loop until we find our solution
while 1:
if (len(queue) == 0):
print "Puzzle search exhausted"
sys.exit(0)
# make the puzzleNode equal to the front of queue
checkNode = node()
checkNode.puzzleState = queue[0].puzzleState
checkNode.heuristic = queue[0].heuristic
checkNode.depth = queue[0].depth
# print depth and heuristics stats
print ''
print "The best node to expand with g(n) =", checkNode.depth, \
"and h(n) =", checkNode.heuristic, "is..."
checkNode.printPuzzle()
print "Expanding this node..."
# then remove the front of queue
queue.pop(0)
# check if it is the solution
if (checkGoal(checkNode.puzzleState)):
# then print solution and return
print ''
print "Solution found!!"
checkNode.printPuzzle()
print ''
print "Expanded a total of", nodesExpanded, "nodes"
print "Maximum number of nodes in the queue was", maxQueueSize
print "The depth of the goal node was", checkNode.depth
return
# expand the node
expandedPuzzle = expand(checkNode.puzzleState)
for x in expandedPuzzle:
# make each expansion a node...
# and then add them to the queue
tempNode = node()
tempNode.setPuzzle(x)
# determine the heuristic to use
if (algorithm == "costSearch"):
tempNode.heuristic = 1
if (algorithm == "misplacedTile"):
tempNode.heuristic = misplacedTiles(tempNode.puzzleState)
if (algorithm == "manhattan"):
tempNode.heuristic = manhattan(tempNode.puzzleState)
# every time you expand, you add a depth
tempNode.depth = checkNode.depth + 1
# and then add it to the queue, of course
queue.append(tempNode)
nodesExpanded += 1
if(len(queue) > maxQueueSize):
maxQueueSize = len(queue)
queue = bubblesort(queue)
if __name__ == "__main__":
main()