careless25 commited on
Commit
1aa7564
·
2 Parent(s): 0e00a74dcdb33e

Merge pull request #53 from tttony/master

Browse files
Files changed (3) hide show
  1. config.py +17 -4
  2. config.yml.default +5 -0
  3. main.py +43 -9
config.py CHANGED
@@ -24,12 +24,19 @@ def load_config():
24
  raise Exception(section[2])
25
 
26
 
27
- engine_sections = ["dir", "name"]
 
 
 
 
 
 
 
28
  for subsection in engine_sections:
29
- if subsection not in CONFIG["engine"]:
30
  raise Exception("Your config.yml does not have required `engine` subsection `{}`.".format(subsection))
31
- if not isinstance(CONFIG["engine"][subsection], str):
32
- raise Exception("Engine subsection `{}` must be a string wrapped in quotes.".format(subsection))
33
 
34
  if CONFIG["token"] == "xxxxxxxxxxxxxxxx":
35
  raise Exception("Your config.yml has the default Lichess API token. This is probably wrong.")
@@ -45,4 +52,10 @@ def load_config():
45
  if not os.access(engine, os.X_OK):
46
  raise Exception("The engine %s doesn't have execute (x) permission. Try: chmod +x %s" % (engine, engine))
47
 
 
 
 
 
 
 
48
  return CONFIG
 
24
  raise Exception(section[2])
25
 
26
 
27
+ engine_sections = [["dir", str, "´dir´ must be a string wrapped in quotes."],
28
+ ["name", str, "´name´ must be a string wrapped in quotes."],
29
+ ["polyglot", bool, "´polyglot´ must be a boolean type: true or false."],
30
+ ["polyglot_book", str, "´polyglot_book´ must be a string wrapped in quotes."],
31
+ ["polyglot_max_depth", int, "`polyglot_max_depth` must be an integer number without quotes."],
32
+ ["polyglot_min_weight", int, "`polyglot_min_weight` must be an integer number without quotes."],
33
+ ["polyglot_random", bool, "`polyglot_random` must be a boolean type: true or false."]]
34
+
35
  for subsection in engine_sections:
36
+ if subsection[0] not in CONFIG["engine"]:
37
  raise Exception("Your config.yml does not have required `engine` subsection `{}`.".format(subsection))
38
+ if not isinstance(CONFIG["engine"][subsection[0]], subsection[1]):
39
+ raise Exception("´engine´ subsection {}".format(subsection[2]))
40
 
41
  if CONFIG["token"] == "xxxxxxxxxxxxxxxx":
42
  raise Exception("Your config.yml has the default Lichess API token. This is probably wrong.")
 
52
  if not os.access(engine, os.X_OK):
53
  raise Exception("The engine %s doesn't have execute (x) permission. Try: chmod +x %s" % (engine, engine))
54
 
55
+ if (CONFIG["engine"]["polyglot"] == True):
56
+ book_dir = os.path.join(CONFIG["engine"]["dir"], CONFIG["engine"]["polyglot_book"])
57
+ if not os.path.isfile(book_dir):
58
+ raise Exception("The polyglot book %s file does not exist." % book_dir)
59
+ CONFIG["engine"]["polyglot_book"] = book_dir
60
+
61
  return CONFIG
config.yml.default CHANGED
@@ -7,6 +7,11 @@ engine: # engine settings
7
  protocol: "uci" # "uci" or "xboard"
8
  # weights: "latest.txt" # only if the engine is lczero
9
  # threads: 1 # only if the engine is lczero
 
 
 
 
 
10
 
11
  ucioptions: # arbitrary UCI options passed to the engine
12
  Move Overhead: 100 # increase if your bot flags games too often
 
7
  protocol: "uci" # "uci" or "xboard"
8
  # weights: "latest.txt" # only if the engine is lczero
9
  # threads: 1 # only if the engine is lczero
10
+ polyglot: false # activate polyglot book
11
+ polyglot_book: "book.bin" # book file name, must be in engine.dir
12
+ polyglot_max_depth: 8 # half move max depth
13
+ polyglot_min_weight: 1 # best move weight
14
+ polyglot_random: true # select move randomly otherwise select by min weight
15
 
16
  ucioptions: # arbitrary UCI options passed to the engine
17
  Move Overhead: 100 # increase if your bot flags games too often
main.py CHANGED
@@ -1,6 +1,7 @@
1
  import argparse
2
  import chess
3
  from chess.variant import find_variant
 
4
  import engine_wrapper
5
  import model
6
  import json
@@ -38,8 +39,9 @@ def watch_control_stream(control_queue, li):
38
  else:
39
  control_queue.put_nowait({"type": "ping"})
40
 
41
- def start(li, user_profile, max_games, engine_factory, config):
42
  # init
 
43
  print("You're now connected to {} and awaiting challenges.".format(config["url"]))
44
  manager = multiprocessing.Manager()
45
  challenge_queue = []
@@ -74,7 +76,7 @@ def start(li, user_profile, max_games, engine_factory, config):
74
  else:
75
  queued_processes -= 1
76
  game_id = event["game"]["id"]
77
- pool.apply_async(play_game, [li, game_id, control_queue, engine_factory, user_profile])
78
  busy_processes += 1
