-
Notifications
You must be signed in to change notification settings - Fork 0
/
MCTS_example.py
555 lines (466 loc) · 20.1 KB
/
MCTS_example.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# This is a very simple implementation of the UCT Monte Carlo Tree Search algorithm in Python 3.6
# The function UCT(rootstate, itermax, verbose = False) is towards the bottom of the code.
# It aims to have the clearest and simplest possible code, and for the sake of clarity, the code
# is orders of magnitude less efficient than it could be made, particularly by using a
# state.GetRandomMove() or state.DoRandomRollout() function.
#
# Example GameState classes for Nim, OXO and Othello are included to give some idea of how you
# can write your own GameState use UCT in your 2-player game. Change the game to be played in
# the UCTPlayGame() function at the bottom of the code.
#
# Written by Peter Cowling, Ed Powley, Daniel Whitehouse (University of York, UK) September 2012.
#
# Licence is granted to freely use and distribute for any sensible/legal purpose so long as this comment
# remains in any distributed code.
#
# For more information about Monte Carlo Tree Search check out our web site at www.mcts.ai
from math import *
import random
class GameState:
""" A state of the game, i.e. the game board. These are the only functions which are
absolutely necessary to implement UCT in any 2-player complete information deterministic
zero-sum game, although they can be enhanced and made quicker, for example by using a
GetRandomMove() function to generate a random move during rollout.
By convention the players are numbered 1 and 2.
"""
def __init__(self):
self.playerJustMoved = 2 # At the root pretend the player just moved is player 2 - player 1 has the first move
def Clone(self):
""" Create a deep clone of this game state.
"""
st = GameState()
st.playerJustMoved = self.playerJustMoved
return st
def DoMove(self, move):
""" Update a state by carrying out the given move.
Must update playerJustMoved.
"""
self.playerJustMoved = 3 - self.playerJustMoved
def GetMoves(self):
""" Get all possible moves from this state.
"""
def GetResult(self, playerjm):
""" Get the game result from the viewpoint of playerjm.
"""
def __repr__(self):
""" Don't need this - but good style.
"""
pass
class GomokuState:
"""
A state of game Gomoku
"""
def __init__(self, boardSize=12):
self.size = boardSize
self.playerJustMoved = 2
self.board = []
self.pieceJustMoved = [0, 0]
assert boardSize == int(boardSize)
for y in range(boardSize):
self.board.append([0] * boardSize)
def Clone(self):
""" Make a deep clone of the game state.
"""
st = GomokuState()
st.playerJustMoved = self.playerJustMoved
st.board = [self.board[i][:] for i in range(self.size)]
st.size = self.size
st.pieceJustMoved = self.pieceJustMoved[:]
return st
def DoMove(self, move):
"""
make a move.
:param move:
:return:
"""
# assert
(x, y) = (move[0], move[1])
assert x == int(x) and y == int(y) and self.IsOnBoard(x, y) and self.board[x][y] == 0
self.playerJustMoved = 3 - self.playerJustMoved
self.board[x][y] = self.playerJustMoved
(self.pieceJustMoved[0], self.pieceJustMoved[1]) = (move[0], move[1])
def GetMoves(self):
"""
Get all possible moves from this state.
:return:
"""
return [(x, y) for x in range(self.size) for y in range(self.size) if
self.board[x][y] == 0]
# comment the sandwich check below...
# return [i for i in range(self.boardSize * self.boardSize) if self.board[i] == 0]
def GetResult(self, playerJm):
"""
:param playerjm:
:return: Get the result from the playerjm
"""
(m, n) = (self.pieceJustMoved[0], self.pieceJustMoved[1])
#print (self.playerJustMoved)
count = 1
for (p, q) in [(-1, 0), (-1, -1), (0, 1), (1, 1)]:
count = 1
advtg = 0
step = 1
# and (m + step * p) < self.size
while (m + step * p) < self.size\
and (m + step * p) >= 0 \
and (n + step * q) < self.size \
and (n + step * q) >= 0:
if self.board[m + step * p][n + step * q] == self.playerJustMoved:
count += 1
elif self.board[m + step * p][n + step * q] == 0:
advtg += 1
break
else:
break
step += 1
step = -1
# and (m + step * p)>= 0\
while (m + step * p)<self.size\
and (n + step * q) < self.size\
and (n + step * q)>=0 \
and (m + step * p)>= 0:
if self.board[m + step * p][n + step * q] == self.playerJustMoved:
count += 1
if self.board[m + step * p][n + step * q] == 0:
count += advtg
break
else:
break
step -= 1
if count >= 5:
#print("winner ", count)
return 1.0
if self.GetMoves()==[]:
return 0.5
return
def IsOnBoard(self, x, y):
return x >= 0 and x < self.size and y >= 0 and y < self.size
def __repr__(self):
s = ""
for y in range(self.size - 1, -1, -1):
for x in range(self.size):
s += [" .", " X"," O"][self.board[x][y]]
s += "\n"
return s
class NimState:
""" A state of the game Nim. In Nim, players alternately take 1,2 or 3 chips with the
winner being the player to take the last chip.
In Nim any initial state of the form 4n+k for k = 1,2,3 is a win for player 1
(by choosing k) chips.
Any initial state of the form 4n is a win for player 2.
Introduction of Nim on wiki:
https://en.wikipedia.org/wiki/Nim
"""
def __init__(self, ch):
self.playerJustMoved = 2 # At the root pretend the player just moved is p2 - p1 has the first move
self.chips = ch
def Clone(self):
""" Create a deep clone of this game state.
"""
st = NimState(self.chips)
st.playerJustMoved = self.playerJustMoved
return st
def DoMove(self, move):
""" Update a state by carrying out the given move.
Must update playerJustMoved.
"""
assert move >= 1 and move <= 3 and move == int(move)
self.chips -= move
self.playerJustMoved = 3 - self.playerJustMoved
def GetMoves(self):
""" Get all possible moves from this state.
"""
return list(range(1, min([4, self.chips + 1])))
def GetResult(self, playerjm):
""" Get the game result from the viewpoint of playerjm.
"""
assert self.chips == 0
if self.playerJustMoved == playerjm:
return 1.0 # playerjm took the last chip and has won
else:
return 0.0 # playerjm's opponent took the last chip and has won
def __repr__(self):
s = "Chips:" + str(self.chips) + " JustPlayed:" + str(self.playerJustMoved)
return s
class OXOState:
""" A state of the OXOgame(圈圈叉叉), i.e. the game board.
Squares in the board are in this arrangement
012
345
678
where 0 = empty, 1 = player 1 (X), 2 = player 2 (O)
"""
def __init__(self):
self.playerJustMoved = 2 # At the root pretend the player just moved is p2 - p1 has the first move
self.board = [0, 0, 0, 0, 0, 0, 0, 0, 0] # 0 = empty, 1 = player 1, 2 = player 2
def Clone(self):
""" Create a deep clone of this game state.
"""
st = OXOState()
st.playerJustMoved = self.playerJustMoved
st.board = self.board[:]
return st
def DoMove(self, move):
""" Update a state by carrying out the given move.
Must update playerToMove.
"""
assert move >= 0 and move <= 8 and move == int(move) and self.board[move] == 0
self.playerJustMoved = 3 - self.playerJustMoved
self.board[move] = self.playerJustMoved
def GetMoves(self):
""" Get all possible moves from this state.
"""
return [i for i in range(9) if self.board[i] == 0]
def GetResult(self, playerjm):
""" Get the game result from the viewpoint of playerjm.
"""
for (x, y, z) in [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]:
if self.board[x] == self.board[y] == self.board[z]:
if self.board[x] == 0:
return
elif self.board[x] == playerjm:
#print("ops")
return 1.0
else :
return 0.0
if self.GetMoves() == []:
return 0.5 # draw
#assert False # Should not be possible to get here
def __repr__(self):
s = ""
for i in range(9):
s += ".XO"[self.board[i]]
if i % 3 == 2: s += "\n"
return s
class OthelloState:
""" A state of the game of Othello(黑白棋), i.e. the game board.
The board is a 2D array where 0 = empty (.), 1 = player 1 (X), 2 = player 2 (O).
In Othello players alternately place pieces on a square board - each piece played
has to sandwich opponent pieces between the piece played and pieces already on the
board. Sandwiched pieces are flipped.
This implementation modifies the rules to allow variable sized square boards and
terminates the game as soon as the player about to move cannot make a move (whereas
the standard game allows for a pass move).
"""
def __init__(self, sz=8):
self.playerJustMoved = 2 # At the root pretend the player just moved is p2 - p1 has the first move
self.board = [] # 0 = empty, 1 = player 1, 2 = player 2
self.size = sz
assert sz == int(sz) and sz % 2 == 0 # size must be integral and even
for y in range(sz):
self.board.append([0] * sz)
# initial the board chess pieces.
self.board[sz // 2][sz // 2] = self.board[sz // 2 - 1][sz // 2 - 1] = 1
self.board[sz // 2][sz // 2 - 1] = self.board[sz // 2 - 1][sz // 2] = 2
def Clone(self):
""" Create a deep clone of this game state.
"""
st = OthelloState()
st.playerJustMoved = self.playerJustMoved
st.board = [self.board[i][:] for i in range(self.size)]
st.size = self.size
return st
def DoMove(self, move):
""" Update a state by carrying out the given move.
Must update playerToMove.
"""
(x, y) = (move[0], move[1])
assert x == int(x) and y == int(y) and self.IsOnBoard(x, y) and self.board[x][y] == 0
m = self.GetAllSandwichedCounters(x, y)
self.playerJustMoved = 3 - self.playerJustMoved
self.board[x][y] = self.playerJustMoved
for (a, b) in m:
self.board[a][b] = self.playerJustMoved
def GetMoves(self):
""" Get all possible moves from this state.
"""
return [(x, y) for x in range(self.size) for y in range(self.size) if
self.board[x][y] == 0 and self.ExistsSandwichedCounter(x, y)]
def AdjacentToEnemy(self, x, y):
""" Speeds up GetMoves by only considering squares which are adjacent to an enemy-occupied square.
"""
for (dx, dy) in [(0, +1), (+1, +1), (+1, 0), (+1, -1), (0, -1), (-1, -1), (-1, 0), (-1, +1)]:
if self.IsOnBoard(x + dx, y + dy) and self.board[x + dx][y + dy] == self.playerJustMoved:
return True
return False
def AdjacentEnemyDirections(self, x, y):
""" Speeds up GetMoves by only considering squares which are adjacent to an enemy-occupied square.
"""
es = []
for (dx, dy) in [(0, +1), (+1, +1), (+1, 0), (+1, -1), (0, -1), (-1, -1), (-1, 0), (-1, +1)]:
if self.IsOnBoard(x + dx, y + dy) and self.board[x + dx][y + dy] == self.playerJustMoved:
es.append((dx, dy))
return es
def ExistsSandwichedCounter(self, x, y):
""" Does there exist at least one counter which would be flipped if my counter was placed at (x,y)?
"""
for (dx, dy) in self.AdjacentEnemyDirections(x, y):
if len(self.SandwichedCounters(x, y, dx, dy)) > 0:
return True
return False
def GetAllSandwichedCounters(self, x, y):
""" Is (x,y) a possible move (i.e. opponent counters are sandwiched between (x,y) and my counter in some direction)?
"""
sandwiched = []
for (dx, dy) in self.AdjacentEnemyDirections(x, y):
sandwiched.extend(self.SandwichedCounters(x, y, dx, dy))
return sandwiched
def SandwichedCounters(self, x, y, dx, dy):
""" Return the coordinates of all opponent counters sandwiched between (x,y) and my counter.
"""
x += dx
y += dy
sandwiched = []
while self.IsOnBoard(x, y) and self.board[x][y] == self.playerJustMoved:
sandwiched.append((x, y))
x += dx
y += dy
if self.IsOnBoard(x, y) and self.board[x][y] == 3 - self.playerJustMoved:
return sandwiched
else:
return [] # nothing sandwiched
def IsOnBoard(self, x, y):
return x >= 0 and x < self.size and y >= 0 and y < self.size
def GetResult(self, playerjm):
""" Get the game result from the viewpoint of playerjm.
"""
jmcount = len([(x, y) for x in range(self.size) for y in range(self.size) if self.board[x][y] == playerjm])
notjmcount = len(
[(x, y) for x in range(self.size) for y in range(self.size) if self.board[x][y] == 3 - playerjm])
if jmcount > notjmcount:
return 1.0
elif notjmcount > jmcount:
return 0.0
else:
return 0.5 # draw
def __repr__(self):
s = ""
for y in range(self.size - 1, -1, -1):
for x in range(self.size):
s += ".XO"[self.board[x][y]]
s += "\n"
return s
class Node:
""" A node in the game tree. Note wins is always from the viewpoint of playerJustMoved.
Crashes if state not specified.
"""
def __init__(self, move=None, parent=None, state=None):
self.move = move # the move that got us to this node - "None" for the root node
self.parentNode = parent # "None" for the root node
self.childNodes = []
self.wins = 0
self.visits = 0
self.untriedMoves = state.GetMoves() # future child nodes
self.playerJustMoved = state.playerJustMoved # the only part of the state that the Node needs later
def UCTSelectChild(self):
""" Use the UCB1 formula to select a child node. Often a constant UCTK is applied so we have
lambda c: c.wins/c.visits + UCTK * sqrt(2*log(self.visits)/c.visits to vary the amount of
exploration versus exploitation.
"""
s = sorted(self.childNodes, key=lambda c: c.wins / c.visits + sqrt(2 * log(self.visits) / c.visits))[-1]
return s
def AddChild(self, m, s):
""" Remove m from untriedMoves and add a new child node for this move.
Return the added child node
"""
n = Node(move=m, parent=self, state=s)
self.untriedMoves.remove(m)
self.childNodes.append(n)
return n
def Update(self, result):
""" Update this node - one additional visit and result additional wins. result must be from the viewpoint of playerJustmoved.
"""
self.visits += 1
self.wins += result
def __repr__(self):
return "[M:" + str(self.move) + " W/V:" + str(self.wins) + "/" + str(self.visits) + " U:" + str(
self.untriedMoves) + "]"
def TreeToString(self, indent):
s = self.IndentString(indent) + str(self)
for c in self.childNodes:
s += c.TreeToString(indent + 1)
return s
def IndentString(self, indent):
s = "\n"
for i in range(1, indent + 1):
s += "| "
return s
def ChildrenToString(self):
s = ""
for c in self.childNodes:
s += str(c) + "\n"
return s
def UCT(rootstate, itermax, verbose=False):
""" Conduct a UCT search for itermax iterations starting from rootstate.
Return the best move from the rootstate.
Assumes 2 alternating players (player 1 starts), with game results in the range [0.0, 1.0]."""
rootnode = Node(state=rootstate)
for i in range(itermax):
node = rootnode
state = rootstate.Clone()
# Select
while node.untriedMoves == [] and node.childNodes != []: # node is fully expanded and non-terminal
node = node.UCTSelectChild()
state.DoMove(node.move)
# Expand
if node.untriedMoves != []: # if we can expand (i.e. state/node is non-terminal)
m = random.choice(node.untriedMoves)
state.DoMove(m)
node = node.AddChild(m, state) # add child and descend tree
# Rollout - this can often be made orders of magnitude quicker using a state.GetRandomMove() function
while state.GetMoves() != []: # while state is non-terminal
#while state.GetResult(state) != []: # while state is non-terminal
state.DoMove(random.choice(state.GetMoves()))
if state.GetResult(state.playerJustMoved)!= None: #added 11.01
break
# choose random step...
# Backpropagate
while node != None: # backpropagate from the expanded node and work back to the root node
node.Update(state.GetResult(
node.playerJustMoved)) # state is terminal. Update node with result from POV of node.playerJustMoved
node = node.parentNode
# Output some information about the tree - can be omitted
if (verbose):
print(rootnode.TreeToString(0))
else:
print(rootnode.ChildrenToString())
return sorted(rootnode.childNodes, key=lambda c: c.visits)[-1].move # return the move that was most visited
def UCTPlayGame():
""" Play a sample game between two UCT players where each player gets a different number
of UCT iterations (= simulations = tree nodes).
"""
# state = OthelloState(4) # uncomment to play Othello on a square board of the given size
#state = OXOState() # uncomment to play OXO
#這邊可以選要玩啥遊戲
# state = OthelloState(8) # uncomment to play Nim with the given number of starting chips
state = GomokuState(12)
while (state.GetMoves() != []):
#while state.GetResult(state.playerJustMoved) ==[]:
print(str(state))
if state.playerJustMoved == 1:
m = UCT(rootstate=state, itermax=1000, verbose=False) # play with values for itermax and verbose = True
else:
m = UCT(rootstate=state, itermax=100, verbose=False)
print("Best Move: " + str(m))
#elif state.GetResult(state.playerJustMoved) == []:
#CHANGED THE PJM TO OPPOSITE ONE
state.DoMove(m)
if state.GetResult(state.playerJustMoved) == 1.0:
print("Player " + str(state.playerJustMoved) + " wins!")
return
elif state.GetResult(state.playerJustMoved) == 0.0:
print("Player " + str(3-state.playerJustMoved) + " wins!")
return
elif state.GetResult(state.playerJustMoved) == 0.5:
print("Nobody wins!")
return
# if state.GetResult(state.playerJustMoved) == 1.0:
# print("Player " + str(state.playerJustMoved) + " wins!")
# elif state.GetResult(state.playerJustMoved) == 0.0:
# print("Player " + str(3 - state.playerJustMoved) + " wins!")
# if state.GetResult(state.playerJustMoved) == 0.5:
# print("Nobody wins!")
if __name__ == "__main__":
""" Play a single game to the end using UCT for both players.
"""
UCTPlayGame()