def findbest(f, times): print('Calibrating search speed...') pos = xboard.parseFEN('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') CAL_NODES = 10000 start = time.time() _ = sunfish.search(pos, CAL_NODES) factor = CAL_NODES/(time.time()-start) print('Running benchmark with %.1f nodes per second...' % factor) print('-'*60) totalpoints = 0 totaltests = 0 for k, line in enumerate(f): fen, opts = parseEPD(line) pos = xboard.parseFEN(fen) color = 0 if fen.split()[1] == 'w' else 1 # am -> avoid move; bm -> best move am = parseSAN(pos,color,opts['am']) if 'am' in opts else None bm = parseSAN(pos,color,opts['bm']) if 'bm' in opts else None points = 0 print(opts['id'], end=' ', flush=True) for t in times: move, _ = sunfish.search(pos, factor*t) mark = renderSAN(pos, move) if am and move != am or bm and move == bm: mark += '(1)' points += 1 totalpoints += 1 else: mark += '(0)' print(mark, end=' ', flush=True) totaltests + 1 print(points) print('-'*60) print('Total Points: %d/%d', totalpoints, totaltests)
def selfplay(): """ Start a game sunfish vs. sunfish """ wa, ba = (['C', 'N', 'E', 'R', 'T', 'A'])[random.randint(0, 5)], (['c', 'n', 'e', 'r', 't', 'a'])[random.randint(0, 5)] #pos = xboard.parseFEN('{}{} 33 rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'.format(wa, ba)) pos = xboard.parseFEN( 'Ca 33 rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') print(' '.join(pos.board)) print('#' * 10) for d in range(100): move, score = sunfish.search(pos, maxn=1e3) pos = pos.move(move) # Always print the board from the same direction board = pos.rotate().board if pos.color else pos.board #board = pos.board print(' '.join(board)) print("{}. {}: {}".format(d + 1, (['w', 'b'])[not pos.color], xboard.mrender(pos, move))) print("\n" + str(xboard.printFEN(pos))) if pos.second: print("second initiated") move, score = sunfish.search(pos, maxn=1e2) if move: print("move found") board = pos.rotate().board if pos.color else pos.board print(' '.join(board)) print("{}. {}: {}".format(d + 1, (['w', 'b'])[not pos.color], xboard.mrender(pos, move))) print("\n" + str(xboard.printFEN(pos))) pos = pos.move(move) else: score = 0 pos = sunfish.Position(pos.board, pos.color, False, pos.score, pos.wa, pos.ba, pos.ws, pos.bs, pos.wc, pos.bc, pos.ep, pos.kp) pos = pos.rotate() if score <= -30000: print("Game over. White wins.") break if score >= 30000: print("Game over. Black wins.") break print('#' * 10)
def allmate(path): with open(path) as f: for line in f: line = line.strip() print(line) pos = xboard.parseFEN(line) _, score = sunfish.search(pos, maxn=1e9) if score < sunfish.MATE_VALUE: print("Unable to find mate. Only got score = %d" % score) break
def findbest(f, times): print('Calibrating search speed...') pos = xboard.parseFEN(xboard.FEN_INITIAL) CAL_NODES = 100000 start = time.time() _ = sunfish.search(pos, CAL_NODES) factor = sunfish.nodes/(time.time()-start) print('Running benchmark with %.1f nodes per second...' % factor) print('Printing best move after seconds', times) print('-'*60) totalpoints = 0 totaltests = 0 for line in f: fen, opts = parseEPD(line, opt_dict=True) if type(opts) != dict or ('am' not in opts and 'bm' not in opts): print("Line didn't have am/bm in opts", line, opts) continue pos = xboard.parseFEN(fen) color = xboard.WHITE if fen.split()[1] == 'w' else xboard.BLACK # am -> avoid move; bm -> best move am = parseSAN(pos,color,opts['am']) if 'am' in opts else None bm = parseSAN(pos,color,opts['bm']) if 'bm' in opts else None print('Looking for am/bm', opts.get('am'), opts.get('bm')) points = 0 print(opts.get('id','unnamed'), end=' ', flush=True) for t in times: move, _ = sunfish.search(pos, factor*t) mark = renderSAN(pos,color,move) if am and move != am or bm and move == bm: mark += '(1)' points += 1 else: mark += '(0)' print(mark, end=' ', flush=True) totaltests += 1 print(points) totalpoints += points print('-'*60) print('Total Points: %d/%d', totalpoints, totaltests)
def selfplay(): """ Start a game sunfish vs. sunfish """ wa, ba = (['C', 'N', 'E', 'R', 'T', 'A'])[random.randint(0, 5)], (['c', 'n', 'e', 'r', 't', 'a'])[random.randint(0, 5)] #pos = xboard.parseFEN('{}{} 33 rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'.format(wa, ba)) pos = xboard.parseFEN('Ca 33 rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') print(' '.join(pos.board)) print('#' * 10) for d in range(100): move, score = sunfish.search(pos, maxn=1e3) pos = pos.move(move) # Always print the board from the same direction board = pos.rotate().board if pos.color else pos.board #board = pos.board print(' '.join(board)) print("{}. {}: {}".format(d+1, (['w', 'b'])[not pos.color], xboard.mrender(pos, move))) print("\n" + str(xboard.printFEN(pos))) if pos.second: print("second initiated") move, score = sunfish.search(pos, maxn=1e2) if move: print("move found") board = pos.rotate().board if pos.color else pos.board print(' '.join(board)) print("{}. {}: {}".format(d+1, (['w', 'b'])[not pos.color], xboard.mrender(pos, move))) print("\n" + str(xboard.printFEN(pos))) pos = pos.move(move) else: score = 0 pos = sunfish.Position( pos.board, pos.color, False, pos.score, pos.wa, pos.ba, pos.ws, pos.bs, pos.wc, pos.bc, pos.ep, pos.kp) pos = pos.rotate() if score <= -30000: print("Game over. White wins.") break if score >= 30000: print("Game over. Black wins.") break print('#' * 10)
def selfplay(maxn=200): """ Start a game sunfish vs. sunfish """ pos = xboard.parseFEN(xboard.FEN_INITIAL) for d in range(200): # Always print the board from the same direction board = pos.board if d % 2 == 0 else pos.rotate().board print(' '.join(board)) m, _ = sunfish.search(pos, maxn) if m is None: print("Game over") break print("\nmove", xboard.mrender(d%2, pos, m)) pos = pos.move(m)
def jugarPc(self): """Juega la maquina""" mover, _ = sunfish.search(self.posicion, self.secs) self.posicion = self.posicion.move(mover) if self.secs == 1: desde = sunfish.render(mover[0]) hasta = sunfish.render(mover[1]) else: desde = sunfish.brender(mover[0]) hasta = sunfish.brender(mover[1]) self.realizarMovimiento(desde, hasta) self.pasar_turno()
def selfplay(): """ Start a game sunfish vs. sunfish """ pos = xboard.parseFEN('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') for d in range(200): # Always print the board from the same direction board = pos.board if d % 2 == 0 else pos.rotate().board print(' '.join(board)) m, _ = sunfish.search(pos, maxn=200) if m is None: print("Game over") break print("\nmove", xboard.mrender(d%2, pos, m)) pos = pos.move(m)
def findbest(path, times): print('Calibrating search speed...') pos = xboard.parseFEN( 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') CAL_NODES = 10000 start = time.time() _ = sunfish.search(pos, CAL_NODES) factor = CAL_NODES / (time.time() - start) print('Running benchmark with %.1f nodes per second...' % factor) print('-' * 60) totalpoints = 0 totaltests = 0 with open(path) as f: for k, line in enumerate(f): fen, opts = parseEPD(line) pos = xboard.parseFEN(fen) color = 0 if fen.split()[1] == 'w' else 1 # am -> avoid move; bm -> best move am = parseSAN(pos, color, opts['am']) if 'am' in opts else None bm = parseSAN(pos, color, opts['bm']) if 'bm' in opts else None points = 0 print(opts['id'], end=' ', flush=True) for t in times: move, _ = sunfish.search(pos, factor * t) mark = renderSAN(pos, move) if am and move != am or bm and move == bm: mark += '(1)' points += 1 totalpoints += 1 else: mark += '(0)' print(mark, end=' ', flush=True) totaltests + 1 print(points) print('-' * 60) print('Total Points: %d/%d', totalpoints, totaltests)
def selfplay(): """ Start a game sunfish vs. sunfish """ pos = parseFEN('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') for d in range(200): # Always print the board from the same direction if d % 2 == 0: pos = pos.rotate() print('\n'.join(pos.board[i:i+10] for i in range(100,0,-10))) if d % 2 == 0: pos = pos.rotate() m, _ = search(pos) if m is None: print("Game over") break print("\nmove %s%s" % tuple(map(render,m))) pos = pos.move(m)
def selfplay(maxn=200): """ Start a game sunfish vs. sunfish """ pos = xboard.parseFEN( 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') for d in range(200): # Always print the board from the same direction board = pos.board if d % 2 == 0 else pos.rotate().board print(' '.join(board)) m, _ = sunfish.search(pos, maxn) if m is None: print("Game over") break print("\nmove", xboard.mrender(d % 2, pos, m)) pos = pos.move(m)
def xboard(): """ Play as a black engine in the CECP/XBoard protocol """ pos = parseFEN('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') while True: smove = input() if smove == 'quit': break elif smove == 'protover 2': print('feature myname="Sunfish" usermove=1 done=1') continue elif smove.startswith('usermove'): smove = smove[9:] m = parse(smove[0:2]), parse(smove[2:4]) pos = pos.move(m) # Respond m, _ = search(pos) print("move %s%s" % (render(119-m[0]), render(119-m[1]))) pos = pos.move(m) else: print("Didn't understand command '%s'" % smove) continue
def move(self, gn_current): assert(gn_current.board().turn == 1) # Apply last_move crdn = str(gn_current.move) move = (sunfish.parse(crdn[0:2]), sunfish.parse(crdn[2:4])) self._pos = self._pos.move(move) #t0 = time.time() move, score = sunfish.search(self._pos, maxn=self._maxn) #print time.time() - t0, move, score self._pos = self._pos.move(move) crdn = sunfish.render(119-move[0]) + sunfish.render(119 - move[1]) move = create_move(gn_current.board(), crdn) gn_new = chess.pgn.GameNode() gn_new.parent = gn_current gn_new.move = move return gn_new
def handle_event(self, command): if not command.is_prepared() or not self.backlog_processed: return self.verbose('Got Command: {}', command.DB_TAG) action = None if MoveCommand.DB_TAG in command.DB_TAG: move = command.move move_str = command.move_str if move in self.game.genMoves(): self.game = self.game.move(move) self.game.rotate() move, score = search(self.game) if score <= -MATE_VALUE: action = ReplyAction('You Win!', self.reply_to) elif score >= MATE_VALUE: action = ReplyAction('You Lost :(', self.reply_to) else: bot_move = render(119 - move[0]) + render(119 - move[1]) self.game = self.game.move(move) action = PrintBoardAction(self.game.board, move_str, bot_move, self.reply_to) else: action = ReplyAction('That move is invalid.', command.uid) elif NewGameCommand.DB_TAG in command.DB_TAG: self.new_game() self.reply_to = command.uid action = PrintBoardAction(self.game.board, None, None, self.reply_to) if action: yield from self.send_action(action)
def handle_event(self, command): if not command.is_prepared() or not self.backlog_processed: return self.verbose('Got Command: {}', command.DB_TAG) action = None if MoveCommand.DB_TAG in command.DB_TAG: move = command.move move_str = command.move_str if move in self.game.genMoves(): self.game = self.game.move(move) self.game.rotate() move, score = search(self.game) if score <= -MATE_VALUE: action = ReplyAction('You Win!', self.reply_to) elif score >= MATE_VALUE: action = ReplyAction('You Lost :(', self.reply_to) else: bot_move = render(119-move[0]) + render(119-move[1]) self.game = self.game.move(move) action = PrintBoardAction(self.game.board, move_str, bot_move, self.reply_to) else: action = ReplyAction('That move is invalid.', command.uid) elif NewGameCommand.DB_TAG in command.DB_TAG: self.new_game() self.reply_to = command.uid action = PrintBoardAction(self.game.board, None, None, self.reply_to) if action: yield from self.send_action(action)
def main(): pos = parseFEN(FEN_INITIAL) forced = False color = WHITE time, otim = 1, 1 stack = [] while True: if stack: smove = stack.pop() else: smove = input() if smove == 'quit': break elif smove == 'protover 2': print('feature done=0') print('feature myname="Sunfish"') print('feature usermove=1') print('feature setboard=1') print('feature ping=1') print('feature sigint=0') print('feature variants="normal"') print('feature done=1') elif smove == 'new': stack.append('setboard ' + FEN_INITIAL) elif smove.startswith('setboard'): _, fen = smove.split(' ', 1) pos = parseFEN(fen) color = WHITE if fen.split()[1] == 'w' else BLACK elif smove == 'force': forced = True elif smove == 'go': forced = False # Let's follow the clock of our opponent nodes = 2e4 if time > 0 and otim > 0: nodes *= time / otim m, s = sunfish.search(pos, maxn=nodes) # We don't play well once we have detected our death if s <= -sunfish.MATE_VALUE: print('resign') else: print('# %d %+d %d %d %s' % (0, s, 0, sunfish.nodes, pv(color, pos))) print('move', mrender(color, pos, m)) print('score before %d after %+d' % (pos.score, pos.value(m))) pos = pos.move(m) color = 1 - color elif smove.startswith('ping'): _, N = smove.split() print('pong', N) elif smove.startswith('usermove'): _, smove = smove.split() m = mparse(color, smove) pos = pos.move(m) color = 1 - color if not forced: stack.append('go') elif smove.startswith('time'): time = int(smove.split()[1]) elif smove.startswith('otim'): otim = int(smove.split()[1]) elif any( smove.startswith(x) for x in ('xboard', 'post', 'random', 'hard', 'accepted', 'level')): pass else: print("Error (unkown command):", smove)
def main(): pos = parseFEN('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') forced = False color = WHITE msecLeft = 1 mps = 0 minutes = 0 seconds = 0 inc = 0 moveNr = 0 neverExceedLimit = 0 noNewMoveLimit = 0 noNewIterationLimit = 0 stack = [] nodes = 0 while True: if stack: smove = stack.pop() else: smove = input() if smove == 'quit': break elif smove == 'protover 2': print('feature done=0') print('feature myname="Sunfish"') print('feature usermove=1') print('feature setboard=1') print('feature ping=1') print('feature sigint=0') print('feature variants="normal"') print('feature done=1') elif smove == 'new': stack.append('setboard rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') forced = False elif smove.startswith('setboard'): _, fen = smove.split(' ', 1) pos = parseFEN(fen) color = WHITE if fen.split()[1] == 'w' else BLACK print(pos.board) elif smove == 'force': forced = True elif smove == 'go': forced = False print("# Search Start") m, s = sunfish.search(pos, nodes, neverExceedLimit, noNewMoveLimit, noNewIterationLimit) # We don't play well once we have detected our death if s <= -sunfish.MATE_VALUE: print('resign') else: print('%d %+d %d %d %s' % (0, s, 0, sunfish.N, pv(color,pos))) print('move', mrender(color, pos, m)) print('score before %d after %+d' % (pos.score, pos.value(m))) pos = pos.move(m) color = 1-color elif smove.startswith('ping'): _, N = smove.split() print('pong', N) elif smove.startswith('usermove'): _, smove = smove.split() m = mparse(color, smove) print("# usermove %s" % (mrender(color, pos, m))) pos = pos.move(m) color = 1-color if not forced: stack.append('go') print('# moving') moveNr += 1 elif smove.startswith('time'): msecLeft = int(smove.split()[1]) movesToGo = mps - (moveNr/2) if mps == 0: movesToGo = 30 else: while (movesToGo <= 0): movesToGo += mps msecLeft -= 16 neverExceedLimit = int(float(10*msecLeft) / float(movesToGo + 9)) noNewMoveLimit = int(float(1.5*msecLeft) / float(movesToGo + 0.5)) noNewIterationLimit = int(float(0.5*msecLeft) / float(movesToGo)) print("# %d, %d, %d" % (neverExceedLimit, noNewMoveLimit, noNewIterationLimit)) elif smove.startswith('level'): line = smove.split() mps = int(line[1]) minutes = line[2] inc = line[3] if re.search(':', minutes) != None: line = re.split(':', minutes) minutes = line[0] seconds = line[1] elif smove.startswith('analyze'): m, s = sunfish.search(pos, 1000000000) elif any(smove.startswith(x) for x in ('xboard','post','random','hard','accepted','rejected','otim')): pass else: print("Error (unknown command):", smove)
def main(): pos = parseFEN(FEN_INITIAL) forced = False color = WHITE time, otim = 1, 1 stack = [] while True: if stack: smove = stack.pop() else: smove = input() if smove == "quit": break elif smove == "protover 2": print("feature done=0") print('feature myname="Sunfish"') print("feature usermove=1") print("feature setboard=1") print("feature ping=1") print("feature sigint=0") print('feature variants="normal"') print("feature done=1") elif smove == "new": stack.append("setboard " + FEN_INITIAL) elif smove.startswith("setboard"): _, fen = smove.split(" ", 1) pos = parseFEN(fen) color = WHITE if fen.split()[1] == "w" else BLACK elif smove == "force": forced = True elif smove == "go": forced = False # Let's follow the clock of our opponent nodes = 2e4 if time > 0 and otim > 0: nodes *= time / otim m, s = sunfish.search(pos, maxn=nodes) # We don't play well once we have detected our death if s <= -sunfish.MATE_VALUE: print("resign") else: print("# %d %+d %d %d %s" % (0, s, 0, sunfish.nodes, pv(color, pos))) print("move", mrender(color, pos, m)) print("score before %d after %+d" % (pos.score, pos.value(m))) pos = pos.move(m) color = 1 - color elif smove.startswith("ping"): _, N = smove.split() print("pong", N) elif smove.startswith("usermove"): _, smove = smove.split() m = mparse(color, smove) pos = pos.move(m) color = 1 - color if not forced: stack.append("go") elif smove.startswith("time"): time = int(smove.split()[1]) elif smove.startswith("otim"): otim = int(smove.split()[1]) elif any(smove.startswith(x) for x in ("xboard", "post", "random", "hard", "accepted", "level")): pass else: print("Error (unkown command):", smove)
def main(): pos = parseFEN(FEN_INITIAL) forced = False color = WHITE time, otim = 1, 1 stack = [] while True: if stack: smove = stack.pop() else: smove = input() if smove == 'quit': break elif smove == 'protover 2': print('feature done=0') print('feature myname="Sunfish"') print('feature usermove=1') print('feature setboard=1') print('feature ping=1') print('feature sigint=0') print('feature variants="normal"') print('feature done=1') elif smove == 'new': stack.append('setboard ' + FEN_INITIAL) elif smove.startswith('setboard'): _, fen = smove.split(' ', 1) pos = parseFEN(fen) color = WHITE if fen.split()[1] == 'w' else BLACK elif smove == 'force': forced = True elif smove == 'go': forced = False # Let's follow the clock of our opponent nodes = 2e4 if time > 0 and otim > 0: nodes *= time/otim m, s = sunfish.search(pos, maxn=nodes) # We don't play well once we have detected our death if s <= -sunfish.MATE_VALUE: print('resign') else: print('# %d %+d %d %d %s' % (0, s, 0, sunfish.nodes, pv(color,pos))) print('move', mrender(color, pos, m)) print('score before %d after %+d' % (pos.score, pos.value(m))) pos = pos.move(m) color = 1-color elif smove.startswith('ping'): _, N = smove.split() print('pong', N) elif smove.startswith('usermove'): _, smove = smove.split() m = mparse(color, smove) pos = pos.move(m) color = 1-color if not forced: stack.append('go') elif smove.startswith('time'): time = int(smove.split()[1]) elif smove.startswith('otim'): otim = int(smove.split()[1]) elif any(smove.startswith(x) for x in ('xboard','post','random','hard','accepted','level')): pass else: print("Error (unkown command):", smove)