79
  print("--- Process Used. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
80
 
@@ -94,8 +96,7 @@ def start(li, user_profile, max_games, engine_factory, config):
94
  control_stream.terminate()
95
  control_stream.join()
96
 
97
-
98
- def play_game(li, game_id, control_queue, engine_factory, user_profile):
99
  updates = li.get_game_stream(game_id).iter_lines()
100
 
101
  #Initial response of stream will be the full game info. Store it
@@ -108,7 +109,12 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile):
108
 
109
  engine.pre_game(game)
110
 
111
- board = play_first_move(game, engine, board, li)
 
 
 
 
 
112
 
113
  try:
114
  for binary_chunk in updates:
@@ -120,9 +126,12 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile):
120
  game.state = upd
121
  moves = upd["moves"].split()
122
  board = update_board(board, moves[-1])
123
-
124
  if is_engine_move(game, moves):
125
- best_move = engine.search(board, upd["wtime"], upd["btime"], upd["winc"], upd["binc"])
 
 
 
 
126
  li.make_move(game.id, best_move)
127
  game.abort_in(20)
128
  elif u_type == "ping":
@@ -150,6 +159,32 @@ def play_first_move(game, engine, board, li):
150
  return board
151
 
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  def setup_board(game):
154
  if game.variant_name.lower() == "chess960":
155
  board = chess.Board(game.initial_fen, chess960=True)
@@ -208,8 +243,7 @@ if __name__ == "__main__":
208
  is_bot = upgrade_account(li)
209
 
210
  if is_bot:
211
- max_games = CONFIG["max_concurrent_games"]
212
  engine_factory = partial(engine_wrapper.create_engine, CONFIG)
213
- start(li, user_profile, max_games, engine_factory, CONFIG)
214
  else:
215
  print("{} is not a bot account. Please upgrade your it to a bot account!".format(user_profile["username"]))
 
1
  import argparse
2
  import chess
3
  from chess.variant import find_variant
4
+ import chess.polyglot
5
  import engine_wrapper
6
  import model
7
  import json
 
39
  else:
40
  control_queue.put_nowait({"type": "ping"})
41
 
42
+ def start(li, user_profile, engine_factory, config):
43
  # init
44
+ max_games = config["max_concurrent_games"]
45
  print("You're now connected to {} and awaiting challenges.".format(config["url"]))
46
  manager = multiprocessing.Manager()
47
  challenge_queue = []
 
76
  else:
77
  queued_processes -= 1
78
  game_id = event["game"]["id"]
79
+ pool.apply_async(play_game, [li, game_id, control_queue, engine_factory, user_profile, config])
80
  busy_processes += 1
81
  print("--- Process Used. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
82
 
 
96
  control_stream.terminate()
97
  control_stream.join()
98
 
99
+ def play_game(li, game_id, control_queue, engine_factory, user_profile, config):
 
100
  updates = li.get_game_stream(game_id).iter_lines()
101
 
102
  #Initial response of stream will be the full game info. Store it
 
109
 
110
  engine.pre_game(game)
111
 
112
+ engine_cfg = config["engine"]
113
+
114
+ if (engine_cfg["polyglot"] == True):
115
+ board = play_first_book_move(game, engine, board, li, engine_cfg)
116
+ else:
117
+ board = play_first_move(game, engine, board, li)
118
 
119
  try:
120
  for binary_chunk in updates:
 
126
  game.state = upd
127
  moves = upd["moves"].split()
128
  board = update_board(board, moves[-1])
 
129
  if is_engine_move(game, moves):
130
+ best_move = None
131
+ if (engine_cfg["polyglot"] == True and len(moves) <= (engine_cfg["polyglot_max_depth"] * 2) - 1):
132
+ best_move = get_book_move(board, engine_cfg)
133
+ if best_move == None:
134
+ best_move = engine.search(board, upd["wtime"], upd["btime"], upd["winc"], upd["binc"])
135
  li.make_move(game.id, best_move)
136
  game.abort_in(20)
137
  elif u_type == "ping":
 
159
  return board
160
 
161
 
162
+ def play_first_book_move(game, engine, board, li, config):
163
+ moves = game.state["moves"].split()
164
+ if is_engine_move(game, moves):
165
+ book_move = get_book_move(board, config)
166
+ if (book_move != None):
167
+ li.make_move(game.id, book_move)
168
+ else:
169
+ return play_first_move(game, engine, board, li)
170
+
171
+ return board
172
+
173
+
174
+ def get_book_move(board, engine_cfg):
175
+ try:
176
+ with chess.polyglot.open_reader(engine_cfg["polyglot_book"]) as reader:
177
+ if (engine_cfg["polyglot_random"] == True):
178
+ book_move = reader.choice(board).move()
179
+ else:
180
+ book_move = reader.find(board, engine_cfg["polyglot_min_weight"]).move()
181
+ return book_move
182
+ except:
183
+ pass
184
+
185
+ return None
186
+
187
+
188
  def setup_board(game):
189
  if game.variant_name.lower() == "chess960":
190
  board = chess.Board(game.initial_fen, chess960=True)
 
243
  is_bot = upgrade_account(li)
244
 
245
  if is_bot:
 
246
  engine_factory = partial(engine_wrapper.create_engine, CONFIG)
247
+ start(li, user_profile, engine_factory, CONFIG)
248
  else:
249
  print("{} is not a bot account. Please upgrade your it to a bot account!".format(user_profile["username"]))