-
Notifications
You must be signed in to change notification settings - Fork 0
/
Board.py
605 lines (543 loc) · 18.4 KB
/
Board.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
import time
import copy
import numpy as np
import platform
import functools
from os import system
from random import Random
def timer(func):
'''
Função para contar tempo da jogada
'''
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
t1 = time.perf_counter()
res = func(self, *args, **kwargs)
t2 = round(time.perf_counter() - t1, 6)
print("Tempo da jogada: " + str(t2))
return res
return wrapper
class Board:
def __init__(self):
self.board = np.zeros(shape=(4, 4))
self.possible_plays = [a for a in range(16)]
self.plays_ocurred = 0
def render(self):
"""
Plota o tabuleiro
"""
simbolo = {
1: "X",
-1: "O",
0: " "
}
str_line = '--------------------'
cont = 1
print('\n' + str_line)
for linha in self.board:
for cell in linha:
symbol = simbolo[cell]
symbol = str(cont) if symbol == ' ' else symbol
print(f'| {symbol} |', end='')
cont += 1
print('\n' + str_line)
def clean(self):
"""
Limpa o console
"""
os_name = platform.system().lower()
if 'windows' in os_name:
system('cls')
else:
system('clear')
def check_win(self):
"""
verifica se algum jogador ganhou a partida, dado sua jogada
"""
for i in range(4):
possible = 0
for j in range(4):
possible += jogo.board[i][j]
if abs(possible) == 4:
return True
for i in range(4):
possible = 0
for j in range(4):
possible += jogo.board[j][i]
if abs(possible) == 4:
return True
possible = 0
for i in range(4):
possible += jogo.board[i][i]
if abs(possible) == 4:
return True
possible = 0
for i in range(4):
possible += jogo.board[i][3 - i]
if abs(possible) == 4:
return True
return False
def contar_jogada(self):
self.plays_ocurred += 1
print(f"Jogada nº {self.plays_ocurred}")
def count_play(self, jogada : int, index : int):
self.possible_plays.remove(jogada)
self.board[(jogada) // 4][(jogada) % 4] = index
self.contar_jogada()
class Jogador:
def __init__(self, index):
self.id = index
def make_play(self, board: Board):
"""
método para jogador realizar jogada e alterar estado do tabuleiro
"""
class Humano(Jogador):
def __init__(self):
super().__init__(index=1)
@timer
def make_play(self, tabuleiro: Board):
"""
método para jogador realizar jogada e alterar estado do tabuleiro
"""
play_not_made = True
a = -1
while play_not_made:
a = int(input("Jogada (numpad) : 1...16 "))
if tabuleiro.board[(a - 1) // 4][(a - 1) % 4] == 0:
play_not_made = False
else:
print("Jogada " + str(a) + " não é possível. Tente outra jogada")
return a - 1
POSSIBLE_TYPES = ["Random", "MiniMax", "MiniMaxAlphaBeta"]
class Maquina(Jogador):
def __init__(self, index, type, max_depth):
super().__init__(index)
if type not in POSSIBLE_TYPES:
print("Tipo do agente não reconhecido, escolha entre : " + POSSIBLE_TYPES)
self.type = type
self.nos_percorridos = 0
if type == "Random":
self.random = Random()
else:
self.max_depth = max_depth
@timer
def make_play(self, board: Board):
"""
método para maquina realizar jogada
"""
a = -1
if self.type == "Random":
play = board.possible_plays[self.random.randint(0, len(board.possible_plays) - 1)]
a = play
elif self.type == "MiniMax":
copia = copy.deepcopy(board)
for cell in copia.possible_plays:
copia = copy.deepcopy(jogo)
copia.board[cell // 4][cell % 4] = self.id
copia.possible_plays.remove(cell)
if self.win_state(copia, self.id) == self.id:
a = cell
if self.avoid_win(cell, copia, self.id):
a = cell
if a == -1:
copia = copy.deepcopy(board)
minimax = self.minimax(copia, 1, self.id)
play = minimax[0]
a = play
print("nós percorridos : ", self.nos_percorridos)
self.nos_percorridos = 0
else:
copia = copy.deepcopy(board)
for cell in copia.possible_plays:
copia = copy.deepcopy(jogo)
copia.board[cell // 4][cell % 4] = self.id
copia.possible_plays.remove(cell)
if self.win_state(copia, self.id) == self.id:
a = cell
break
if self.avoid_win(cell, copia, self.id):
a = cell
if a == -1:
copia = copy.deepcopy(board)
alfabeta = self.alfa_beta(copia, 1, self.id, -np.Inf, np.Inf)
play = alfabeta[0]
a = play
print("nós percorridos : ", self.nos_percorridos)
self.nos_percorridos = 0
assert a in range(16)
return a
def avoid_win(self,jogada,jogo, player):
'''
Dado uma jogada, verifica se essa evita ganho do oponente
'''
if jogada in [0,15]:
score_player = 0
score_oponent = 0
for i in range(4):
if jogo.board[i][i] == player:
score_player += 1
if jogo.board[i][i] == -player:
score_oponent += 1
if score_player == 1 and score_oponent == 3:
return True
if jogada in [3,11]:
score_player = 0
score_oponent = 0
for i in range(4):
if jogo.board[i][3 - i] == player:
score_player += 1
if jogo.board[i][3 - i] == -player:
score_oponent += 1
if score_player == 1 and score_oponent == 3:
return True
score_player = 0
score_oponent = 0
for i in range(4):
if jogo.board[i][jogada % 4] == player:
score_player += 1
if jogo.board[i][jogada % 4] == -player:
score_oponent += 1
if score_player == 1 and score_oponent == 3:
return True
score_player = 0
score_oponent = 0
for i in range(4):
if jogo.board[jogada // 4][i] == player:
score_player += 1
if jogo.board[jogada // 4][i] == -player:
score_oponent += 1
if score_player == 1 and score_oponent == 3:
return True
return False
def win_state(self,jogo, player):
'''
Retorna 1 caso o player ganhou dado o estado do jogo,
Retorna 0 caso houve empate ou nenhum dos jogadores ganhou dado o estado do tabuleiro,
Retorna -1 caso o player perdeu dado o estado do jogo.
'''
for i in range(4):
possible = 0
for j in range(4):
possible += jogo.board[i][j]
if possible == player * 4:
return 1
elif possible == -player * 4:
return -1
for i in range(4):
possible = 0
for j in range(4):
possible += jogo.board[j][i]
if possible == player * 4:
return 1
elif possible == -player * 4:
return -1
possible = 0
for i in range(4):
possible += jogo.board[i][i]
if possible == player * 4:
return 1
elif possible == -player * 4:
return -1
possible = 0
for i in range(4):
possible += jogo.board[i][3 - i]
if possible == player * 4:
return 1
elif possible == -player * 4:
return -1
return 0.0
def possible_wins(self, jogo, player):
"""
dado um jogador, retorna o número de jogadas possíveis com ganho
"""
n = 0
for i in range(0,4):
ally = 0
enemy = 0
empty = 0
for j in range(0, 4):
if jogo.board[i][j] == player:
ally += 1
elif jogo.board[i][j] == 0:
empty += 1
else:
enemy += 1
if ally == 4:
return np.inf
elif enemy == 4:
return -np.inf
if ally + empty == 4:
n += 1
elif enemy + empty == 4:
n -= 1
for i in range(0, 4):
ally = 0
enemy = 0
empty = 0
for j in range(0, 4):
if jogo.board[j][i] == player:
ally += 1
elif jogo.board[j][i] == 0:
empty += 1
else:
enemy += 1
if ally == 4:
return np.inf
elif enemy == 4:
return -np.inf
if ally + empty == 4:
n += ally
elif enemy + empty == 4:
n -= enemy
ally = 0
enemy = 0
empty = 0
for i in range(0, 4):
if jogo.board[i][i] == player:
ally += 1
elif jogo.board[i][i] == 0:
empty += 1
else:
enemy += 1
if ally == 4:
return np.inf
elif enemy == 4:
return -np.inf
if ally + empty == 4:
n += ally
elif enemy + empty == 4:
n -= enemy
ally = 0
enemy = 0
empty = 0
for i in range(0, 4):
if jogo.board[i][3 - i] == player:
ally += 1
elif jogo.board[i][3 - i] == 0:
empty += 1
else:
enemy += 1
if ally == 4:
return np.inf
elif enemy == 4:
return -np.inf
if ally + empty == 4:
n += ally
elif enemy + empty == 4:
n -= enemy
return n
def eval(self, jogo, player):
"""
Heuristica de avaliação.
"""
if player == 1:
if agent_type == 'MAX':
return self.possible_wins(jogo, 1) - self.possible_wins(jogo, -1)
else:
return self.possible_wins(jogo, -1) - self.possible_wins(jogo, 1)
else:
if agent_type == 'MAX':
return self.possible_wins(jogo, -1) - self.possible_wins(jogo, 1)
else:
return self.possible_wins(jogo, 1) - self.possible_wins(jogo, -1)
def minimax(self, state, depth, player):
self.nos_percorridos += 1
"""
Algoritmo minimax sem poda alfa beta
"""
if depth % 2 == 1: # depth ímpar
agent = 'MAX'
else:
agent = 'MIN' # depth par
#Nós terminais
if len(state.possible_plays) == 1 or depth == self.max_depth:
if agent == 'MAX':
max_v = (-1, -np.Inf)
for cell in state.possible_plays:
copia = copy.deepcopy(jogo)
copia.board[cell // 4][cell % 4] = player
copia.possible_plays.remove(cell)
heuristica = self.eval(copia, player)
if heuristica > max_v[1]:
max_v = (cell, heuristica, copia)
# print(max_v)
return max_v
else:
min_v = (-1, +np.Inf)
for cell in jogo.possible_plays:
copia = copy.deepcopy(jogo)
copia.board[(cell) // 4][(cell) % 4] = player
copia.possible_plays.remove(cell)
heuristica = self.eval(copia, player,'MIN')
if heuristica < min_v[1]:
min_v = (cell, heuristica, copia)
# print(min_v)
return min_v
#MAX
elif agent == 'MAX':
return self.max_value(state, depth, player)
#MIN
elif agent == 'MIN':
return self.min_value(state, depth, player)
def max_value(self, jogo: Board, depth, player):
'''
max value para minimax
'''
max_v = (-1, -np.inf, 0)
for cell in jogo.possible_plays:
copia = copy.deepcopy(jogo)
copia.board[(cell) // 4][(cell) % 4] = player
copia.possible_plays.remove(cell)
#heuristica = self.eval(copia, player)
max_v = self.maximo(max_v, self.minimax(copia, depth + 1, player))
return max_v
def min_value(self, jogo: Board, depth, player):
'''
min value para minimax
'''
min_v = (-1, +np.inf, 0)
for cell in jogo.possible_plays:
copia = copy.deepcopy(jogo)
copia.board[(cell) // 4][(cell) % 4] = -player
copia.possible_plays.remove(cell)
if self.win_state(copia, player) == -1:
return (cell, +np.inf, copia)
#heuristica = self.eval(copia, player)
min_v = self.minimo(min_v, self.minimax(copia, depth + 1, player))
return min_v
def alfa_beta(self, state: Board, depth: int, player : int, alpha = -np.Inf, beta = np.Inf):
self.nos_percorridos += 1
"""
minimax com poda alfa beta
"""
if depth % 2 == 1: # depth ímpar
agent = 'MAX'
else:
agent = 'MIN' # depth par
#nós terminais
if len(state.possible_plays) == 1 or depth == self.max_depth:
if agent == 'MAX':
max_v = (-1, -np.Inf)
for cell in state.possible_plays:
copia = copy.deepcopy(jogo)
copia.board[cell // 4][cell % 4] = player
copia.possible_plays.remove(cell)
heuristica = self.eval(copia, player, "MAX")
if heuristica > max_v[1]:
max_v = (cell, heuristica, copia)
# print(max_v)
return max_v
else:
min_v = (-1, +np.Inf)
for cell in jogo.possible_plays:
copia = copy.deepcopy(jogo)
copia.board[(cell) // 4][(cell) % 4] = -player
copia.possible_plays.remove(cell)
heuristica = self.eval(copia, player, "MAX")
if heuristica < min_v[1]:
min_v = (cell, heuristica, copia)
# print(min_v)
return min_v
#MAX
elif agent == 'MAX':
return self.max_value_ab(state, depth, player,alpha, beta)
#MIN
elif agent == 'MIN':
return self.min_value_ab(state, depth, player,alpha, beta)
def max_value_ab(self, jogo: Board, depth, player,alpha, beta):
'''
max value para minimax com poda alfa beta
'''
max_v = (-1, -np.inf, 0)
for cell in jogo.possible_plays:
copia = copy.deepcopy(jogo)
copia.board[(cell) // 4][(cell) % 4] = player
copia.possible_plays.remove(cell)
if self.win_state(copia, player) == 1:
return (cell, +np.inf, copia)
max_v = self.maximo(max_v, self.alfa_beta(copia, depth + 1, player,alpha, beta))
if max_v[1] >= beta:
return max_v
alpha = max(max_v[1], alpha)
return max_v
def min_value_ab(self, jogo: Board, depth, player,alpha, beta):
'''
min value para minimax com poda alfa beta
'''
min_v = (-1, +np.inf, 0)
for cell in jogo.possible_plays:
copia = copy.deepcopy(jogo)
copia.board[(cell) // 4][(cell) % 4] = -player
copia.possible_plays.remove(cell)
if self.win_state(copia, -player) == -1:
return (cell, -np.inf, copia)
min_v = self.minimo(min_v, self.alfa_beta(copia, depth + 1, player,alpha, beta))
if min_v[1] <= alpha:
return min_v
beta = min(beta, min_v[1])
return min_v
"""
Funções que comparam max para elementos especificos de tuplas e retornam a tupla desejada
"""
def maximo(self, tuple_v, heuristic):
if tuple_v[1] > heuristic[1]:
return tuple_v
else:
return heuristic
def minimo(self, tuple_v, heuristic):
if tuple_v[1] < heuristic[1]:
return tuple_v
else:
return heuristic
if __name__ == "__main__":
"""
#Instanciamento de variáveis
"""
jogo = Board()
n_jogadas = 0
modo = ""
"""
#Seleção do modo de jogo
"""
print("Selecione o modo de jogo:")
print("-Jogador Versus Máquina (1)")
print("-Máquina Versus Máquina (2)")
while True:
modo = input()
if modo in ["1", "2"]:
break
raise Exception("Selecione um modo válido")
if modo == "1":
jogador = Humano()
else:
jogador = Maquina(1, inteligenca_bots, max_depth=5)
"""
Início do jogo
"""
while True:
print()
jogo.render()
print()
# if modo == "MxM":
# time.sleep(1)
jogada = jogador.make_play(jogo)
jogo.count_play(jogada, 1)
if jogo.check_win():
print("JOGADOR 1 GANHOU")
break
if maquina.possible_wins(jogo, 1) == 0 and maquina.possible_wins(jogo, -1) == 0:
print("EMPATE")
break
# jogo.clean()
jogo.render()
print()
jogada = maquina.make_play(jogo)
jogo.count_play(jogada, -1)
if jogo.check_win():
print("JOGADOR 2 GANHOU")
break
if maquina.possible_wins(jogo, 1) == 0 and maquina.possible_wins(jogo, -1) == 0:
print("EMPATE")
break
# jogo.clean()
jogo.render()