Ejemplo n.º 1
0
 def __init__(self, board, evalfunction=None, depth=0):
     if evalfunction is None:
         evalfunction = evaluation.Classical()
     self.board = board
     self.evaluation = evalfunction
     self.depth = depth
     self._score = None
Ejemplo n.º 2
0
def test_position(fen, blunders):
    position, searcher = setUpPosition(fen)
    for depth, move, score in searcher.search(position.board,
                                              evaluation.Classical(),
                                              maxdepth=5,
                                              maxtime=30):
        print(searcher.nodes, depth, move, score)
    print(depth, move, score)
Ejemplo n.º 3
0
def main():
    #logging.basicConfig(level=logging.INFO)
    board = chess.Board()
    boardeval = evaluation.Classical()
    searcher = Searcher()
    while True:
        #print_pos(board)

        if board.is_checkmate():
            print("You lost")
            break

        # We query the user until she enters a (pseudo) legal move.
        while True:
            inp = input('Your move: ')
            try:
                move = chess.Move.from_uci(inp)
                if move not in board.legal_moves:
                    raise ValueError
            except ValueError:
                print("{} is not a legal move".format(move))
            else:
                break

        board.push(move)

        # After our move we rotate the board and print it again.
        # This allows us to see the effect of our move.
        print_pos(board)

        if board.is_checkmate():
            print("You won")
            break

        # Fire up the engine to look for a move.
        start = time.time()
        for _depth, move, score, stack in searcher.search(board,
                                                          boardeval,
                                                          maxdepth=10,
                                                          maxtime=5):
            print(_depth, move, score, searcher.nodes, stack)
            # if time.time() - start > 2:
            #     break

        if score == MATE_UPPER:
            print("Checkmate!")

        # The black player moves from a rotated position, so we have to
        # 'back rotate' the move before printing it.
        print("My move:", board.san(move))
        board.push(move)
        print_pos(board)
Ejemplo n.º 4
0
 def _test_timeout(self):
     """Test timeout on game SKsTefjW"""
     fen = "r1b1k1nr/ppp2ppp/2np1q2/4p3/2B1P3/2NPB3/PPP1NbPP/R2Q1R1K b kq - 1 8"
     position, searcher = setUpPosition(fen)
     # best = searcher.bound(position, 0, 2)
     # #print(best, searcher.tp_move[position])
     # best = searcher.bound(position, position.score, 10)
     # print(best, searcher.tp_move[position])
     start = time.clock()
     for depth, move, score in searcher.search(position.board, evaluation.Classical(), maxdepth=10, maxtime=5):
         print(depth, move, score)
         print(searcher.nodes)
         #print(searcher.tp_move[position])
         end = time.clock()
         print("Time taken = ", end - start)
         start = end
Ejemplo n.º 5
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('module',
                        help='sunfish.py file (without .py)',
                        type=str,
                        default='amwafish',
                        nargs='?')
    parser.add_argument('--tables',
                        metavar='pst',
                        help='alternative pst table',
                        type=str,
                        default=None)
    args = parser.parse_args()

    amwafish = importlib.import_module(args.module)
    #logging.basicConfig(filename='amwafish.log', level=logging.DEBUG)

    out = Unbuffered(sys.stdout)

    def output(line):
        print(line, file=out)
        logging.debug(line)

    pos = chess.Board()
    searcher = amwafish.Searcher()
    our_time, opp_time = 1000, 1000  # time in centi-seconds
    show_thinking = True
    options = {}
    eval_function = evaluation.get_evaluation_function()
    stack = []
    while True:
        logging.debug(f'>>> in loop ')
        if stack:
            smove = stack.pop()
        else:
            smove = input()

        logging.debug(f'>>> {smove} ')
        if smove.startswith('setoption'):
            optionMatcher = re.compile(
                "setoption name (?P<name>.*) value (?P<value>.*)")
            match = optionMatcher.match(smove)
            if match:
                options[match.group("name")] = match.group("value")

        if smove == 'quit':
            break

        elif smove == 'uci':
            output('id name amwafish')
            output('id author Sven Wambecq')
            output('uciok')

        elif smove == 'isready':
            output('readyok')

        elif smove == 'ucinewgame':
            stack.append('position fen ' + chess.STARTING_FEN)

        elif smove.startswith('position fen'):
            _, _, data = smove.split(' ', 2)
            try:
                fen, moves = data.split('moves')
                moves = moves.strip().split(' ')
            except ValueError:
                fen = data
                moves = []
            try:
                chess960 = options["UCI_Chess960"] == "true"
            except KeyError:
                chess960 = False

            try:
                board = get_variant(options["UCI_Variant"])(fen,
                                                            chess960=chess960)
                eval_function = evaluation.get_evaluation_function(
                    options["UCI_Variant"])
            except KeyError:
                board = chess.Board()
                eval_function = evaluation.Classical()
            for move in moves:
                board.push(chess.Move.from_uci(move))
            pos = board

        elif smove.startswith('position startpos'):
            params = smove.split(' ')
            pos = chess.Board()

            if len(params) > 2 and params[2] == 'moves':
                for move in params[3:]:
                    pos.push(chess.Move.from_uci(move))

        elif smove.startswith('go'):
            #  default options
            depth = 1000
            movetime = -1

            _, *params = smove.split(' ')
            for param, val in zip(*2 * (iter(params), )):
                if param == 'depth':
                    depth = int(val)
                if param == 'movetime':
                    movetime = int(val)
                if param == 'wtime':
                    our_time = int(val)
                if param == 'btime':
                    opp_time = int(val)

            moves_remain = 40

            for sdepth, _move, _score in searcher.search(pos,
                                                         eval_function,
                                                         maxdepth=depth,
                                                         maxtime=our_time /
                                                         moves_remain / 1000):
                pass
            else:
                if _move:
                    output('bestmove ' + _move.uci())

        elif smove.startswith('time'):
            our_time = int(smove.split()[1])

        elif smove.startswith('otim'):
            opp_time = int(smove.split()[1])

        else:
            pass
Ejemplo n.º 6
0
def setUpPosition(fen):
    board = chess.Board(fen)
    pos = amwafish.Position(board, evaluation.Classical(), depth=0)
    searcher = amwafish.Searcher()
    return pos, searcher
Ejemplo n.º 7
0
 def test_position(self, fen, best):
     position, searcher = setUpPosition(fen)
     for depth, move, score in searcher.search(position.board, evaluation.Classical(), maxdepth=10, maxtime=5):
         print(searcher.nodes)
     print(move)
     self.assertEqual(move, chess.Move.from_uci(best))
Ejemplo n.º 8
0
 def test_position(self, fen, blunders):
     position, searcher = setUpPosition(fen)
     for depth, move, score in searcher.search(position.board, evaluation.Classical(), maxdepth=10, maxtime=5):
         print(searcher.nodes, depth, move, score)
     print(depth, move, score)
     self.assertNotIn(move, [chess.Move.from_uci(blunder) for blunder in blunders])