def reset(self, white=True):
        self.pos = sunfish.Position(sunfish.initial, 0, (True, True),
                                    (True, True), 0, 0)
        self.isPlayerTurn = white
        self.isPlayerwhite = white

        self.board = chess.board()
示例#2
0
def parseFEN(fen):
    """ Parses a string in Forsyth-Edwards Notation into a Position """
    armies, stones, board, color, castling, enpas, hclock, fclock = fen.split()
    wa, ba = int(army_abr_dict[armies[0]]), int(
        army_abr_dict[armies[1].upper()])
    ws, bs = int(stones[0]), int(stones[1])
    board = re.sub('\d', (lambda m: '.' * int(m.group(0))), board)
    board = list(' ' * 9 + '\n' + ' ' * 9 + '\n ' +
                 '\n '.join(board.split('/')) + '\n' + ' ' * 9 + '\n' +
                 ' ' * 10)
    change = lambda p, a: classic_piece_to_army_piece_dict[p][a - 1]
    for num, char in enumerate(board):
        if char == '.': continue
        if char.isspace(): continue
        if char.isupper():
            board[num] = change(char, wa)
        else:
            board[num] = change(char.upper(), ba).lower()
    board = "".join(board)
    color = 0 if color == 'w' else 1
    if color == 1:
        board = board[::-1].swapcase()
    wc = ('Q' in castling, 'K' in castling)
    bc = ('k' in castling, 'q' in castling)
    ep = sunfish.parse(enpas) if enpas != '-' else 0
    score = sum(sunfish.pst[p][i] for i, p in enumerate(board)
                if p.isupper() and p != 'U')
    score -= sum(sunfish.pst[p.upper()][i] for i, p in enumerate(board)
                 if p.islower() and p != 'u')
    pos = sunfish.Position(board, color, False, score, wa, ba, ws, bs, wc, bc,
                           ep, 0)
    return pos
示例#3
0
    def sunfish_move_suggestion(self, secs):
        board = ("         \n" "         \n")
        for y in reversed(range(8)):
            board += ' '
            for x in range(8):
                if self.grid[x][y] is None:
                    board += '.'
                elif self.grid[x][y].color_name == "W":
                    board += self.grid[x][y].nature_guess
                else:
                    board += self.grid[x][y].nature_guess.lower()
            board += '\n'
        board += ("         \n" "         \n")
        pos = sunfish.Position(board, 0, (False, False), (False, False), 0, 0)
        if self.time % 2 == 1:
            pos = pos.rotate()

        searcher = sunfish.Searcher()
        move, score = searcher.search(pos, secs=secs)
        if move is None:
            raise IllegalMove("Sunfish didn't find a feasible move")
        if self.time % 2 == 1:
            move = (119 - move[0], 119 - move[1])
        first_square, last_square = sunfish.render(move[0]), sunfish.render(
            move[1])
        x1, y1, x2, y2 = self.translate_move((first_square, last_square))
        return x1, y1, x2, y2
示例#4
0
def parseFEN(fen):
	""" Parses a string in Forsyth-Edwards Notation into a Position """
	board, color, castling, enpas, hclock, fclock = fen.split()
	board = re.sub('\d', (lambda m: '.'*int(m.group(0))), board)
	board = ' '*19+'\n ' + '\n '.join(board.split('/')) + ' \n'+' '*19
	wc = ('Q' in castling, 'K' in castling)
	bc = ('k' in castling, 'q' in castling)
	ep = sunfish.parse(enpas) if enpas != '-' else 0
	score = sum(sunfish.pst[p][i] for i,p in enumerate(board) if p.isupper())
	score -= sum(sunfish.pst[p.upper()][i] for i,p in enumerate(board) if p.islower())
	pos = sunfish.Position(board, score, wc, bc, ep, 0)
	return pos if color == 'w' else pos.rotate()
