-
Notifications
You must be signed in to change notification settings - Fork 1
/
nega.py
55 lines (46 loc) · 945 Bytes
/
nega.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
import itertools
import random
"""
Lo = [-1, 4, -3, -2, 0 ,2, 3, -4, 1]
b = dict(zip(Lo, [0]*9))
b = {-4: 1, -3: 0, -2: -1, -1: 0, 0: 1, 1: 0, 2: 0, 3: -1, 4: 0}
"""
def c(b):
for s in [1, -1]:
l = [k for k, v in b.items() if v == s]
l = list(itertools.combinations(l, 3))
if len(l) > 0:
for i in l:
if sum(i) == 0:
return [-1, 1][s == 1]
return 0
def negamax(b, α, β, t, Lo):
w = c(b)
if w != 0:
return t * w
if 0 not in b.values():
return 0
r = -2
for m in Lo:
if b[m] == 0:
b[m] = t
v = -negamax(b, -β, -α, -t, Lo)
b[m] = 0
r = max([r, v])
α = max([α, v])
if α >= β:
break
return r
def best_move(b,Lo):
lk = []
lv = []
for m in Lo:
if b[m] == 0:
b[m] = 1
v = -negamax(b, -2, 2, -1, Lo)
b[m] = 0
lk.append(m)
lv.append(v)
m = max(lv)
l = dict(zip(lk, lv))
return random.choice([k for k, v in l.items() if v == m])