Tianshou/AlphaGo/play.py

115 lines
4.5 KiB
Python
Raw Normal View History

import argparse
2017-12-09 21:41:11 +08:00
import sys
import re
import time
import os
from game import Game
from engine import GTPEngine
2018-01-11 17:02:36 +08:00
from utils import Data
2017-12-26 19:29:35 +08:00
import utils
from time import gmtime, strftime
2017-12-25 15:33:17 +08:00
python_version = sys.version_info
if python_version < (3, 0):
import cPickle
else:
import _pickle as cPickle
2018-01-09 20:09:48 +08:00
if __name__ == '__main__':
"""
Starting two different players which load network weights to evaluate the winning ratio.
Note that, this function requires the installation of the Pyro4 library.
"""
# TODO : we should set the network path in a more configurable way.
parser = argparse.ArgumentParser()
2017-12-25 16:40:38 +08:00
parser.add_argument("--data_path", type=str, default="./data/")
parser.add_argument("--black_weight_path", type=str, default=None)
parser.add_argument("--white_weight_path", type=str, default=None)
2017-12-24 01:07:46 +08:00
parser.add_argument("--debug", type=bool, default=False)
2017-12-25 16:40:38 +08:00
parser.add_argument("--game", type=str, default="go")
args = parser.parse_args()
2017-12-25 16:40:38 +08:00
if not os.path.exists(args.data_path):
os.mkdir(args.data_path)
# black_weight_path = "./checkpoints"
# white_weight_path = "./checkpoints_origin"
if args.black_weight_path is not None and (not os.path.exists(args.black_weight_path)):
2017-12-26 19:29:35 +08:00
raise ValueError("Can't find the network weights for black player.")
if args.white_weight_path is not None and (not os.path.exists(args.white_weight_path)):
2017-12-26 19:29:35 +08:00
raise ValueError("Can't find the network weights for white player.")
game = Game(name=args.game,
black_checkpoint_path=args.black_weight_path,
white_checkpoint_path=args.white_weight_path,
debug=args.debug)
engine = GTPEngine(game_obj=game, name='tianshou', version=0)
2017-12-09 21:41:11 +08:00
data = Data()
role = ["BLACK", "WHITE"]
color = ['b', 'w']
pattern = "[A-Z]{1}[0-9]{1}"
2017-12-21 23:30:24 +08:00
space = re.compile("\s+")
2017-12-24 14:40:50 +08:00
size = {"go":9, "reversi":8}
show = ['.', 'X', 'O']
2017-12-09 21:41:11 +08:00
2017-12-26 19:29:35 +08:00
evaluate_rounds = 100
game_num = 0
try:
while True:
#while game_num < evaluate_rounds:
2017-12-21 23:30:24 +08:00
start_time = time.time()
game.model.check_latest_model()
num = 0
pass_flag = [False, False]
print("Start game {}".format(game_num))
# end the game if both palyer chose to pass, or play too much turns
2017-12-25 16:40:38 +08:00
while not (pass_flag[0] and pass_flag[1]) and num < size[args.game] ** 2 * 2:
turn = num % 2
board = engine.run_cmd(str(num) + ' show_board')
2017-12-21 23:30:24 +08:00
board = eval(board[board.index('['):board.index(']') + 1])
2017-12-25 16:40:38 +08:00
for i in range(size[args.game]):
for j in range(size[args.game]):
print show[board[i * size[args.game] + j]] + " ",
2017-12-21 23:30:24 +08:00
print "\n",
data.boards.append(board)
2017-12-24 01:07:46 +08:00
start_time = time.time()
move = engine.run_cmd(str(num) + ' genmove ' + color[turn])[:-1]
2017-12-26 19:29:35 +08:00
print("\n" + role[turn] + " : " + str(move)),
num += 1
match = re.search(pattern, move)
if match is not None:
# print "match : " + str(match.group())
play_or_pass = match.group()
pass_flag[turn] = False
else:
# print "no match"
play_or_pass = ' PASS'
pass_flag[turn] = True
prob = engine.run_cmd(str(num) + ' get_prob')
2017-12-21 23:30:24 +08:00
prob = space.sub(',', prob[prob.index('['):prob.index(']') + 1])
prob = prob.replace('[,', '[')
prob = prob.replace('],', ']')
prob = eval(prob)
data.probs.append(prob)
score = engine.run_cmd(str(num) + ' get_score')
2017-12-25 16:35:43 +08:00
print("Finished : {}".format(score.split(" ")[1]))
2017-12-21 23:30:24 +08:00
if eval(score.split(" ")[1]) > 0:
2017-12-26 19:29:35 +08:00
data.winner = utils.BLACK
2017-12-21 23:30:24 +08:00
if eval(score.split(" ")[1]) < 0:
2017-12-26 19:29:35 +08:00
data.winner = utils.WHITE
engine.run_cmd(str(num) + ' clear_board')
2017-12-25 16:40:38 +08:00
file_list = os.listdir(args.data_path)
2017-12-26 19:29:35 +08:00
current_time = strftime("%Y%m%d_%H%M%S", gmtime())
2017-12-27 19:54:36 +08:00
if os.path.exists(args.data_path + current_time + ".pkl"):
time.sleep(1)
current_time = strftime("%Y%m%d_%H%M%S", gmtime())
2017-12-26 19:29:35 +08:00
with open(args.data_path + current_time + ".pkl", "wb") as file:
picklestring = cPickle.dump(data, file)
data.reset()
game_num += 1
2017-12-25 16:40:38 +08:00
except KeyboardInterrupt:
pass