示例#5
0
def game(f_pred, f_train, learning_rate, momentum=0.9):
    pos = sunfish.Position(sunfish.initial, 0, (True, True), (True, True), 0,
                           0)

    data = []

    max_turns = 100

    for turn in range(max_turns):
        # Generate all possible moves
        Xs = []
        new_poss = []
        for move in pos.genMoves():
            new_pos = pos.move(move)
            Xs.append(sf2array(new_pos, False))
            new_poss.append(new_pos)

        # Calculate softmax probabilities
        ys = f_pred(Xs)
        zs = numpy.exp(ys)
        Z = sum(zs)
        ps = zs / Z
        i = weighted_random_sample(ps)

        # Append moves
        data.append((turn % 2, Xs[i]))
        pos = new_poss[i]

        if pos.board.find('K') == -1:
            break

        if turn == 0 and random.random() < 0.01:
            print(ys)

    if turn == max_turns - 1:
        return

    # White moves all even turns
    # If turn is even, it means white just moved, and black is up next
    # That means if turn is even, all even (black) boards are losses
    # If turn is odd, all odd (white) boards are losses
    win = (turn % 2)  # 0 = white, 1 = black

    #X = numpy.array([x for t, x in data], dtype=theano.config.floatX)
    #Y = numpy.array([(t ^ win) for t, x in data], dtype=theano.config.floatX)

    X = cp.array([x for t, x in data], dtype=theano.config.floatX)
    Y = cp.array([(t ^ win) for t, x in data], dtype=theano.config.floatX)

    loss, frac_correct = f_train(X, Y, learning_rate, momentum)

    return len(data), loss, frac_correct
 def parseFEN(self, fen, pst):
     board, color, castling, enpas, _hclock, _fclock = fen.split()
     board = re.sub(r'\d', (lambda m: '.' * int(m.group(0))), board)
     board = list(21 * ' ' + '  '.join(board.split('/')) + 21 * ' ')
     board[9::10] = ['\n'] * 12
     #if color == 'w': board[::10] = ['\n']*12
     #if color == 'b': board[9::10] = ['\n']*12
     board = ''.join(board)
     wc = ('Q' in castling, 'K' in castling)
     bc = ('k' in castling, 'q' in castling)
     ep = sunfish.parse(enpas) if enpas != '-' else 0
     score = sum(pst[p][i] for i, p in enumerate(board) if p.isupper())
     score -= sum(pst[p.upper()][119 - i] for i, p in enumerate(board)
                  if p.islower())
     pos = sunfish.Position(board, score, wc, bc, ep, 0)
     return pos if color == 'w' else pos.rotate()
    def __init__(self, white=True):
        self.pos = sunfish.Position(sunfish.initial, 0, (True, True),
                                    (True, True), 0, 0)
        self.searcher = sunfish.Searcher()
        self.isPlayerTurn = white
        self.isPlayerwhite = white

        self.board = chess.Board()
        context.log_level = 'error'

        data = {
            'fen': "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",
            'move': "Start",
            'player': "True",
            'ann': "None"
        }
        r = requests.post("http://141.223.163.184:5000/saveinfo", json=data)
示例#8
0
 def test_fen2(self):
     initial = sunfish.Position(sunfish.initial, 0, (True, True),
                                (True, True), 0, 0)
     for pos in tools.flatten_tree(tools.expand_position(initial), 3):
         fen = tools.renderFEN(pos)
         self.assertEqual(fen.split()[1], 'wb'[tools.get_color(pos)],
                          "Didn't read color correctly")
         pos1 = tools.parseFEN(fen)
         self.assertEqual(pos.board, pos1.board,
                          "Sunfish didn't correctly reproduce the board")
         self.assertEqual(pos.wc, pos1.wc)
         self.assertEqual(pos.bc, pos1.bc)
         ep = pos.ep if not pos.board[pos.ep].isspace() else 0
         ep1 = pos1.ep if not pos1.board[pos1.ep].isspace() else 0
         kp = pos.kp if not pos.board[pos.kp].isspace() else 0
         kp1 = pos1.kp if not pos1.board[pos1.kp].isspace() else 0
         self.assertEqual(ep, ep1)
         self.assertEqual(kp, kp1)
