-
Notifications
You must be signed in to change notification settings - Fork 45
/
lightsout.py
executable file
·245 lines (188 loc) · 6.99 KB
/
lightsout.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
lightsout.py
------------
Tarea sobre búsquedas, donde lo que es importante es crear nuevas heurísticas
"""
__author__ = 'nombre del estudiante'
import busquedas
class LightsOut(busquedas.ModeloBusqueda):
# --------------------------------------------------------
# Completa la clase
# para el modelo de lights out
# --------------------------------------------------------
"""
Problema del jueguito "Ligths out".
La idea del juego es el apagar o prender todas las luces.
Al seleccionar una casilla, la casilla y sus casillas
adjacentes cambian (si estan prendidas se apagan y viceversa).
El juego consiste en una matriz de 5 X 5, cuyo estado puede
ser apagado 0 o prendido 1. Por ejemplo el estado
(0,0,1,0,0,1,1,0,0,1,0,0,1,1,0,1,0,1,0,1,0,0,0,0,0)
corresponde a:
---------------------
| | | X | | |
---------------------
| X | X | | | X |
---------------------
| | | X | X | |
---------------------
| X | | X | | X |
---------------------
| | | | | |
---------------------
Las acciones posibles son de elegir cambiar una luz y sus casillas
adjacentes, por lo que la accion es un número entre 0 y 24.
Para mas información sobre el juego, se puede consultar
http://en.wikipedia.org/wiki/Lights_Out_(game)
"""
def __init__(self):
raise NotImplementedError('Hay que hacerlo de tarea')
def acciones_legales(self, estado):
raise NotImplementedError('Hay que hacerlo de tarea')
def sucesor(self, estado, accion):
raise NotImplementedError('Hay que hacerlo de tarea')
def costo_local(self, estado, accion):
raise NotImplementedError('Hay que hacerlo de tarea')
@staticmethod
def bonito(estado):
"""
El prettyprint de un estado dado
"""
cadena = "---------------------\n"
for i in range(5):
for j in range(5):
if estado[5 * i + j]:
cadena += "| X "
else:
cadena += "| "
cadena += "|\n---------------------\n"
return cadena
# ------------------------------------------------------------
# Completa el problema de LightsOut
# ------------------------------------------------------------
class ProblemaLightsOut(busquedas.ProblemaBusqueda):
def __init__(self, pos_ini):
"""
Utiliza la superclase para hacer el problema
"""
# Completa el código
x0 = tuple(pos_ini)
def meta(x):
raise NotImplementedError("Hay que hacer de tarea")
super().__init__(x0=x0, meta=meta, modelo=LightsOut())
# ------------------------------------------------------------
# Desarrolla una política admisible.
# ------------------------------------------------------------
def h_1(nodo):
"""
DOCUMENTA LA HEURÍSTICA QUE DESARROLLES Y DA UNA JUSTIFICACIÓN
PLATICADA DE PORQUÉ CREES QUE LA HEURÍSTICA ES ADMISIBLE
"""
return 0
# ------------------------------------------------------------
# Desarrolla otra política admisible.
# Analiza y di porque piensas que es (o no es) dominante una
# respecto otra política
# ------------------------------------------------------------
def h_2(nodo):
"""
DOCUMENTA LA HEURÍSTICA DE DESARROLLES Y DA UNA JUSTIFICACIÓN
PLATICADA DE PORQUÉ CREES QUE LA HEURÍSTICA ES ADMISIBLE
"""
return 0
def prueba_modelo():
"""
Prueba la clase LightsOut
"""
pos_ini = (0, 1, 0, 1, 0,
0, 0, 1, 1, 0,
0, 0, 0, 1, 1,
0, 0, 1, 1, 1,
0, 0, 0, 1, 1)
pos_a0 = (1, 0, 0, 1, 0,
1, 0, 1, 1, 0,
0, 0, 0, 1, 1,
0, 0, 1, 1, 1,
0, 0, 0, 1, 1)
pos_a4 = (1, 0, 0, 0, 1,
1, 0, 1, 1, 1,
0, 0, 0, 1, 1,
0, 0, 1, 1, 1,
0, 0, 0, 1, 1)
pos_a24 = (1, 0, 0, 0, 1,
1, 0, 1, 1, 1,
0, 0, 0, 1, 1,
0, 0, 1, 1, 0,
0, 0, 0, 0, 0)
pos_a15 = (1, 0, 0, 0, 1,
1, 0, 1, 1, 1,
1, 0, 0, 1, 1,
1, 1, 1, 1, 0,
1, 0, 0, 0, 0)
pos_a12 = (1, 0, 0, 0, 1,
1, 0, 0, 1, 1,
1, 1, 1, 0, 1,
1, 1, 0, 1, 0,
1, 0, 0, 0, 0)
modelo = LightsOut()
assert modelo.acciones_legales(pos_ini) == range(25)
assert modelo.sucesor(pos_ini, 0) == pos_a0
assert modelo.sucesor(pos_a0, 4) == pos_a4
assert modelo.sucesor(pos_a4, 24) == pos_a24
assert modelo.sucesor(pos_a24, 15) == pos_a15
assert modelo.sucesor(pos_a15, 12) == pos_a12
print("Paso la prueba de la clase LightsOut")
def compara_metodos(pos_inicial, heuristica_1, heuristica_2):
"""
Compara en un cuadro lo nodos expandidos y el costo de la solución
de varios métodos de búsqueda
@param pos_inicial: Una tupla con una posicion inicial
@param heuristica_1: Una función de heurística
@param heuristica_2: Una función de heurística
@return None (no regresa nada, son puros efectos colaterales)
Si la búsqueda no informada es muy lenta, posiblemente tendras que quitarla
de la función
"""
solucion1 = busquedas.busqueda_A_estrella(ProblemaLightsOut(pos_inicial),
heuristica_1)
solucion2 = busquedas.busqueda_A_estrella(ProblemaLightsOut(pos_inicial),
heuristica_2)
print('-' * 50)
print('Método'.center(10) + 'Costo'.center(20) + 'Nodos visitados')
print('-' * 50 + '\n\n')
print('A* con h1'.center(10) + str(solucion1.costo).center(20) +
str(solucion1.nodos_visitados))
print('A* con h2'.center(10) + str(solucion2.costo).center(20) +
str(solucion2.nodos_visitados))
print('-' * 50 + '\n\n')
if __name__ == "__main__":
print("Antes de hacer otra cosa,")
print("vamos a verificar medianamente la clase LightsOut")
prueba_modelo()
# Tres estados iniciales interesantes
diagonal = (0, 0, 0, 0, 1,
0, 0, 0, 1, 0,
0, 0, 1, 0, 0,
0, 1, 0, 0, 0,
1, 0, 0, 0, 0)
simetria = (1, 0, 1, 0, 1,
1, 0, 1, 0, 1,
0, 0, 0, 0, 0,
1, 0, 1, 0, 1,
1, 0, 1, 0, 1)
problemin = (0, 1, 0, 1, 0,
0, 0, 1, 1, 0,
0, 0, 0, 1, 1,
0, 0, 1, 1, 1,
0, 0, 0, 1, 1)
print("\n\nPara el problema en diagonal")
print("\n{}".format(LightsOut.bonito(diagonal)))
compara_metodos(diagonal, h_1, h_2)
print("\n\nPara el problema simétrico")
print("\n".format(LightsOut.bonito(simetria)))
compara_metodos(simetria, h_1, h_2)
print("\n\nPara el problema Bonito")
print("\n".format(LightsOut.bonito(problemin)))
compara_metodos(problemin, h_1, h_2)