-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpu.py
67 lines (63 loc) · 2.58 KB
/
cpu.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
import game_functions as gf
def calculate_utility(player):
return 22 - player.get_laid_stones()
def cpu_min_max_algorithm(game, own, opponent):
heuristic_ordering = gf.heuristic_ordering(game.size_horizontal)
value, move = max_value(game, own, opponent, float("-inf"), float("inf"), heuristic_ordering)
return value, move
def max_value(game, own, opponent, alpha, beta, heuristic_ordering):
if game.victory(own, opponent, printing = False):
utility = - calculate_utility(opponent)
return (utility, None)
if game.draw(printing = False):
return (0, None)
max_val = float("-inf")
for column in heuristic_ordering:
if column not in game.board.get_free_columns():
continue
row = game.board.check_row(column)
if row == 0:
game.board.remove_free_column(column)
game.board.change_character(own.character, row, column)
own.increase_laid_stones()
value2, action2 = min_value(game, opponent, own, alpha, beta, heuristic_ordering)
#Restore (backtrack)
own.decrease_laid_stones()
game.board.change_character('.', row, column)
if row == 0:
game.board.add_free_column(column)
if value2 > max_val:
max_val = value2
move = column
alpha = max(alpha, max_val)
if max_val >= beta:
return max_val, move
return max_val, move
def min_value(game, own, opponent, alpha, beta, heuristic_ordering):
if game.victory(own, opponent, printing = False):
utility = calculate_utility(opponent)
return (utility, None)
if game.draw(printing = False):
return (0, None)
min_val = float("inf")
for column in gf.heuristic_ordering(game.size_horizontal):
if column not in game.board.get_free_columns():
continue
row = game.board.check_row(column)
if row == 0:
game.board.remove_free_column(column)
game.board.change_character(own.character, row, column)
own.increase_laid_stones()
value2, action2 = max_value(game, opponent, own, alpha, beta, heuristic_ordering)
#Restore (backtrack)
own.decrease_laid_stones()
game.board.change_character('.', row, column)
if row == 0:
game.board.add_free_column(column)
if value2 < min_val:
min_val = value2
move = column
beta = min(beta, min_val)
if min_val <= alpha:
return min_val, move
return min_val, move