-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplayers.py
More file actions
68 lines (50 loc) · 1.91 KB
/
players.py
File metadata and controls
68 lines (50 loc) · 1.91 KB
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
import numpy as np
import os
import torch
from gameEngine import GameEngine, TicTacToeMoves
Ms = TicTacToeMoves
class Player:
def __init__(self):
raise NotImplementedError
def random_move(self, game, gen: np.random.Generator):
del game, gen
raise NotImplementedError
def name(self):
raise NotImplementedError
class RandomPlayer(Player):
def __init__(self, gameEngine: GameEngine, id=''):
self.ge = gameEngine
self.id = id
def random_move(self, game, gen: np.random.Generator):
moves = self.ge.legalMoves(game)
return moves[gen.choice(len(moves))]
def name(self):
return f'Random{self.id}'
class NNPlayer(Player):
def __init__(self, nnet, mcts, id=''):
self.nnet = nnet
self.mcts = mcts
self.ge = mcts.ge
self.id = id
def gen_data(self, n_games=25_000, max_len=-1, progress=None, device=None):
return self.mcts.gen_data(self.nnet, n_games=n_games, max_len=max_len, progress=progress, device=device)
def random_move(self, game, gen: np.random.Generator):
pi = self.mcts.policy(game, self.nnet, gen)
moves = self.ge.legalMoves(game)
p_pi = [pi[move] for move in moves]
return moves[np.argmax(p_pi)]
def best_move(self, game):
pi = self.mcts.policy(game, self.nnet, None)
moves = self.ge.legalMoves(game)
p_pi = [pi[move] for move in moves]
return moves[np.argmax(p_pi)]
# return moves[gen.choice(len(moves), p=p_pi)]
def name(self):
return f"NN{self.id}"
def BestPlayer(mcts, config, gameEngine: GameEngine, id='') -> Player:
id = f'Best{id}'
if os.path.isfile(f'./models/{config["game"]}best.pt'):
nnet = config['model']()
nnet.load_state_dict(torch.load(f'./models/{config["game"]}best.pt'))
return NNPlayer(nnet, mcts, id=id)
return RandomPlayer(gameEngine, id=id)