-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.py
More file actions
686 lines (486 loc) · 17.4 KB
/
game.py
File metadata and controls
686 lines (486 loc) · 17.4 KB
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
import sys
import numpy as np
import random
import pygame
import math
import random
import numpy as np
from util import flipCoin, Counter
import math
BLUE = (0,0,255)
BLACK = (0,0,0)
RED = (255,0,0)
YELLOW = (255,255,0)
ROW_COUNT = 4
COLUMN_COUNT = 5
EMPTY = 0
WINDOW_LENGTH = 4
def get_state(board):
return tuple(map(tuple, board))
class Game():
# Criar jogo
def __init__(self):
self.board = np.zeros((ROW_COUNT, COLUMN_COUNT))
self.id1 = 1
self.id2 = 2
self.p1 = QLearnAgent(self, self.id1)
self.p2 = MinMaxAgent(self, self.id2, self.id1)
self.p3 = RandomAgent(self, self.id2)
def reset_board(self):
self.board = np.zeros((ROW_COUNT, COLUMN_COUNT))
def place_piece(self, row, col, piece):
self.board[row][col] = piece
def is_valid(self, board, col):
return board[ROW_COUNT-1][col] == 0
def get_next_open_row(self, board, col):
for r in range(ROW_COUNT):
if board[r][col] == 0:
return r
def print_board(self):
print(np.flip(self.board, 0))
def get_valid_locations(self, board):
valid_locations = []
for col in range(COLUMN_COUNT):
if self.is_valid(board, col):
valid_locations.append(col)
return valid_locations
def get_board(self):
return self.board
def is_terminal(self, board):
return self.winning_move(board, self.id1) or self.winning_move(board, self.id2) or len(self.get_valid_locations(board)) == 0
def evaluate_window(self, window, piece):
score = 0
opp_piece = self.id2
if piece == self.id2:
opp_piece = self.id1
if window.count(piece) == 4:
score += 100
elif window.count(piece) == 3 and window.count(EMPTY) == 1:
score += 5
elif window.count(piece) == 2 and window.count(EMPTY) == 2:
score += 2
if window.count(opp_piece) == 3 and window.count(EMPTY) == 1:
score -= 4
return score
def score_position(self, board, piece):
score = 0
## Score center column
center_array = [int(i) for i in list(board[:, COLUMN_COUNT//2])]
center_count = center_array.count(piece)
score += center_count * 3
## Score Horizontal
for r in range(ROW_COUNT):
row_array = [int(i) for i in list(board[r,:])]
for c in range(COLUMN_COUNT-3):
window = row_array[c:c+WINDOW_LENGTH]
score += self.evaluate_window(window, piece)
## Score Vertical
for c in range(COLUMN_COUNT):
col_array = [int(i) for i in list(board[:,c])]
for r in range(ROW_COUNT-3):
window = col_array[r:r+WINDOW_LENGTH]
score += self.evaluate_window(window, piece)
## Score posiive sloped diagonal
for r in range(ROW_COUNT-3):
for c in range(COLUMN_COUNT-3):
window = [board[r+i][c+i] for i in range(WINDOW_LENGTH)]
score += self.evaluate_window(window, piece)
for r in range(ROW_COUNT-3):
for c in range(COLUMN_COUNT-3):
window = [board[r+3-i][c+i] for i in range(WINDOW_LENGTH)]
score += self.evaluate_window(window, piece)
return score
def winning_move(self, board, piece):
# Check horizontal locations for win
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece:
return True
# Check vertical locations for win
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece:
return True
# Check positively sloped diaganols
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece:
return True
# Check negatively sloped diaganols
for c in range(COLUMN_COUNT-3):
for r in range(3, ROW_COUNT):
if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece:
return True
def draw_board(self, screen, SQUARESIZE, RADIUS, height):
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
pygame.draw.rect(screen, BLUE, (c*SQUARESIZE, r*SQUARESIZE+SQUARESIZE, SQUARESIZE, SQUARESIZE))
pygame.draw.circle(screen, BLACK, (int(c*SQUARESIZE+SQUARESIZE/2), int(r*SQUARESIZE+SQUARESIZE+SQUARESIZE/2)), RADIUS)
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
if self.board[r][c] == self.id1:
pygame.draw.circle(screen, RED, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
elif self.board[r][c] == self.id2:
pygame.draw.circle(screen, YELLOW, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
pygame.display.update()
def run_q_vs_minmax(self, graphics=False, name="tab_final"):
self.reset_board()
game_over = False
turn = random.randint(self.id1, self.id2)
winner_id = -1
episode_reward = 0
if graphics:
pygame.init()
SQUARESIZE = 100
width = COLUMN_COUNT * SQUARESIZE
height = (ROW_COUNT+1) * SQUARESIZE
size = (width, height)
RADIUS = int(SQUARESIZE/2 - 5)
screen = pygame.display.set_mode(size)
self.draw_board(screen, SQUARESIZE, RADIUS, height)
pygame.display.update()
myfont = pygame.font.SysFont("monospace", 50)
state = None
next_state = None
action = None
while not game_over:
reward = 0
# Q-Learn
if turn == self.id1:
state = get_state(self.board) # Estado anterior da ação
col = self.p1.choose_move(self.board)
if self.is_valid(self.board, col):
row = self.get_next_open_row(self.board, col)
self.place_piece(row, col, self.id1)
action = col # A coluna representa a ação
if self.winning_move(self.board, self.id1):
reward = 1 # Recompensa para vitória
game_over = True
winner_id = self.id1
if graphics:
label = myfont.render("Q-Learn wins!!", 1, RED)
screen.blit(label, (20, 10))
# Se vencer, atualizar com base nisso
# state - anterior // action - col // next_state - estado após(0.0?) //
next_state = get_state(self.board) # Como esse estado nunca será atualizado, seu Q-Value é 0.0
self.p1.process_move(state, action, next_state, reward)
# Se não vencer, atualizar na iteração - 3 situações (se perdeu // se deu empate // se continua)
if graphics:
# self.print_board()
self.draw_board(screen, SQUARESIZE, RADIUS, height)
turn = self.id2
# MinMax
elif turn == self.id2:
col = self.p2.choose_move()
if self.is_valid(self.board, col):
row = self.get_next_open_row(self.board, col)
self.place_piece(row, col, self.id2)
if self.winning_move(self.board, self.id2):
reward = -2 # Penalidade para derrota do Q-Learn
game_over = True
winner_id = self.id2
if graphics:
label = myfont.render("MinMax wins!!", 1, YELLOW)
screen.blit(label, (20, 10))
if graphics:
# self.print_board()
self.draw_board(screen, SQUARESIZE, RADIUS, height)
if state is not None:
next_state = get_state(self.board)
turn = self.id1
if self.is_terminal(self.board):
game_over = True
if winner_id == -1:
reward = -1 # Penalidade para empate
next_state = get_state(self.board)
if state is not None and next_state is not None:
self.p1.process_move(state, action, next_state, reward)
if game_over and graphics:
# Salvar resultado da imagem
file_name = f"{name}-w{winner_id}.jpg"
pygame.image.save(screen, file_name)
pygame.time.wait(2000)
episode_reward += reward
# print('Cheguei aqui')
if graphics:
self.print_board()
return winner_id, episode_reward
def run_q_vs_random(self, graphics=False, name="tab_final"):
self.reset_board()
game_over = False
turn = 1
winner_id = -1
episode_reward = 0
if graphics:
pygame.init()
SQUARESIZE = 100
width = COLUMN_COUNT * SQUARESIZE
height = (ROW_COUNT+1) * SQUARESIZE
size = (width, height)
RADIUS = int(SQUARESIZE/2 - 5)
screen = pygame.display.set_mode(size)
self.draw_board(screen, SQUARESIZE, RADIUS, height)
pygame.display.update()
myfont = pygame.font.SysFont("monospace", 50)
state = None
next_state = None
action = None
while not game_over:
reward = 0
# Q-Learn
if turn == self.id1:
state = get_state(self.board) # Estado anterior da ação
col = self.p1.choose_move(self.board)
if self.is_valid(self.board, col):
row = self.get_next_open_row(self.board, col)
self.place_piece(row, col, self.id1)
action = col # A coluna representa a ação
if self.winning_move(self.board, self.id1):
reward = 1 # Recompensa para vitória
game_over = True
winner_id = self.id1
if graphics:
label = myfont.render("Q-Learn wins!!", 1, RED)
screen.blit(label, (20, 10))
# Se vencer, atualizar com base nisso
# state - anterior // action - col // next_state - estado após(0.0?) //
next_state = get_state(self.board) # Como esse estado nunca será atualizado, seu Q-Value é 0.0
self.p1.process_move(state, action, next_state, reward)
# Se não vencer, atualizar na iteração - 3 situações (se perdeu // se deu empate // se continua)
if graphics:
# self.print_board()
self.draw_board(screen, SQUARESIZE, RADIUS, height)
turn = self.id2
# Random
elif turn == self.id2:
col = self.p3.choose_move(self.board)
if self.is_valid(self.board, col):
row = self.get_next_open_row(self.board, col)
self.place_piece(row, col, self.id2)
if self.winning_move(self.board, self.id2):
reward = -2 # Penalidade para derrota do Q-Learn
game_over = True
winner_id = self.id2
if graphics:
label = myfont.render("Random wins!!", 1, YELLOW)
screen.blit(label, (20, 10))
if graphics:
# self.print_board()
self.draw_board(screen, SQUARESIZE, RADIUS, height)
if state is not None:
next_state = get_state(self.board)
turn = self.id1
if self.is_terminal(self.board):
game_over = True
if winner_id == -1:
reward = -1 # Penalidade para empate
next_state = get_state(self.board)
if state is not None and next_state is not None:
self.p1.process_move(state, action, next_state, reward)
if game_over and graphics:
# Salvar resultado da imagem
file_name = f"{name}-w{winner_id}.jpg"
pygame.image.save(screen, file_name)
pygame.time.wait(2000)
episode_reward += reward
# print('Cheguei aqui')
if graphics:
self.print_board()
return winner_id, episode_reward
def run_q_vs_human(self):
graphics = True
self.reset_board()
game_over = False
turn = 1
winner_id = -1
if graphics:
pygame.init()
SQUARESIZE = 100
width = COLUMN_COUNT * SQUARESIZE
height = (ROW_COUNT+1) * SQUARESIZE
size = (width, height)
RADIUS = int(SQUARESIZE/2 - 5)
screen = pygame.display.set_mode(size)
self.draw_board(screen, SQUARESIZE, RADIUS, height)
pygame.display.update()
myfont = pygame.font.SysFont("monospace", 50)
state = None
next_state = None
action = None
while not game_over:
reward = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEMOTION:
pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE))
posx = event.pos[0]
if turn == self.id2:
pygame.draw.circle(screen, YELLOW, (posx, int(SQUARESIZE/2)), RADIUS)
pygame.display.update()
if event.type == pygame.MOUSEBUTTONDOWN:
pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE))
#print(event.pos)
# Ask for Player 1 Input
if turn == self.id2:
posx = event.pos[0]
col = int(math.floor(posx/SQUARESIZE))
if self.is_valid(self.board, col):
row = self.get_next_open_row(self.board, col)
self.place_piece(row, col, self.id2)
if self.winning_move(self.board, self.id2):
label = myfont.render("Human wins!!", 1, YELLOW)
screen.blit(label, (20,10))
reward = -5 # Penalidade para derrota do Q-Learn
game_over = True
winner_id = self.id2
turn = self.id1
# self.print_board()
self.draw_board(screen, SQUARESIZE, RADIUS, height)
# Q-Learn
if turn == self.id1:
state = get_state(self.board) # Estado anterior da ação
col = self.p1.choose_move(self.board)
if self.is_valid(self.board, col):
row = self.get_next_open_row(self.board, col)
self.place_piece(row, col, self.id1)
action = col # A coluna representa a ação
if self.winning_move(self.board, self.id1):
reward = 2 # Recompensa para vitória
game_over = True
winner_id = self.id1
if graphics:
label = myfont.render("Q-Learn wins!!", 1, RED)
screen.blit(label, (20, 10))
# Se vencer, atualizar com base nisso
# state - anterior // action - col // next_state - estado após(0.0?) //
next_state = get_state(self.board) # Como esse estado nunca será atualizado, seu Q-Value é 0.0
self.p1.process_move(state, action, next_state, reward)
# Se não vencer, atualizar na iteração - 3 situações (se perdeu // se deu empate // se continua)
if graphics:
self.print_board()
self.draw_board(screen, SQUARESIZE, RADIUS, height)
turn = self.id2
if self.is_terminal(self.board):
game_over = True
if winner_id == -1:
reward = -20 # Penalidade para empate
next_state = get_state(self.board)
if state is not None and next_state is not None:
self.p1.process_move(state, action, next_state, reward)
if game_over and graphics:
pygame.time.wait(2000)
# print('Cheguei aqui')
self.print_board()
return winner_id
###################################################################################################################
###################################################################################################################
###################################################################################################################
class Player():
def __init__(self, game:Game, id):
self.game = game
self.id = int(id)
def choose_move(self):
pass
def process_move(self):
pass
""" UM STATE DO AGENTE REPRESENTA O MOMENTO APÓS O OPONENTE COLOCOU A PEÇA E DEVE O EFEITO QUE COLOCAR A PEÇA VAI FAZER """
class QLearnAgent(Player):
def __init__(self, game, id, alpha=0.2, gamma=0.95, epsilon=0.1):
super().__init__(game, id)
self.alpha = float(alpha)
self.gamma = float(gamma)
self.epsilon = float(epsilon)
self.q_table = Counter()
def choose_move(self, board):
state = get_state(board)
actions = self.game.get_valid_locations(board)
if flipCoin(self.epsilon):
action = random.choice(actions)
else:
action = self.best_action(state)
return action
def process_move(self, state, action, nextState, reward):
# Atualiza o valor de Q
amostra = reward + self.gamma*self.getValue(nextState)
newQVal = (1 - self.alpha) * self.getQValue(state, action) + self.alpha*amostra
self.q_table[state, action] = newQVal
# print("Atualizei")
def best_action(self, state):
maxValue = self.getValue(state)
actions = self.game.get_valid_locations(self.game.board)
for action in actions:
if maxValue == self.getQValue(state, action):
return action
def getValue(self, state):
actions = self.game.get_valid_locations(self.game.board)
all_q_values = []
# Para cada possivel acao do oponente
for action in actions:
all_q_values.append(self.getQValue(state, action))
# Para cada acao a partir de um estado
if len(all_q_values) > 0:
return max(all_q_values)
return 0.0
def getQValue(self, state, action):
return self.q_table[(state, action)]
def printQ(self):
print(self.q_table)
class MinMaxAgent(Player):
def __init__(self, game: Game, id, oppId):
super().__init__(game, id)
self.oppId = int(oppId)
def choose_move(self):
col, _ = self.minmax(self.game.board, 5, -math.inf, math.inf, True)
return col
def minmax(self, board, depth, alpha, beta, maximizingOpp):
valid_locations = self.game.get_valid_locations(board)
is_terminal = self.game.is_terminal(board)
if depth==0 or is_terminal:
if is_terminal:
if self.game.winning_move(board, self.id):
return (None, 100000000000000)
elif self.game.winning_move(board, self.oppId):
return (None, -10000000000000)
else:
return (None, 0)
else:
return (None, self.game.score_position(board, self.id))
if maximizingOpp:
value = -math.inf
column = random.choice(valid_locations)
for col in valid_locations:
row = self.game.get_next_open_row(board, col)
b_copy = board.copy()
b_copy[row][col] = self.id
new_score = self.minmax(b_copy, depth-1, alpha, beta, False)[1]
if new_score > value:
value = new_score
column = col
alpha = max(alpha, value)
if alpha >= beta:
break
return column, value
else:
value = math.inf
column = random.choice(valid_locations)
for col in valid_locations:
row = self.game.get_next_open_row(board, col)
b_copy = board.copy()
b_copy[row][col] = self.oppId
new_score = self.minmax(b_copy, depth-1, alpha, beta, True)[1]
if new_score < value:
value = new_score
column = col
beta = min(beta, value)
if alpha >= beta:
break
return column, value
class RandomAgent(Player):
def __init__(self, game: Game, id):
super().__init__(game, id)
def choose_move(self, board):
# Pegar uma posição aleatória válida
actions = self.game.get_valid_locations(board)
action = random.choice(actions)
return action