-
Notifications
You must be signed in to change notification settings - Fork 0
/
from_gist.py
280 lines (231 loc) · 8.2 KB
/
from_gist.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
import copy
import random
class TicTacToe:
def __init__(self, playerX, playerO, score):
self.board = [' ']*9
self.playerX, self.playerO = playerX, playerO
# self.playerX_turn = random.choice([True, False])
self.playerX_turn = True
self.score = score
def play_game(self):
self.playerX.start_game('X')
self.playerO.start_game('O')
while True: #yolo
if self.playerX_turn:
player, char, other_player = self.playerX, 'X', self.playerO
else:
player, char, other_player = self.playerO, 'O', self.playerX
if player.breed == "human":
self.display_board()
space = player.move(self.board)
if self.board[space-1] != ' ': # illegal move
player.reward(-99, self.board) # score of shame
break
self.board[space-1] = char
if self.player_wins(char):
player.reward(1, self.board)
other_player.reward(-1, self.board)
if char == 'X':
self.score[1] += 1
else:
self.score[2] += 1
break
if self.board_full(): # tie game
player.reward(0.5, self.board)
other_player.reward(0.5, self.board)
self.score[0] += 1
break
other_player.reward(0, self.board)
self.playerX_turn = not self.playerX_turn
def player_wins(self, char):
for a,b,c 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 char == self.board[a] == self.board[b] == self.board[c]:
return True
return False
def board_full(self):
return not any([space == ' ' for space in self.board])
def display_board(self):
row = " {} | {} | {}"
hr = "\n-----------\n"
print((row + hr + row + hr + row).format(*self.board))
def reset_score(self):
self.score = {0:0, 1:0, 2:0}
class Player:
def __init__(self):
self.breed = "human"
def start_game(self, char):
print("\nNew game!")
def move(self, board):
return int(input("Your move? "))
def reward(self, value, board):
print("{} rewarded: {}".format(self.breed, value))
def available_moves(self, board):
return [i+1 for i in range(0,9) if board[i] == ' ']
class RandomPlayer(Player):
def __init__(self):
self.breed = "random"
def reward(self, value, board):
pass
def start_game(self, char):
pass
def move(self, board):
return random.choice(self.available_moves(board))
class MinimaxPlayer(Player):
def __init__(self):
self.breed = "minimax"
self.best_moves = {}
def start_game(self, char):
self.me = char
self.enemy = self.other(char)
def other(self, char):
return 'O' if char == 'X' else 'X'
def move(self, board):
# if tuple(board) in self.best_moves:
# return random.choice(self.best_moves[tuple(board)])
if len(self.available_moves(board)) == 9:
return random.choice(range(1,10))
best_yet = -2
choices = []
for move in self.available_moves(board):
board[move-1] = self.me
optimal = self.minimax(board, self.enemy, -2, 2)
board[move-1] = ' '
if optimal > best_yet:
choices = [move]
best_yet = optimal
elif optimal == best_yet:
choices.append(move)
self.best_moves[tuple(board)] = choices
return random.choice(choices)
def minimax(self, board, char, alpha, beta):
if self.player_wins(self.me, board):
return 1
if self.player_wins(self.enemy, board):
return -1
if self.board_full(board):
return 0
if 'X' not in board and 'O' not in board:
return random.randint(1,9)
for move in self.available_moves(board):
board[move-1] = char
val = self.minimax(board, self.other(char), alpha, beta)
board[move-1] = ' '
if char == self.me:
if val > alpha:
alpha = val
if alpha >= beta:
return beta
else:
if val < beta:
beta = val
if beta <= alpha:
return alpha
if char == self.me:
return alpha
else:
return beta
def player_wins(self, char, board):
for a,b,c 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 char == board[a] == board[b] == board[c]:
return True
return False
def board_full(self, board):
return not any([space == ' ' for space in board])
def reward(self, value, board):
pass
class MinimuddledPlayer(MinimaxPlayer):
def __init__(self, confusion=0.1):
super(MinimuddledPlayer, self).__init__()
self.breed = "muddled"
self.confusion = confusion
self.ideal_player = MinimaxPlayer()
def start_game(self, char):
self.ideal_player.me = char
self.ideal_player.enemy = self.other(char)
def move(self, board):
if random.random() > self.confusion:
return self.ideal_player.move(board)
else:
return random.choice(self.available_moves(board))
class QLearningPlayer(Player):
def __init__(self, epsilon=0.2, alpha=0.3, gamma=0.9):
self.breed = "Qlearner"
self.harm_humans = False
self.q = {} # (state, action) keys: Q values
self.epsilon = epsilon # e-greedy chance of random exploration
self.alpha = alpha # learning rate
self.gamma = gamma # discount factor for future rewards
def start_game(self, char):
self.last_board = (' ',)*9
self.last_move = None
def getQ(self, state, action):
# encourage exploration; "optimistic" 1.0 initial values
if self.q.get((state, action)) is None:
self.q[(state, action)] = 1.0
return self.q.get((state, action))
def move(self, board):
self.last_board = tuple(board)
actions = self.available_moves(board)
if random.random() < self.epsilon: # explore!
self.last_move = random.choice(actions)
return self.last_move
qs = [self.getQ(self.last_board, a) for a in actions]
maxQ = max(qs)
if qs.count(maxQ) > 1:
# more than 1 best option; choose among them randomly
best_options = [i for i in range(len(actions)) if qs[i] == maxQ]
i = random.choice(best_options)
else:
i = qs.index(maxQ)
self.last_move = actions[i]
return actions[i]
def reward(self, value, board):
if self.last_move:
self.learn(self.last_board, self.last_move, value, tuple(board))
def learn(self, state, action, reward, result_state):
prev = self.getQ(state, action)
maxqnew = max([self.getQ(result_state, a) for a in self.available_moves(state)])
self.q[(state, action)] = prev + self.alpha * ((reward + self.gamma*maxqnew) - prev)
# p1 = RandomPlayer()
# p1 = MinimaxPlayer()
# p1 = MinimuddledPlayer()
p1 = QLearningPlayer()
p2 = QLearningPlayer()
for i in range(200):
score = {0: 0, 1: 0, 2: 0}
for _ in range(1000):
t = TicTacToe(p1, p2, score)
t.play_game()
print(score)
p2.epsilon = 0
# gist_p1 = copy.deepcopy(p1)
# p1 = RandomPlayer()
# score = {0: 0, 1: 0, 2: 0}
# for i in range(0,20000):
# t = TicTacToe(p1, p2, score)
# t.play_game()
# print(score)
#
p1 = MinimaxPlayer()
score = {0: 0, 1: 0, 2: 0}
for i in range(0,1000):
t = TicTacToe(p1, p2, score)
t.play_game()
print(score)
# p1 = MinimaxPlayer()
# score = {0: 0, 1: 0, 2: 0}
# for i in range(0,20000):
# t = TicTacToe(p1, p2, score)
# t.play_game()
# print(score)
# p1 = Player()
# p2.epsilon = 0
#
# score = {0: 0, 1: 0, 2: 0}
# while True:
# t = TicTacToe(p1, p2, score)
# t.play_game()