-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.py
93 lines (88 loc) · 2.83 KB
/
state.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
import numpy as np
class State:
def __init__(self,board):
#print("state created")
self.board = board.copy()
self.playerID = self.evalID()
self.eval = self.evalBoard()
self.children = []
def generateChildren(self):
ans = []
board = self.board
playerID = self.evalID()
choices = np.nonzero(board == 0)
tempBoard = board.copy()
numChoices = len(choices[0])
for i in range(numChoices):
tempBoard = board.copy()
tempBoard[choices[0][i], choices[1][i]] = playerID
ans.append(State(tempBoard))
self.children = ans
def evalID(self):
board = self.board
if np.count_nonzero(board == 1) > np.count_nonzero(board == -1):
return -1
else:
return 1
def evalBoard(self):
board = self.board
playerID = self.playerID
ans = -50 if playerID != self.evalID() else 0
x2 = 0
x1 = 0
o2 = 0
o1 = 0
# rows
for row in board:
blanks = np.count_nonzero(row == 0)
enemy = np.count_nonzero(row == -1 )
ally = np.count_nonzero(row == 1)
if blanks == 2 and enemy == 1:
o1 +=1
elif blanks == 2 and ally == 1:
x1 +=1
elif blanks == 1 and enemy == 2:
o2 +=1
elif blanks == 1 and ally == 2:
x2 += 1
elif enemy == 3:
return -1000
elif ally == 3:
return 1000
# columns
for row in board.T:
blanks = np.count_nonzero(row == 0)
enemy = np.count_nonzero(row == -1 )
ally = np.count_nonzero(row == 1)
if blanks == 2 and enemy == 1:
o1 +=1
elif blanks == 2 and ally == 1:
x1 +=1
elif blanks == 1 and enemy == 2:
o2 +=1
elif blanks == 1 and ally == 2:
x2 += 1
elif enemy == 3:
return -1000
elif ally == 3:
return 1000
# northwest-diag
diags = [np.diag(board),np.diag(np.fliplr(board))]
for diag in diags:
blanks = np.count_nonzero(diag == 0)
enemy = np.count_nonzero(diag == -1)
ally = np.count_nonzero(diag == 1)
if blanks == 2 and enemy == 1:
o1 +=1
elif blanks == 2 and ally == 1:
x1 +=1
elif blanks == 1 and enemy == 2:
o2 +=1
elif blanks == 1 and ally == 2:
x2 += 1
elif enemy == 3:
return -1000
elif ally == 3:
return 1000
ans+= (3 * x2 + x1) - (3 * o2 + o1)
return ans