-
Notifications
You must be signed in to change notification settings - Fork 20
/
puzzle.py
79 lines (72 loc) · 2.56 KB
/
puzzle.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
class Puzzle:
goal_state=[1,2,3,8,0,4,7,6,5]
heuristic=None
evaluation_function=None
needs_hueristic=False
num_of_instances=0
def __init__(self,state,parent,action,path_cost,needs_hueristic=False):
self.parent=parent
self.state=state
self.action=action
if parent:
self.path_cost = parent.path_cost + path_cost
else:
self.path_cost = path_cost
if needs_hueristic:
self.needs_hueristic=True
self.generate_heuristic()
self.evaluation_function=self.heuristic+self.path_cost
Puzzle.num_of_instances+=1
def __str__(self):
return str(self.state[0:3])+'\n'+str(self.state[3:6])+'\n'+str(self.state[6:9])
def generate_heuristic(self):
self.heuristic=0
for num in range(1,9):
distance=abs(self.state.index(num) - self.goal_state.index(num))
i=int(distance/3)
j=int(distance%3)
self.heuristic=self.heuristic+i+j
def goal_test(self):
if self.state == self.goal_state:
return True
return False
@staticmethod
def find_legal_actions(i,j):
legal_action = ['U', 'D', 'L', 'R']
if i == 0: # up is disable
legal_action.remove('U')
elif i == 2: # down is disable
legal_action.remove('D')
if j == 0:
legal_action.remove('L')
elif j == 2:
legal_action.remove('R')
return legal_action
def generate_child(self):
children=[]
x = self.state.index(0)
i = int(x / 3)
j = int(x % 3)
legal_actions=self.find_legal_actions(i,j)
for action in legal_actions:
new_state = self.state.copy()
if action is 'U':
new_state[x], new_state[x-3] = new_state[x-3], new_state[x]
elif action is 'D':
new_state[x], new_state[x+3] = new_state[x+3], new_state[x]
elif action is 'L':
new_state[x], new_state[x-1] = new_state[x-1], new_state[x]
elif action is 'R':
new_state[x], new_state[x+1] = new_state[x+1], new_state[x]
children.append(Puzzle(new_state,self,action,1,self.needs_hueristic))
return children
def find_solution(self):
solution = []
solution.append(self.action)
path = self
while path.parent != None:
path = path.parent
solution.append(path.action)
solution = solution[:-1]
solution.reverse()
return solution