-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
694 lines (563 loc) · 20.1 KB
/
main.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import json
import math
import random
import time
import sys
import numpy as np
from copy import deepcopy
# Variables Globales
phi = (1 + 5 ** 0.5) / 2
#
class Accion:
def __init__(self):
self.knight_id = 0
self.knight_movement = 0
def setKnight_id(self, id):
self.knight_id = id
def setKnight_movement(self, mov):
self.knight_movement = mov
def getKnight_id(self):
return self.knight_id
def getKnight_movement(self):
return self.knight_movement
def printAccion(self):
print('Pieza: ', self.knight_id, 'puede realizar el movimiento: ', self.knight_movement)
class Estado:
def __init__(self, tablero_nuevo, enemigo, aliado, pos_enemigo, pos_aliado):
self.tablero = self.iniciar(tablero_nuevo)
self.knight_enemigo = self.iniciar(enemigo)
self.knight_enemigo_pos = pos_enemigo
self.knight_aliado = self.iniciar(aliado)
self.knight_aliado_pos = pos_aliado
def iniciar(self, tablero):
for x in range(8):
tablero[x] = list(tablero[x])
return tablero
def printTablero(self):
print(np.matrix(self.tablero))
def printAliado(self):
print(self.knight_aliado)
def printKnight_aliado_pos(self):
print(self.knight_aliado_pos)
def printEnemigo(self):
print(self.knight_enemigo)
def printKnight_enemigo_pos(self):
print(self.knight_enemigo_pos)
def getTablero(self):
return self.tablero
def getPos_knight_enemigo(self, id):
return self.knight_enemigo_pos[str(id)]
def getPos_knight_aliado(self, id):
return self.knight_aliado_pos[str(id)]
def getEnemigo(self):
return self.knight_enemigo
def getAliado(self):
return self.knight_aliado
def esAliado(self, x, y):
if self.knight_aliado[x][y] is not None:
return True
return False
def insertarKnight_tablero(self, x, y, id):
if self.tablero[x][y] is not None:
self.knight_enemigo_pos[str(self.tablero[x][y])] = None
self.knight_enemigo[x][y] = None
self.tablero[x][y] = None
print("pieza enemiga comida")
self.tablero[x][y] = id
self.knight_aliado_pos[str(id)] = [x, y]
self.knight_aliado[x][y] = id
def esEnemigo(self, y, x):
if self.knight_enemigo[x][y] is not None:
return True
return False
def insertarKnight_tablero_enemigo(self, x, y, id):
if self.tablero[x][y] is not None:
self.knight_aliado_pos[str(self.tablero[x][y])] = None
self.knight_aliado[x][y] = None
self.tablero[x][y] = None
print("pieza comida")
self.tablero[x][y] = id
self.knight_enemigo_pos[str(id)] = [x, y]
self.knight_enemigo[x][y] = id
def eliminarKnight_tablero(self, x, y):
self.tablero[x][y] = None
self.knight_aliado[x][y] = None
def eliminarKnight_tablero_enemigo(self, x, y):
self.tablero[x][y] = None
self.knight_enemigo[x][y] = None
def whoWon(self):
empty = [[None, None, None, None, None, None, None, None],
[None, None, None, None, None, None, None, None],
[None, None, None, None, None, None, None, None],
[None, None, None, None, None, None, None, None],
[None, None, None, None, None, None, None, None],
[None, None, None, None, None, None, None, None],
[None, None, None, None, None, None, None, None],
[None, None, None, None, None, None, None, None]]
if self.knight_aliado == empty:
return 0
elif self.knight_enemigo == empty:
return 1
else:
return -1
def getActions(estado):
lista_acciones = []
for i in range(200, 216):
if estado.getPos_knight_aliado(str(i)):
knight_pos = estado.getPos_knight_aliado(str(i))
else:
continue
# print(knight_pos)
x = knight_pos[0]
# print (x)
y = knight_pos[1]
# print(y)
directions = [0, 1, 2, 3, 4, 5, 6, 7]
tablero = estado.getTablero()
if x + 2 < 8 and y + 1 < 8:
if estado.esAliado(x + 2, y + 1):
directions.remove(0)
else:
if x + 2 >= 8 or y + 1 >= 8:
directions.remove(0)
if x + 1 < 8 and y + 2 < 8:
if estado.esAliado(x + 1, y + 2):
directions.remove(1)
else:
if x + 1 >= 8 or y + 2 >= 8:
directions.remove(1)
if y + 2 < 8 and x - 1 >= 0:
if estado.esAliado(x - 1, y + 2):
directions.remove(2)
else:
if x - 1 < 0 or y + 2 >= 8:
directions.remove(2)
if y + 1 < 8 and x - 2 >= 0:
if estado.esAliado(x - 2, y + 1):
directions.remove(3)
else:
if x - 2 < 0 or y + 1 >= 8:
directions.remove(3)
if y - 1 >= 0 and x - 2 >= 0:
if estado.esAliado(x - 2, y - 1):
directions.remove(4)
else:
if y - 1 < 0 or x - 2 < 0:
directions.remove(4)
if y - 2 >= 0 and x - 1 >= 0:
if estado.esAliado(x - 1, y - 2):
directions.remove(5)
else:
if x - 1 < 0 or y - 2 < 0:
directions.remove(5)
if y - 2 >= 0 and x + 1 < 8:
if estado.esAliado(x + 1, y - 2):
directions.remove(6)
else:
if x + 1 >= 8 or y - 2 < 0:
directions.remove(6)
if y - 1 >= 0 and x + 2 < 8:
if estado.esAliado(x + 2, y - 1):
directions.remove(7)
else:
if y - 1 < 0 or x + 2 >= 8:
directions.remove(7)
for direction in directions:
accion = Accion()
accion.setKnight_id(i)
accion.setKnight_movement(direction)
lista_acciones.append(accion)
return lista_acciones
def transition(accion, estado):
nuevo_estado = estado
knight_pos = estado.getPos_knight_aliado(accion.getKnight_id())
# print(knight_pos)
x = knight_pos[0]
# print (x)
y = knight_pos[1]
if accion.getKnight_movement() == 0:
nuevo_estado.eliminarKnight_tablero(x, y)
x = x + 2
y = y + 1
nuevo_estado.insertarKnight_tablero(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 1:
nuevo_estado.eliminarKnight_tablero(x, y)
x = x + 1
y = y + 2
nuevo_estado.insertarKnight_tablero(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 2:
nuevo_estado.eliminarKnight_tablero(x, y)
x = x - 1
y = y + 2
nuevo_estado.insertarKnight_tablero(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 3:
nuevo_estado.eliminarKnight_tablero(x, y)
x = x - 2
y = y + 1
nuevo_estado.insertarKnight_tablero(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 4:
nuevo_estado.eliminarKnight_tablero(x, y)
x = x - 2
y = y - 1
nuevo_estado.insertarKnight_tablero(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 5:
nuevo_estado.eliminarKnight_tablero(x, y)
x = x - 1
y = y - 2
nuevo_estado.insertarKnight_tablero(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 6:
nuevo_estado.eliminarKnight_tablero(x, y)
x = x + 1
y = y - 2
nuevo_estado.insertarKnight_tablero(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 7:
nuevo_estado.eliminarKnight_tablero(x, y)
x = x + 2
y = y - 1
nuevo_estado.insertarKnight_tablero(x, y, accion.getKnight_id())
return nuevo_estado
def getActions_Enemigo(estado):
lista_acciones = []
for i in range(100, 116):
if estado.getPos_knight_enemigo(str(i)):
knight_pos = estado.getPos_knight_enemigo(str(i))
else:
continue
# print(knight_pos)
x = knight_pos[0]
# print (x)
y = knight_pos[1]
# print(y)
directions = [0, 1, 2, 3, 4, 5, 6, 7]
tablero = estado.getTablero()
if y + 1 < 8 and x + 2 < 8:
if estado.esEnemigo(y + 1, x + 2):
directions.remove(0)
else:
if x + 2 >= 8 or y + 1 >= 8:
directions.remove(0)
if y + 2 < 8 and x + 1 < 8:
if estado.esEnemigo(y + 2, x + 1):
directions.remove(1)
else:
if x + 1 >= 8 or y + 2 >= 8:
directions.remove(1)
if y + 2 < 8 and x - 1 >= 0:
if estado.esEnemigo(y + 2, x - 1):
directions.remove(2)
else:
if x - 1 < 0 or y + 2 >= 8:
directions.remove(2)
if y + 1 < 8 and x - 2 >= 0:
if estado.esEnemigo(y + 1, x - 2):
directions.remove(3)
else:
if x - 2 < 0 or y + 1 >= 8:
directions.remove(3)
if y - 1 >= 0 and x - 2 >= 0:
if estado.esEnemigo(y - 1, x - 2):
directions.remove(4)
else:
if y - 1 < 0 or x - 2 < 0:
directions.remove(4)
if y - 2 >= 0 and x - 1 >= 0:
if estado.esEnemigo(y - 2, x - 1):
directions.remove(5)
else:
if x - 1 < 0 or y - 2 < 0:
directions.remove(5)
if y - 2 >= 0 and x + 1 < 8:
if estado.esEnemigo(y - 2, x + 1):
directions.remove(6)
else:
if x + 1 >= 8 or y - 2 < 0:
directions.remove(6)
if y - 1 >= 0 and x + 2 < 8:
if estado.esEnemigo(y - 1, x + 2):
directions.remove(7)
else:
if y - 1 < 0 or x + 2 >= 8:
directions.remove(7)
for direction in directions:
accion = Accion()
accion.setKnight_id(i)
accion.setKnight_movement(direction)
lista_acciones.append(accion)
#print(lista_acciones)
return lista_acciones
def transitionEnemigo(accion, estado):
nuevo_estado = estado
knight_pos = estado.getPos_knight_enemigo(accion.getKnight_id())
# print(knight_pos)
x = knight_pos[0]
# print (x)
y = knight_pos[1]
if accion.getKnight_movement() == 0:
nuevo_estado.eliminarKnight_tablero_enemigo(x, y)
x = x + 2
y = y + 1
nuevo_estado.insertarKnight_tablero_enemigo(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 1:
nuevo_estado.eliminarKnight_tablero_enemigo(x, y)
x = x + 1
y = y + 2
nuevo_estado.insertarKnight_tablero_enemigo(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 2:
nuevo_estado.eliminarKnight_tablero_enemigo(x, y)
x = x - 1
y = y + 2
nuevo_estado.insertarKnight_tablero_enemigo(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 3:
nuevo_estado.eliminarKnight_tablero_enemigo(x, y)
x = x - 2
y = y + 1
nuevo_estado.insertarKnight_tablero_enemigo(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 4:
nuevo_estado.eliminarKnight_tablero_enemigo(x, y)
x = x - 2
y = y - 1
nuevo_estado.insertarKnight_tablero_enemigo(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 5:
nuevo_estado.eliminarKnight_tablero_enemigo(x, y)
x = x - 1
y = y - 2
nuevo_estado.insertarKnight_tablero_enemigo(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 6:
nuevo_estado.eliminarKnight_tablero_enemigo(x, y)
x = x + 1
y = y - 2
nuevo_estado.insertarKnight_tablero_enemigo(x, y, accion.getKnight_id())
if accion.getKnight_movement() == 7:
nuevo_estado.eliminarKnight_tablero_enemigo(x, y)
x = x + 2
y = y - 1
nuevo_estado.insertarKnight_tablero_enemigo(x, y, accion.getKnight_id())
return nuevo_estado
#
# Estructuras Para Implementar Arbol
#
class Node:
def __init__(self, sInput, pInput, wInput, cInput, vInput, aInput, tInput, uInput):
self.state = sInput
self.parent = pInput
self.childs = cInput
self.simulations = vInput
self.wins = wInput
self.action = aInput
self.turn = tInput # 1 si es el turno del jugador y -1 si es el del enemigo
self.uctValue = uInput
self.isRoot = False
self.flag = False
# Gets y Sets
def setState(self, SInput):
self.state = SInput
def getState(self):
return self.state
def setRoot(self, root):
self.isRoot = root
def getRoot(self):
return self.isRoot
def visit(self):
self.flag = True
def isVisited(self):
return self.flag
def unvisit(self):
self.flag = False
def setParent(self, PInput):
self.parent = PInput
def getParent(self):
return self.parent
def setChilds(self, CInput):
self.childs = CInput
def getChilds(self):
return self.childs
def setVisits(self, VInput):
self.simulations = VInput
def getVisits(self):
return self.simulations
def setWins(self, WInput):
self.wins = WInput
def getWins(self):
return self.wins
def setTurn(self, TInput):
self.turn = TInput
def setUct(self, UInput):
self.uctValue = UInput
def getUct(self):
return self.uctValue
#
# Funciones Clase
#
def isFullExpanded(self):
# Determina si el nodo esta completamente Expandido
if self.turn == 1:
if len(self.childs) == (len(getActions(self.state))):
return True
else:
return False
else:
if len(self.childs) == (len(getActions_Enemigo(self.state))):
return True
else:
return False
def ifActionIsInChilds(self, action):
for c in self.childs:
if c.action == action:
return True
return False
def expandNode(self):
if self.turn == -1:
actions = getActions(self.state)
for a in actions:
if self.ifActionIsInChilds(a) is False:
child = Node(transition(a, self.state), self, 0, [], 0, a, 1, 0)
self.childs.append(child)
return child
else:
actions = getActions_Enemigo(self.state)
for a in actions:
if self.ifActionIsInChilds(a) is False:
child = Node(transitionEnemigo(a, self.state), self, 0, [], 0, a, -1, 0)
self.childs.append(child)
return child
def updateWins(self, outcome):
self.simulations += 1
self.wins += outcome
def UCTvalue(Tvisits, nodeWins, nodeVisits, nodeTurn):
if nodeVisits == 0:
return sys.maxsize
else:
return (nodeTurn * (nodeWins / nodeVisits)) + (phi * (math.sqrt(math.log(Tvisits) / nodeVisits)))
def findBestNode(rootNode):
childs = rootNode.getChilds()
sim = 0
best = childs[0]
for child in childs:
if child.getVisits() > sim:
best = child
return best
def defaultPolicy(state, flag):
temp = deepcopy(state)
while temp.whoWon() == -1:
if flag == 1:
if not getActions(temp):
print("acciones vacia")
break
a = random.choice(getActions(temp))
#print(a)
temp = transition(a, temp)
flag = 0
else:
if not getActions_Enemigo(temp):
print("acciones vacia")
break
a = random.choice(getActions_Enemigo(temp))
#print(a)
temp = transitionEnemigo(a, temp)
flag = 1
#print("who won:")
#print(temp.whoWon())
#state.printTablero()
#print()
#()
#print()
#temp.printTablero()
#print()
#print()
#print()
return temp.whoWon()
def monteCarloTreeSearch(intialState, turn):
t_end = time.time() + 4.8
rootNode = Node(intialState, None, 0, [], 0, None, turn, 0)
simulations = 0
while time.time() < t_end:
node = selectNode(rootNode)
child = expandNode(node)
outcome = defaultPolicy(child.getState(), child.turn)
simulations += 1
updateNodes(outcome, child, simulations)
return findBestNode(rootNode)
def getTree(rootNode):
nodes = [rootNode]
rootNode.setRoot(True)
currentNode = rootNode
while rootNode.isVisited() is False:
if not currentNode.getChilds():
currentNode.visit()
if currentNode is not rootNode:
nodes.append(currentNode)
currentNode = currentNode.getParent()
else:
complete = True
for child in currentNode.getChilds():
if not child.isVisited():
currentNode = child
complete = False
break
if complete:
currentNode.visit()
if currentNode is not rootNode:
nodes.append(currentNode)
currentNode = currentNode.getParent()
for node in nodes:
node.unvisit()
rootNode.setRoot(False)
return nodes
def selectNode(rootNode):
nodos = getTree(rootNode)
higher = 0
bestnode = rootNode
first = True
for nodo in nodos:
if first:
first = False
continue
if nodo.getUct() > higher:
higher = nodo.getUct()
bestnode = nodo
return bestnode
def expandNode(node):
if node.isFullExpanded():
return expandNodeFull(node)
else:
return node.expandNode()
def expandNodeFull(node):
new = selectNode(node)
return expandNode(new)
def updateNodes(outcome, child, simulations):
while child.getParent() is not None:
child.updateWins(outcome)
child.setUct(UCTvalue(simulations, child.getWins(), child.getVisits(), child.turn))
child = child.getParent()
def main():
runtime = time.time()
with open('tablero.json') as f:
datos = json.load(f)
print(datos)
for dato in datos:
# print(dato['ids'])
tablero = Estado([*zip(*dato['ids'])], [*zip(*dato['enemy_knights'])], [*zip(*dato['my_knights'])],
dato['enemy_knights_dict'],
dato['my_knights_dict'])
with open('primerturno.json') as f:
datos = json.load(f)
print(datos)
for dato in datos:
# print(dato['ids'])
primerturno = Estado([*zip(*dato['ids'])], [*zip(*dato['enemy_knights'])], [*zip(*dato['my_knights'])],
dato['enemy_knights_dict'],
dato['my_knights_dict'])
test = getActions(tablero)
print(test)
testalt = getActions_Enemigo(tablero)
print(testalt)
tablero.printTablero()
#if primerturno == tablero:
jugada = monteCarloTreeSearch(tablero, 1)
#else:
# jugada = monteCarloTreeSearch(tablero, -1)
jugada.getState().printTablero()
endtime = time.time() - runtime
print(endtime)
if __name__ == "__main__":
main()