-
Notifications
You must be signed in to change notification settings - Fork 2
/
players.py
80 lines (60 loc) · 2.12 KB
/
players.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
from abc import ABC, abstractmethod
from random import randint
from numpy import argmax
class Player(ABC):
@abstractmethod
def next_action(self, state):
...
class IndecisivePlayer(Player):
def next_action(self, state):
moves = self.next_actions(state)
return moves[randint(0, len(moves) - 1)]
@abstractmethod
def next_actions(self, state):
...
class RandomPlayer(IndecisivePlayer):
def next_actions(self, state):
return state.actions()
class ConsolePlayer(Player):
def next_action(self, state):
actions = state.actions()
while True:
try:
print(state)
action = input(f'Action [{actions}]: ')
action = int(action)
if action in actions:
return action
except Exception:
pass
class MiniMaxPlayer(IndecisivePlayer):
def __init__(self, lookahead):
assert lookahead > 0
self.lookahead = lookahead
def next_actions(self, state):
moves, _ = self.value(state, self.lookahead)
return moves
def value(self, state, lookahead):
if lookahead == 0 or state.gameover():
return [], 1.0*state.winner()*(lookahead+1)
behaviour = max if state.player() == 1 else min
return self.minimax(state, behaviour, lookahead)
def minimax(self, state, behaviour, lookahead):
moves, res = [], -10000*state.player()
for cell in state.actions():
_, v = self.value(state.move(cell), lookahead-1)
if res == v:
moves.append(cell)
elif behaviour(res, v) == v:
moves, res = [cell], v
return moves, res
class NNPlayer(Player):
def __init__(self, model):
self.model = model
def next_action(self, state):
actions = state.actions()
current_player = state.player()
states = [state.move(action).cells for action in actions]
probs = self.model.predict(states)
player_probs = [p[current_player] for p in probs]
return actions[argmax(player_probs)]