-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
253 lines (211 loc) · 7.55 KB
/
main.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
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
import re
from random import choice, shuffle
class Board:
def __init__(self):
self.width, self.height = 8, 8
self.black, self.white = 2, 2
self.board = [[" "] * self.height for row in range(self.width)]
self.board[3][3] = self.board[4][4] = "-"
self.board[3][4] = self.board[4][3] = "+"
self.onTurn = True # true if White (+), false if Black (-)
self.validMoves = []
self.moves = []
def __repr__(self) -> str:
ret = "──┬───┬───┬───┬───┬───┬───┬───┬───\n"
self.validMoves = []
for row in range(self.height - 1, -1, -1):
ret += str(row)
for col in range(self.width):
ret += " │ " + str(self.board[col][row])
ret += "\n──┼───┼───┼───┼───┼───┼───┼───┼───\n"
ret += " │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 \n"
return ret
def endTurn(self) -> None:
self.onTurn = not self.onTurn
def on_board(self, move: tuple) -> bool:
col, row = move
return (row >= 0) and (row < self.height) and (col >= 0) and (col < self.width)
def scan(self, position) -> list:
validDirections = []
if self.onTurn:
player = "+"
opponent = "-"
else:
player = "-"
opponent = "+"
directons = [
(-1, -1),
(-1, 0),
(-1, 1),
(0, -1),
(0, 1),
(1, -1),
(1, 0),
(1, 1),
]
for direction in directons:
dc, dr = direction
c, r = position
vals = ""
while 0 <= r < self.height and 0 <= c < self.width:
vals += str(self.board[c][r])
r += dr
c += dc
if re.search("^\s{1}" + "\{}+\{}".format(opponent, player), vals) != None:
validDirections.append(direction)
return validDirections
def isValidMove(self, move: tuple) -> bool:
if not (self.on_board(move)):
return False
c, r = move
if self.board[c][r] != " ":
return False
if len(self.scan(move)) == 0:
return False
return True
def makeMove(self, move: list) -> int:
move = [int(i) for i in move]
if self.onTurn:
opponent = "-"
else:
opponent = "+"
col, row = move
if self.on_board(move) and self.isValidMove(move):
validDirections = self.scan(move)
for direction in validDirections:
self.board[col][row] = "-" if self.onTurn else "+"
dc, dr = direction
c, r = move
while (
0 <= r < self.height
and 0 <= c < self.width
and self.board[c][r] == opponent
):
self.board[c][r] = "+" if self.onTurn else "-"
r += dr
c += dc
self.endTurn()
self.moves.append(move)
else:
print("Invalid Move!")
self.updateScore()
def unmakeMove(self) -> None:
self.board = [[" "] * self.height for row in range(self.width)]
self.board[3][3] = self.board[4][4] = "-"
self.board[3][4] = self.board[4][3] = "+"
self.onTurn = True
moves = self.moves[:-1]
self.moves = []
for move in moves:
self.makeMove(move)
self.updateScore()
def updateScore(self):
self.black = self.white = 0
for row in self.board:
for cell in row:
if cell == "+":
self.white += 1
elif cell == "-":
self.black += 1
return self.white / (self.black + self.white)
def checkWin(self) -> str:
self.updateScore()
if self.black + self.white == 64:
if self.white > self.black or self.black == 0:
return "White Wins! {} : {}".format(self.white, self.black)
elif self.black > self.white or self.white == 0:
return "Black Wins! {} : {}".format(self.black, self.white)
else:
return "Tie!"
else:
if len(self.getValidMoves()) == 0:
self.endTurn()
return "Game on"
def getValidMoves(self) -> list:
self.validMoves = []
for col in range(self.width):
for row in range(self.height):
if self.isValidMove((col, row)):
self.validMoves.append((col, row))
return self.validMoves
class AlphaBeta:
def __init__(self, depth=8):
self.game = Board()
self.depth = depth
# returns a move based on an alpha-beta search
def act(self):
move = self.search()
return move
# update the internal board state for the class
def feed(self, move):
self.game.makeMove(move)
# the root node of an alpha-beta search
def search(self):
print("AlphaBeta searching")
moves = self.game.getValidMoves()
if (len(moves) == 0):
self.game.endTurn
moves = self.game.getValidMoves()
if (len(moves) == 0):
return None
# a list to store the values associated with each move
scores = []
alpha = -10
for move in moves:
print(move, end="\r")
res = self.game.makeMove(move)
# if the move wins the game, play it immediately
if res:
self.game.unmakeMove()
return move
val = -self.alpha_beta(-10, -alpha, self.depth - 1)
self.game.unmakeMove()
scores.append((val, move))
# the algorithm randomises between moves that have the same value
shuffle(scores)
scores.sort(key=lambda x: -x[0])
print(scores)
print("\nAlphaBeta score: " + str(scores[0][0]))
return scores[0][1]
def alpha_beta(self, alpha, beta, depth):
if depth == 0:
corners = "".join([self.game.board[i][j] for i in (0,7) for j in (0,7)])
whiteInCorners = corners.count("+")
blackInCorners = corners.count("-")
return self.game.updateScore() + (2 * whiteInCorners) - (2 * blackInCorners)
moves = self.game.getValidMoves()
for move in moves:
self.game.makeMove(move)
val = -self.alpha_beta(-beta, -alpha, depth - 1)
self.game.unmakeMove()
# check for alpha node
if val >= alpha:
alpha = val
# check for beta cut
if val >= beta:
return val
return alpha
board = Board()
print(board)
player1 = AlphaBeta(depth=6)
while board.checkWin() == "Game on":
print(board)
print("Current score:", board.white, ":", board.black)
print("Valid moves: ", board.getValidMoves())
bestmove = player1.act()
if bestmove == None:
break
print(bestmove)
board.makeMove(bestmove)
player1.feed(bestmove)
end = board.checkWin()
if end != "Game on":
break
print(board)
print("Current score:", board.white, ":", board.black)
print("Valid moves: ", board.getValidMoves())
move = input("Move ({}): ".format("+" if board.onTurn else "-"))
move = move.strip().split(" ")
board.makeMove(move)
player1.feed(move)
print(board.white, ":", board.black)