-
Notifications
You must be signed in to change notification settings - Fork 5
/
puzzle.py
197 lines (178 loc) · 6.26 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
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
from random import randint
from matrix import Matrix
from queue import PriorityQueue, Queue
import random
import pygame
import colors
import numpy as np
import time
class Puzzle:
def __init__(self, x, y, width, height, lastSolveTime, move, cost, matrix, blocks = [], final_state = "1,2,3,4,5,6,7,8,0"):
self.x = x
self.y = y
self.width = width
self.height = height
self.lastSolveTime = lastSolveTime
self.move = move
self.cost = cost
self.matrix = matrix
self.blocks = blocks
self.final_state = final_state
@staticmethod
def new(x, y, width, height):
return Puzzle(x, y, width, height, 0, [], 0, Matrix(3,3), [])
def validNumbers(self, numbers):
valid = False
if len(numbers) == 9:
ref = list(range(9))
valid = True
for i in numbers:
if int(i) not in ref:
valid = False
else:
ref.remove(int(i))
return valid
def randomBlocks(self):
n = randint(30,40)
for i in range(n):
zero = self.matrix.searchBlock(0)
possibleMoves = []
#move up
if zero[0] > 0:
possibleMoves.append(self.matrix.moveup)
if zero[0] < 2:
possibleMoves.append(self.matrix.movedown)
if zero[1] > 0:
possibleMoves.append(self.matrix.moveleft)
if zero[1] < 2:
possibleMoves.append(self.matrix.moveright)
random.choice(possibleMoves)(zero)
self.setBlocksMatrix()
def setBlocksMatrix(self):
blocks = []
block_x=self.x
block_y=self.y
block_w = self.width/3
block_h = self.height/3
m = self.matrix.getMatrix()
i=0
for k in range(3):
for j in range(3):
blocks.append({'rect':pygame.Rect(block_x, block_y, block_w, block_h),'color':colors.BABY_BLUE,'block':m[k][j]})
block_x += block_w+1
i+=1
block_y += block_h+1
block_x = self.x
self.blocks = blocks
def setBlocks(self, string):
numbers = string.split(",")
blocks = []
if self.validNumbers(numbers) :
block_x=self.x
block_y=self.y
block_w = self.width/3
block_h = self.height/3
self.matrix.buildMatrix(string)
i=0
for k in range(3):
for j in range(3):
blocks.append({'rect':pygame.Rect(block_x, block_y, block_w, block_h),'color':colors.BABY_BLUE,'block':int(numbers[i])})
block_x += block_w+1 #right
i+=1
block_y += block_h+1 #down
block_x = self.x
self.blocks = blocks
return True
return False
def initialize(self):
blocks = self.final_state
self.setBlocks(blocks)
def existsIn(self,elem, list = []):
for item in list:
if item.isEqual(elem):
return True
return False
def getCost(self,actual):
while(actual > 0):
return 1
def bestFirst(self):
#função de avaliação por busca em largura
inicio = time.time()
node = self.matrix
Mfinal = Matrix(3,3)
Mfinal.buildMatrix(self.final_state) #1,2,3,4,5,6,7,8,0
final = Mfinal.getMatrix()
queue = PriorityQueue()
queue.put(node)
visitedNodes = []
n = 1
while(not node.isEqual(final) and not queue.empty()):
node = queue.get()
visitedNodes.append(node)
moves = []
childNodes = node.getPossibleNodes(moves)
for i in range(len(childNodes)):
if not self.existsIn(childNodes[i].getMatrix(),visitedNodes):
childNodes[i].move = moves[i]
childNodes[i].manhattanDist()
childNodes[i].setPrevious(node)
queue._put(childNodes[i])
n += 1
moves = []
self.cost = n
if(node.isEqual(final)):
moves.append(node.move)
nd = node.previous
while nd != None:
if nd.move != '':
moves.append(nd.move)
nd = nd.previous
fim = time.time()
self.lastSolveTime = fim-inicio
print("## Best-First ##\n")
print("Tempo gasto {temp: .5f}:".format(temp = fim-inicio))
print("Tós visitados:",n,"\n")
return moves[::-1]
def a_star(self):
# iniciando timer
inicio = time.time()
node = self.matrix
Mfinal = Matrix(3,3)
Mfinal.buildMatrix(self.final_state) #1,2,3,4,5,6,7,8,0
final = Mfinal.getMatrix()
queue = PriorityQueue()
queue.put(node)
visitedNodes = []
indexSelected = 0
n = 1
while (not node.isEqual(final) and not queue.empty()):
node = queue.get()
visitedNodes.append(node)
moves = []
childNodes = node.getPossibleNodes(moves)
for i in range(len(childNodes)):
if not self.existsIn(childNodes[i].getMatrix(), visitedNodes):
childNodes[i].move = moves[i]
childNodes[i].manhattanDist()
childNodes[i].setPrevious(node)
# Cumulating the cost function
childNodes[i].cost = node.cost + node.manhattanDistCost(childNodes[i])
childNodes[i].dist += childNodes[i].cost
queue._put(childNodes[i])
n += 1
auxCost = 0
moves = []
self.cost = n
if(node.isEqual(final)):
moves.append(node.move)
nd = node.previous
while nd != None:
if nd.move != '':
moves.append(nd.move)
nd = nd.previous
fim = time.time()
self.lastSolveTime = fim-inicio
print("## A* ##\n")
print("Tempo gasto {temp: .5f}:".format(temp = fim-inicio))
print("Nós visitados:",n,"\n")
return moves[::-1]