-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graphics.py
executable file
·276 lines (250 loc) · 11.2 KB
/
Graphics.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
import PySimpleGUI as psGui
import numpy as np
from tensorflow import keras
from MillEnv import MillEnv
from mcts import State, MonteCarloTreeSearch, generate_empty_nodes
class MillDisplayer(object):
def __init__(self, MillEnvironment: MillEnv = None):
psGui.theme("dark")
self.millImage: str = "MühleBrett.png"
self.blackCheckerImage: str = "Schwarz.png"
self.whiteCheckerImage: str = "Weiss.png"
self.millEnv: MillEnv = MillEnv()
self.moves_names = {0: "put down", 1: "choose checker", 2: "move selected checker",
3: "delete opponent checker"}
self.last_move = []
if MillEnvironment is not None:
self.millEnv = MillEnvironment
self.ImageIDArray = np.array([])
self.imageLocations = [(10, 490), (225, 490), (440, 490),
(75, 415), (225, 415), (375, 415),
(150, 340), (225, 340), (310, 340),
(10, 265), (75, 265), (150, 265),
(310, 265), (375, 265), (440, 265),
(150, 190), (225, 190), (310, 190),
(75, 115), (225, 115), (375, 115),
(10, 55), (225, 55), (440, 55)]
self.graph = psGui.Graph(
canvas_size=(500, 500),
graph_bottom_left=(0, 0),
graph_top_right=(500, 500),
)
self.statusTextBox = psGui.Text("Player " + self.getPlayerName(self.millEnv.isPlaying) + " is playing",
size=(60, 1))
self.layout_ = [
[psGui.Button("Player vs. Player"), psGui.Button("Player vs. Agent"), psGui.Button("Agent vs. Agent")],
[self.statusTextBox],
[self.graph],
[psGui.Button("Close")]]
self.window = psGui.Window("Mill AI", layout=self.layout_, finalize=True)
self.window.finalize()
self.graph.DrawImage(filename=self.millImage, location=(0, 500))
self.activateClick()
self.reloadEnv()
def windowsLoop(self):
while True:
event, values = self.window.read()
if event == psGui.WIN_CLOSED or event == 'Close': # if user closes window or clicks cancel
break
elif not event == "":
self.reset()
self.window.close()
def makeMove(self, pos: int) -> bool:
valid, reward = self.millEnv.makeMove(pos)
if valid:
self.reloadEnv()
return valid
def reloadEnv(self):
self.setStatus(
"Player " + self.getPlayerName(self.millEnv.isPlaying) + " is playing - move needed: " + self.moves_names[
self.millEnv.moveNeeded])
for imageID in self.ImageIDArray:
self.graph.DeleteFigure(imageID)
self.ImageIDArray = np.array([])
for case, location in zip(self.millEnv.getBoard(), self.imageLocations):
if case == 1:
self.ImageIDArray = np.append(self.ImageIDArray,
self.graph.DrawImage(filename=self.blackCheckerImage, location=location))
elif case == -1:
self.ImageIDArray = np.append(self.ImageIDArray,
self.graph.DrawImage(filename=self.whiteCheckerImage, location=location))
self.window.refresh()
def getClicked(self, event) -> int:
for index, location in enumerate(self.imageLocations):
x2, y2 = location
if self.isInArea(event.x, -event.y + 500, x2, y2, 50, 50):
return index
return -1
def setAfterClicked(self, event):
pos = self.getClicked(event)
if pos == -1:
return
if self.millEnv.moveNeeded == 2:
dif = self.millEnv.selected - pos
if dif == 0:
return
if dif == -1:
pos = 1
elif dif == 1:
pos = 3
elif dif < 0:
pos = 2
elif dif > 0:
pos = 0
self.last_move.append(pos)
if not self.makeMove(pos):
self.last_move.pop()
def isInArea(self, posX1: int, posY1: int, posX2: int, posY2: int, width: int, height: int) -> bool:
if posX2 <= posX1 <= posX2 + width:
if posY2 >= posY1 >= posY2 - height:
return True
return False
def setStatus(self, status: str):
self.statusTextBox.Update(status)
def close(self):
self.window.close()
def activateClick(self):
self.graph.TKCanvas.bind("<Button-1>", self.setAfterClicked)
def deactivateClick(self):
self.graph.TKCanvas.unbind("<Button-1>")
def read(self, timout: bool = False):
return self.window.read(0 if timout else None)
def reset(self):
self.millEnv.reset()
self.reloadEnv()
def getPlayerName(self, player: int) -> str:
if player == 1:
return "black"
elif player == -1:
return "white"
else:
return "not a player"
class ModeratedGraphics(object):
def __init__(self, network_path, faktor, exponent):
self.nnet = keras.models.load_model(network_path, compile=False)
self.exponent = exponent
self.faktor = faktor
self.env = MillEnv()
self.graphics = MillDisplayer(self.env)
self.graphics.reloadEnv()
self.root: State = State(np.zeros((1, 24)), 0, -self.env.isPlaying, self.env)
val = self.root.setValAndPriors(self.nnet)
self.root.backpropagate(val)
self.mcts = MonteCarloTreeSearch(self.root)
def agentPlay(self):
self.resetMonteCarlo()
self.graphics.deactivateClick()
finished = 0
while finished == 0:
self.graphics.reloadEnv()
pi = self.mcts.search(self.nnet, self.faktor, self.exponent)
if self.mcts.depth < 5:
choices_pi = np.where(pi == -1, np.zeros(pi.shape), pi)
pos = np.random.choice(np.arange(24), p=choices_pi)
else:
pos = np.argmax(pi)
self.mcts.goToMoveNode(pos)
self.env.setFullState(self.mcts.root.state[0], self.mcts.root.state[1], self.mcts.root.state[2],
self.mcts.root.state[3], self.mcts.root.state[4], self.mcts.root.state[5],
self.mcts.root.state[6], self.mcts.root.state[7], self.mcts.root.state[8],
self.mcts.root.state[9])
event, values = self.graphics.read(True)
if self.eventHandler(event):
return
finished = self.env.isFinished()
self.graphics.reloadEnv()
if not finished == 2:
self.graphics.setStatus("player " + self.graphics.getPlayerName(finished) + " won")
else:
self.graphics.setStatus("The game ended in a draw")
def playersVSPlayer(self):
self.graphics.activateClick()
self.graphics.reset()
finished = 0
while finished == 0:
event, values = self.graphics.read()
if self.eventHandler(event):
return
self.graphics.reloadEnv()
finished = self.env.isFinished()
self.graphics.reloadEnv()
if not finished == 2:
self.graphics.setStatus("player " + self.graphics.getPlayerName(finished) + " won")
else:
self.graphics.setStatus("The game ended in a draw")
self.graphics.deactivateClick()
def playerVSAgent(self):
self.graphics.activateClick()
self.resetMonteCarlo()
finished = 0
while finished == 0:
event, values = self.graphics.read(True)
if self.eventHandler(event):
return
while len(self.graphics.last_move) > 0:
self.mcts.goToMoveNode(self.graphics.last_move.pop())
self.env.setFullState(self.mcts.root.state[0], self.mcts.root.state[1], self.mcts.root.state[2],
self.mcts.root.state[3], self.mcts.root.state[4], self.mcts.root.state[5],
self.mcts.root.state[6], self.mcts.root.state[7], self.mcts.root.state[8],
self.mcts.root.state[9])
if self.env.isPlaying == 1:
self.graphics.activateClick()
else:
if self.mcts.root.priors is None:
val = self.mcts.root.setValAndPriors(self.nnet)
self.mcts.root.backpropagate(val)
generate_empty_nodes(self.mcts.root)
self.graphics.deactivateClick()
pi = self.mcts.search(self.nnet, self.faktor, self.exponent)
pos = np.argmax(pi)
self.mcts.goToMoveNode(pos)
self.env.setFullState(self.mcts.root.state[0], self.mcts.root.state[1], self.mcts.root.state[2],
self.mcts.root.state[3], self.mcts.root.state[4], self.mcts.root.state[5],
self.mcts.root.state[6], self.mcts.root.state[7], self.mcts.root.state[8],
self.mcts.root.state[9])
self.graphics.reloadEnv()
finished = self.env.isFinished()
self.graphics.reloadEnv()
if not finished == 2:
self.graphics.setStatus("player " + self.graphics.getPlayerName(finished) + " won")
else:
self.graphics.setStatus("The game ended in a draw")
self.graphics.deactivateClick()
def playLoop(self):
self.graphics.deactivateClick()
self.playerVSAgent()
finished = False
while not finished:
event, values = self.graphics.read()
finished = self.eventHandler(event)
if event != psGui.WIN_CLOSED and event != 'Close':
finished = False
def eventHandler(self, event) -> bool:
if event == psGui.WIN_CLOSED or event == 'Close': # if user closes window or clicks cancel
self.graphics.close()
return True
elif event == "Agent vs. Agent":
self.agentPlay()
return True
elif event == "Player vs. Player":
self.playersVSPlayer()
return True
elif event == "Player vs. Agent":
self.playerVSAgent()
return True
return False
def resetMonteCarlo(self):
self.env.reset()
self.graphics.millEnv.reset()
self.root: State = State(np.zeros((1, 24)), 0, -self.env.isPlaying, self.env)
self.env.setFullState(self.mcts.root.state[0], self.mcts.root.state[1], self.mcts.root.state[2],
self.mcts.root.state[3], self.mcts.root.state[4], self.mcts.root.state[5],
self.mcts.root.state[6], self.mcts.root.state[7], self.mcts.root.state[8],
self.mcts.root.state[9])
self.mcts = MonteCarloTreeSearch(self.root)
val = self.mcts.root.setValAndPriors(self.nnet)
self.mcts.root.backpropagate(val)
self.graphics.reloadEnv()
if __name__ == "__main__":
MCGraphics = ModeratedGraphics("run5/models/whole_net", 12, 1.05)
MCGraphics.playLoop()