示例#9
0
 def init(self):
     initial = ('         \n'
                '         \n'
                ' r.b.kb.r\n'
                ' ppp.ppp.\n'
                ' n.....p.\n'
                ' ..P..n..\n'
                ' ........\n'
                ' P.......\n'
                ' ....KP.P\n'
                ' ...q...q\n'
                '         \n'
                '         \n')
     self.hist = [
         sf.Position(sf.initial, 0, (True, True), (True, True), 0, 0)
     ]
     self.activePlayer = self.PLAYER
     self.lastmove = None
示例#10
0
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 getMove(moveList):
    learnedModel = model
    currentBoardPosition = sunfish.Position(sunfish.initial, 0, (True,True), (True,True), 0, 0)
    #apply all moves in movelist to the currentBoardPosition
    player1 = True
    for move in moveList:
        if player1:
            formatedMove = (sunfish.parse(move[0:2]), sunfish.parse(move[2:4]))
        else:
            formatedMove = (119 - sunfish.parse(move[0:2]), 119 - sunfish.parse(move[2:4]))
        print 'formatedMove', formatedMove
        player1 = not(player1)
        currentBoardPosition = currentBoardPosition.move(formatedMove)

    # for depth in xrange(1, self._maxd+1):
    alpha = float('-inf')
    beta = float('inf')

    depth = 2
    t0 = time.time()

    best_value, best_move = negamax(currentBoardPosition, depth, alpha, beta, 1, learnedModel)
    moveStandardFormat = sunfish.render(best_move[0]) + sunfish.render(best_move[1])
    return moveStandardFormat
示例#12
0
 def __init__(self, maxn=1e4):
     self._pos = sunfish.Position(sunfish.initial, 0, (True, True),
                                  (True, True), 0, 0)
     self._maxn = maxn
示例#13
0
 def __init__(self, maxn=1e4, dumb=False):
     self._pos = sunfish.Position(sunfish.initial, 0, (True, True),
                                  (True, True), 0, 0)
     self._maxn = maxn
     if dumb:
         sunfish.set_pst()
示例#14
0
 def __init__(self, maxm=10, maxd=2):
     #self._func = func
     self._pos = sunfish.Position(sunfish.initial, 0, (True, True),
                                  (True, True), 0, 0)
     self._maxd = maxd
     self._maxm = maxm
示例#15
0
 def __init__(self, func, maxd=5):
     self._func = func
     self._pos = sunfish.Position(sunfish.initial, 0, (True, True),
                                  (True, True), 0, 0)
     self._maxd = maxd
示例#16
0
 def reset_position(self):
     self.pos = sunfish.Position(sunfish.initial, 0, (True, True),
                                 (True, True), 0, 0, self.pst_padded)
     self.searcher = sunfish.Searcher()
示例#17
0
 def __init__(self, prefix):
     self.load_from_pckl(prefix)
     self.pos = sunfish.Position(sunfish.initial, 0, (True, True),
                                 (True, True), 0, 0, self.pst_padded)
     self.searcher = sunfish.Searcher()
示例#18
0
        DeeperBlue.last_moves = []

        Piececlasses.list_of_pieces = []

        previous_pieces = []

        for i in DeeperBlue.position:

            for j in i:

                if not j == "empty":

                    Piececlasses.list_of_pieces.append(Piececlasses.Piece(j))

        sunfish.pos = sunfish.Position(sunfish.initial, 0, (True, True),
                                       (True, True), 0, 0)

        sunfish.searcher = sunfish.Searcher()

        #print (time.time() - t)

        count += 1

        print(count)

except KeyboardInterrupt:

    print("Write experience to file?")

    user_input = input("Your choice: ")
示例#19
0
文件: play.py 项目: enrique-AMT/Finn
 def __init__(self, secs=1):
     self._searcher = sunfish.Searcher()
     self._pos = sunfish.Position(sunfish.initial, 0, (True, True),
                                  (True, True), 0, 0)
     self._secs = secs
示例#20
0
 def __init__(self, func=evaluate_moves, maxm=10 , maxd=5):
     self._func = func
     self._pos = sunfish.Position(sunfish.initial, 0, (True,True), (True,True), 0, 0)
     self._maxd = maxd
     self._maxm = maxm