-
Notifications
You must be signed in to change notification settings - Fork 1
/
NNHumanCompetition.py
228 lines (205 loc) · 10.1 KB
/
NNHumanCompetition.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
# best net vs old net competition!
import datetime
import threading
import numpy as np
from ChessEnvironment import ChessEnvironment
import ActionToArray
import ChessConvNet
import _thread
import torch
import torch.nn as nn
import torch.utils.data as data_utils
from MCTSCrazyhouse import MCTS
import copy
import chess.variant
import chess.pgn
import chess
import chess.svg
import MCTSCrazyhouse
import time
import ValueEvaluation
def NetworkCompetitionWhite(bestNet, playouts, round="1"):
PGN = chess.pgn.Game()
PGN.headers["Event"] = "Neural Network Comparison Test"
PGN.headers["Site"] = "Cozy Computer Lounge"
PGN.headers["Date"] = datetime.datetime.today().strftime('%Y-%m-%d %H:%M')
PGN.headers["Round"] = round
PGN.headers["White"] = "Network: " + bestNet.nameOfNetwork
PGN.headers["Black"] = "You"
PGN.headers["Variant"] = "crazyhouse"
sim = ChessEnvironment()
while sim.result == 2:
noiseVal = 0.0 / (10 * (sim.plies // 2 + 1))
if sim.plies % 2 == 0:
if playouts > 0:
start = time.time()
bestNet.competitivePlayoutsFromPosition(playouts, sim)
end = time.time()
print(end-start)
else:
position = sim.boardToString()
if position not in bestNet.dictionary:
image = torch.from_numpy(sim.boardToState())
outputs = bestNet.neuralNet(image)[0]
if playouts > 0:
bestNet.addPositionToMCTS(sim.boardToString(),
ActionToArray.legalMovesForState(sim.arrayBoard,
sim.board),
sim.arrayBoard, outputs, sim)
else:
bestNet.dictionary[sim.boardToString()] = len(bestNet.dictionary)
policy = ActionToArray.moveEvaluations(ActionToArray.legalMovesForState(sim.arrayBoard,
sim.board),
sim.arrayBoard, outputs)
bestNet.childrenMoveNames.append(ActionToArray.legalMovesForState(sim.arrayBoard,
sim.board))
bestNet.childrenPolicyEval.append(policy)
directory = bestNet.dictionary[sim.boardToString()]
if playouts > 0:
index = np.argmax(
MCTSCrazyhouse.PUCT_Algorithm(bestNet.childrenStateWin[directory], bestNet.childrenStateSeen[directory], 1,
np.sum(bestNet.childrenStateSeen[directory]),
bestNet.childrenValueEval[directory],
MCTSCrazyhouse.noiseEvals(bestNet.childrenPolicyEval[directory], noiseVal))
)
else:
index = np.argmax(MCTSCrazyhouse.noiseEvals(bestNet.childrenPolicyEval[directory], noiseVal))
move = bestNet.childrenMoveNames[directory][index]
if chess.Move.from_uci(move) not in sim.board.legal_moves:
move = ActionToArray.legalMovesForState(sim.arrayBoard, sim.board)[0]
# PRINT WIN PROBABILITY W/ MCTS?
print("-----")
print(move)
print("Win Probability: {:.4f} %".format(100*ValueEvaluation.positionEval(sim, bestNet.neuralNet)))
if playouts > 0 and bestNet.childrenStateSeen[directory][index] > 0:
mctsWinRate = 100*bestNet.childrenStateWin[directory][index]/bestNet.childrenStateSeen[directory][index]
print("MCTS Win Probability: {:.4f} %".format(mctsWinRate))
totalWinRate = (100*ValueEvaluation.positionEval(sim, bestNet.neuralNet)+mctsWinRate)/2
print("Total Win Probability: {:.4f} %".format(totalWinRate))
print("-----")
sim.makeMove(move)
sim.gameResult()
elif sim.plies % 2 == 1:
legal = False
while not legal:
move = input("Enter move: ")
if len(move) == 4 or len(move) == 5:
if chess.Move.from_uci(move) in sim.board.legal_moves:
legal = True
else:
print("Illegal move! Try again:")
else:
print("Illegal move! Try again:")
print(move)
sim.makeMove(move)
sim.gameResult()
if sim.plies == 1:
node = PGN.add_variation(chess.Move.from_uci(move))
else:
node = node.add_variation(chess.Move.from_uci(move))
print(sim.board)
print("WHITE POCKET")
print(sim.whiteCaptivePieces)
print("BLACK POCKET")
print(sim.blackCaptivePieces)
if sim.result == 1:
PGN.headers["Result"] = "1-0"
if sim.result == 0:
PGN.headers["Result"] = "1/2-1/2"
if sim.result == -1:
PGN.headers["Result"] = "0-1"
print(PGN)
def NetworkCompetitionBlack(bestNet, playouts, round="1"):
PGN = chess.pgn.Game()
PGN.headers["Event"] = "Neural Network Comparison Test"
PGN.headers["Site"] = "Cozy Computer Lounge"
PGN.headers["Date"] = datetime.datetime.today().strftime('%Y-%m-%d %H:%M')
PGN.headers["Round"] = round
PGN.headers["White"] = "You"
PGN.headers["Black"] = "Network: " + bestNet.nameOfNetwork
PGN.headers["Variant"] = "crazyhouse"
sim = ChessEnvironment()
while sim.result == 2:
noiseVal = 0.0 / (10*(sim.plies//2 + 1))
if sim.plies % 2 == 1:
if playouts > 0:
start = time.time()
bestNet.competitivePlayoutsFromPosition(playouts, sim)
end = time.time()
print(end-start)
else:
position = sim.boardToString()
if position not in bestNet.dictionary:
image = torch.from_numpy(sim.boardToState())
outputs = bestNet.neuralNet(image)[0]
if playouts > 0:
bestNet.addPositionToMCTS(sim.boardToString(),
ActionToArray.legalMovesForState(sim.arrayBoard,
sim.board),
sim.arrayBoard, outputs, sim)
else:
bestNet.dictionary[sim.boardToString()] = len(bestNet.dictionary)
policy = ActionToArray.moveEvaluations(ActionToArray.legalMovesForState(sim.arrayBoard,
sim.board),
sim.arrayBoard, outputs)
bestNet.childrenPolicyEval.append(policy)
bestNet.childrenMoveNames.append(ActionToArray.legalMovesForState(sim.arrayBoard,
sim.board))
directory = bestNet.dictionary[sim.boardToString()]
if playouts > 0:
index = np.argmax(
MCTSCrazyhouse.PUCT_Algorithm(bestNet.childrenStateWin[directory], bestNet.childrenStateSeen[directory], 1,
np.sum(bestNet.childrenStateSeen[directory]),
bestNet.childrenValueEval[directory],
MCTSCrazyhouse.noiseEvals(bestNet.childrenPolicyEval[directory], noiseVal))
)
else:
index = np.argmax(MCTSCrazyhouse.noiseEvals(bestNet.childrenPolicyEval[directory], noiseVal))
move = bestNet.childrenMoveNames[directory][index]
if chess.Move.from_uci(move) not in sim.board.legal_moves:
move = ActionToArray.legalMovesForState(sim.arrayBoard, sim.board)[0]
# PRINT WIN PROBABILITY W/ MCTS?
print("-----")
print(move)
print("Win Probability: {:.4f} %".format(100*ValueEvaluation.positionEval(sim, bestNet.neuralNet)))
if playouts > 0 and bestNet.childrenStateSeen[directory][index]>0:
mctsWinRate = 100*bestNet.childrenStateWin[directory][index]/bestNet.childrenStateSeen[directory][index]
print("MCTS Win Probability: {:.4f} %".format(mctsWinRate))
totalWinRate = (100*ValueEvaluation.positionEval(sim, bestNet.neuralNet)+mctsWinRate)/2
print("Total Win Probability: {:.4f} %".format(totalWinRate))
print("-----")
sim.makeMove(move)
sim.gameResult()
elif sim.plies % 2 == 0:
legal = False
while not legal:
move = input("Enter move: ")
if len(move) == 4 or len(move) == 5:
if chess.Move.from_uci(move) in sim.board.legal_moves:
legal = True
else:
print("Illegal move! Try again:")
else:
print("Illegal move! Try again:")
print(move)
sim.makeMove(move)
sim.gameResult()
if sim.plies == 1:
node = PGN.add_variation(chess.Move.from_uci(move))
else:
node = node.add_variation(chess.Move.from_uci(move))
print(sim.board)
print("WHITE POCKET")
print(sim.whiteCaptivePieces)
print("BLACK POCKET")
print(sim.blackCaptivePieces)
if sim.result == 1:
PGN.headers["Result"] = "1-0"
if sim.result == 0:
PGN.headers["Result"] = "1/2-1/2"
if sim.result == -1:
PGN.headers["Result"] = "0-1"
print(PGN)
# PLAY!
network = MCTS('Users/Gordon/Documents/CrazyhouseRL/New Networks/(MCTS)(8X256|8|8)(GPU)64fish.pt', 4)
NetworkCompetitionBlack(network, 10)