-
Notifications
You must be signed in to change notification settings - Fork 0
/
expectimax_algorithm.py
50 lines (44 loc) · 1.73 KB
/
expectimax_algorithm.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
import evaluation_functions
import pygame2048
class AI:
def __init__(self):
self.monotonicity_weight = 50
self.empty_weight = 300
self.merges_weight = 1000
self.total_weight = 10
def evaluate_board(self, grid_):
utility = 0
monotonicity = evaluation_functions.monotonicity(grid_)
empty_merges_total = evaluation_functions.total_empty_and_merges(grid_)
utility += monotonicity * self.monotonicity_weight
utility += empty_merges_total[0] * self.empty_weight
utility += empty_merges_total[1] * self.merges_weight
utility += empty_merges_total[2] * self.total_weight
return utility
def maximise(self, grid_, depth=0):
utilities = []
grids = [pygame2048.left(grid_), pygame2048.right(grid_), pygame2048.up(grid_), pygame2048.down(grid_)]
for _ in grids:
utilities.append(self.chance(_, depth + 1))
if depth == 0:
return utilities
else:
return max(utilities)
def chance(self, grid_, depth):
average_utility = 0
probabilities = evaluation_functions.probabilities(grid_)
if probabilities:
if depth >= 4:
for _ in probabilities:
average_utility += self.evaluate_board(_[0]) * _[1]
return average_utility
for _ in probabilities:
average_utility += _[1] * self.maximise(_[0], depth + 1)
return average_utility
else:
return self.evaluate_board(grid_)
def get_best_move(self, grid_):
moves = ['LEFT', 'RIGHT', 'UP', 'DOWN']
array_ = self.maximise(grid_)
index = array_.index(max(array_))
return moves[index]