コード例 #1
0
ファイル: test.py プロジェクト: ZirconiumX/sunfish
def parseSAN(pos, color, msan):
	# Castling
	if msan == "O-O-O" and color == 0:
		p, src, dst = 'K', 'e1', 'c1'
	if msan == "O-O-O" and color == 1:
		p, src, dst = 'K', 'd1', 'f1'
	if msan == "O-O" and color == 0:
		p, src, dst = 'K', 'e1', 'g1'
	if msan == "O-O" and color == 1:
		p, src, dst = 'K', 'd1', 'b1'
	# Normal moves
	normal = re.match('([KQRBN])([a-h])?([1-8])?x?([a-h][1-8])', msan)
	if normal:
		p, fil, rank, dst = normal.groups()
		src = (fil or '[a-h]')+(rank or '[1-8]')
	# Pawn moves
	pawn = re.match('([a-h])?x?([a-h][1-8])', msan)
	if pawn:
		p, (fil, dst) = 'P', pawn.groups()
		src = (fil or '[a-h]')+'[1-8]'
	# Find possible match
	for i, j in pos.genMoves():
		# TODO: Maybe check for check here?
		csrc, cdst = sunfish.render(i), sunfish.render(j)
		if pos.board[i] == p and dst == cdst and re.match(src, csrc):
			return (i, j)# if color == 0 else (119-i, 119-j)
コード例 #2
0
ファイル: tools.py プロジェクト: denisMihaylov/BattleGround
def parseSAN(pos, msan):
    ''' Assumes board is rotated to position of current player '''
    # Normal moves
    normal = re.match('([KQRBN])([a-h])?([1-8])?x?([a-h][1-8])', msan)
    if normal:
        p, fil, rank, dst = normal.groups()
        src = (fil or '[a-h]') + (rank or '[1-8]')
    # Pawn moves
    pawn = re.match('([a-h])?x?([a-h][1-8])', msan)
    if pawn:
        p, (fil, dst) = 'P', pawn.groups()
        src = (fil or '[a-h]') + '[1-8]'
    # Castling
    if re.match(msan, "O-O-O[+#]?"):
        p, src, dst = 'K', 'e[18]', 'c[18]'
    if re.match(msan, "O-O[+#]?"):
        p, src, dst = 'K', 'e[18]', 'g[18]'
    # Find possible match
    for (i, j), _ in gen_legal_moves(pos):
        if get_color(pos) == WHITE:
            csrc, cdst = sunfish.render(i), sunfish.render(j)
        else:
            csrc, cdst = sunfish.render(119 - i), sunfish.render(119 - j)
        if pos.board[i] == p and re.match(dst, cdst) and re.match(src, csrc):
            return (i, j)
    assert False
コード例 #3
0
ファイル: test.py プロジェクト: NikAlexSer/sunfish
def parseSAN(pos, color, msan):
    ''' Assumes board is rotated to position of current player '''
    # Normal moves
    normal = re.match('([KQRBN])([a-h])?([1-8])?x?([a-h][1-8])', msan)
    if normal:
        p, fil, rank, dst = normal.groups()
        src = (fil or '[a-h]')+(rank or '[1-8]')
    # Pawn moves
    pawn = re.match('([a-h])?x?([a-h][1-8])', msan)
    if pawn:
        p, (fil, dst) = 'P', pawn.groups()
        src = (fil or '[a-h]')+'[1-8]'
    # Castling
    if re.match(msan, "O-O-O[+#]?"):
        p, src, dst = 'K', 'e[18]', 'c[18]'
    if re.match(msan, "O-O[+#]?"):
        p, src, dst = 'K', 'e[18]', 'g[18]'
    # Find possible match
    for i, j in gen_legal_moves(pos):
        if color == xboard.WHITE:
            csrc, cdst = sunfish.render(i), sunfish.render(j)
        else: csrc, cdst = sunfish.render(119-i), sunfish.render(119-j)
        if pos.board[i] == p and re.match(dst,cdst) and re.match(src,csrc):
            return (i, j)
    assert False
コード例 #4
0
ファイル: play.py プロジェクト: enrique-AMT/Finn
    def move(self, gn_current):
        assert (gn_current.board().turn != True)

        if gn_current.move is not None:
            # Apply last_move
            crdn = str(gn_current.move)
            move = (119 - sunfish.parse(crdn[0:2]),
                    119 - sunfish.parse(crdn[2:4]))
            self._pos = self._pos.move(move)

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

        depth = self._maxd
        t0 = time.time()
        best_value, best_move = negamax(self._pos, depth, alpha, beta, 1,
                                        self._func)
        crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1])
        print(depth, best_value, crdn, time.time() - t0)

        self._pos = self._pos.move(best_move)
        crdn = sunfish.render(best_move[0]) + sunfish.render(best_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
コード例 #5
0
    def move(self, gn_current):
        assert(gn_current.board().turn == 0)

        if gn_current.move is not None:
            # Apply last_move
            crdn = str(gn_current.move)
            move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4]))
            self._pos = self._pos.move(move)

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

        depth = self._maxd
        t0 = time.time()
        best_value, best_move = negamax(self._pos, depth, alpha, beta, 1, self._func)
        crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1])
        print depth, best_value, crdn, time.time() - t0

        self._pos = self._pos.move(best_move)
        crdn = sunfish.render(best_move[0]) + sunfish.render(best_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
コード例 #6
0
def parseSAN(pos, msan):
    ''' Assumes board is rotated to position of current player '''
    # Normal moves
    normal = re.match('([KQRBN])([a-h])?([1-8])?x?([a-h][1-8])', msan)
    if normal:
        p, fil, rank, dst = normal.groups()
        src = (fil or '[a-h]')+(rank or '[1-8]')
    # Pawn moves
    pawn = re.match('([a-h])?x?([a-h][1-8])', msan)
    if pawn:
        assert not re.search('[RBN]$', msan), 'Sunfish only supports queen promotion in {}'.format(msan)
        p, (fil, dst) = 'P', pawn.groups()
        src = (fil or '[a-h]')+'[1-8]'
    # Castling
    if re.match(msan, "O-O-O[+#]?"):
        p, src, dst = 'K', 'e[18]', 'c[18]'
    if re.match(msan, "O-O[+#]?"):
        p, src, dst = 'K', 'e[18]', 'g[18]'
    # Find possible match
    assert 'p' in vars(), 'No piece to move with {}'.format(msan)
    for (i, j), _ in gen_legal_moves(pos):
        if get_color(pos) == WHITE:
            csrc, cdst = sunfish.render(i), sunfish.render(j)
        else: csrc, cdst = sunfish.render(119-i), sunfish.render(119-j)
        if pos.board[i] == p and re.match(dst,cdst) and re.match(src,csrc):
            return (i, j)
    assert False, 'Couldn\'t find legal move matching {}. Had {}'.format(msan, {
        'p':p, 'src':src, 'dst': dst, 'mvs':list(gen_legal_moves(pos))})
コード例 #7
0
ファイル: chess.py プロジェクト: gdalle/SchroedingerChess
    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
コード例 #8
0
def renderSAN(pos, move):
    # TODO: How do we simply make this work for black as well?
    i, j = move
    csrc, cdst = sunfish.render(i), sunfish.render(j)
    # Check
    pos1 = pos.move(move)
    cankill = lambda p: any(p.board[b] == 'k' for a, b in p.genMoves())
    check = ''
    if cankill(pos1.rotate()):
        check = '+'
        if all(cankill(pos1.move(move1)) for move1 in pos1.genMoves()):
            check = '#'
    # Castling
    if pos.board[i] == 'K' and csrc == 'e1' and cdst in ('c1', 'g1'):
        if cdst == 'c1':
            return 'O-O-O' + check
        return 'O-O' + check
    # Pawn moves
    if pos.board[i] == 'P':
        pro = '=Q' if cdst[1] == '8' else ''
        cap = csrc[0] + 'x' if pos.board[j] != '.' or j == pos.ep else ''
        return cap + cdst + pro + check
    # Normal moves
    p = pos.board[i]
    srcs = [a for a, b in pos.genMoves() if pos.board[a] == p and b == j]
    # TODO: We can often get away with just sending the rank or file here.
    src = csrc if len(srcs) > 1 else ''
    cap = 'x' if pos.board[j] != '.' else ''
    return p + src + cap + cdst + check
コード例 #9
0
    def move(self, gn_current):
        sys.path.append("/Users/Brennen/sunfish")
        import sunfish
        searcher = sunfish.Searcher()

        assert (gn_current.board().turn == False)

        # 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()
        #print self._maxn
        move, score = searcher.search(self._pos, secs=5)
        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
コード例 #10
0
ファイル: play3.py プロジェクト: SilenceDZ/ConvChess
    def move(self, gn_current):
        if 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)
            #self.first_move = False
            #t0 = time.time()
            move, score = sunfish_mod3.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])
        else:
            if gn_current.move is not None:
                # Apply last_move
                crdn = str(gn_current.move)
                move = (119 - sunfish.parse(crdn[0:2]),
                        119 - sunfish.parse(crdn[2:4]))
                self._pos = self._pos.move(move)
            #t0 = time.time()
            move, score = sunfish_mod3.search(self._pos, maxn=self._maxn)
            #print time.time() - t0, move, score
            self._pos = self._pos.move(move)

            crdn = sunfish.render(move[0]) + sunfish.render(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
コード例 #11
0
    def move(self, gn_current):
        searcher = sunfish.Searcher()

        # assert(gn_current.board().turn == False)

        # parse UCI move into Sunfish format 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()
        # calls Sunfish's search function to find a move
        move, score = searcher.search(self._pos, 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)

        # updates game moves and returns board
        gn_new = chess.pgn.GameNode()
        gn_new.parent = gn_current
        gn_new.move = move

        return gn_new
コード例 #12
0
ファイル: play3.py プロジェクト: ashudeep/ConvChess
    def move(self, gn_current):
        if 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)
            #self.first_move = False
            #t0 = time.time()
            move, score = sunfish_mod3.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])
        else:
            if gn_current.move is not None:
                # Apply last_move
                crdn = str(gn_current.move)
                move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4]))
                self._pos = self._pos.move(move)
            #t0 = time.time()
            move, score = sunfish_mod3.search(self._pos, maxn=self._maxn)
            #print time.time() - t0, move, score
            self._pos = self._pos.move(move)

            crdn = sunfish.render(move[0]) + sunfish.render(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
コード例 #13
0
ファイル: test.py プロジェクト: Athul-Biju/sunfish
def renderSAN(pos, move):
    # TODO: How do we simply make this work for black as well?
    i, j = move
    csrc, cdst = sunfish.render(i), sunfish.render(j)
    # Check
    pos1 = pos.move(move)
    cankill = lambda p: any(p.board[b]=='k' for a,b in p.genMoves())
    check = ''
    if cankill(pos1.rotate()):
        check = '+'
        if all(cankill(pos1.move(move1)) for move1 in pos1.genMoves()):
            check = '#'
    # Castling
    if pos.board[i] == 'K' and csrc == 'e1' and cdst in ('c1','g1'):
        if cdst == 'c1':
            return 'O-O-O' + check
        return 'O-O' + check
    # Pawn moves
    if pos.board[i] == 'P':
        pro = '=Q' if cdst[1] == '8' else ''
        cap = csrc[0] + 'x' if pos.board[j] != '.' or j == pos.ep else ''
        return cap + cdst + pro + check
    # Normal moves
    p = pos.board[i]
    srcs = [a for a,b in pos.genMoves() if pos.board[a] == p and b == j]
    # TODO: We can often get away with just sending the rank or file here.
    src = csrc if len(srcs) > 1 else ''
    cap = 'x' if pos.board[j] != '.' else ''
    return p + src + cap + cdst + check
コード例 #14
0
    def engine_move(self):
        # Fire up the engine to look for a move.
        start = time.time()
        for _depth, move, score in self.searcher.search(
                self.hist[-1], self.hist):
            if time.time() - start > 1:
                break

        self.lastmove = sf.render(119 - move[0]) + sf.render(119 - move[1])
        self.hist.append(self.hist[-1].move(move))
        self.togglePlayer()
        return self.lastmove
コード例 #15
0
ファイル: ajedrez_ia.py プロジェクト: barrazamiguel/pydrez
    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()
コード例 #16
0
ファイル: test.py プロジェクト: AmineYaiche/sunfish
def perft(pos, depth, divide=False):
	if depth == 0:
		return 1
	res = 0
	for m in pos.genMoves():
		pos1 = pos.move(m)
		# Make sure the move was legal
		if not any(pos1.value(m) >= MATE_VALUE for m in pos1.genMoves()):
			sub = perft(pos1, depth-1, False)
			if divide:
				print(" "*depth+render(m[0])+render(m[1]), sub)
			res += sub
	return res
コード例 #17
0
    def move_computer(self):
        move, score = self.searcher.search(self.pos, secs=0.5)
        self.pos = self.pos.move(move)

        self.isPlayerTurn = True
        if self.isPlayerwhite:
            uci_move = sunfish.render(119 - move[0]) + sunfish.render(119 -
                                                                      move[1])
        else:
            uci_move = sunfish.render(move[0]) + sunfish.render(move[1])

        annotation = self.get_kor_sentence(uci_move, False)

        return (uci_move, annotation)
コード例 #18
0
def renderSAN(pos, move):
    ''' Assumes board is rotated to position of current player '''
    i, j = move
    csrc, cdst = sunfish.render(i), sunfish.render(j)
    # Rotate flor black
    if get_color(pos) == BLACK:
        csrc, cdst = sunfish.render(119 - i), sunfish.render(119 - j)
    # Check
    pos1 = pos.move(move)
    cankill = lambda p: any(p.board[b] == 'k' for a, b in p.gen_moves())
    check = ''
    if cankill(pos1.rotate()):
        check = '+'
        if all(cankill(pos1.move(move1)) for move1 in pos1.gen_moves()):
            check = '#'
    # Castling
    if pos.board[i] == 'K' and abs(i - j) == 2:
        if get_color(pos) == WHITE and j > i or get_color(
                pos) == BLACK and j < i:
            return 'O-O' + check
        else:
            return 'O-O-O' + check
    # Pawn moves
    if pos.board[i] == 'P':
        pro = '=Q' if sunfish.A8 <= j <= sunfish.H8 else ''
        cap = csrc[0] + 'x' if pos.board[j] != '.' or j == pos.ep else ''
        return cap + cdst + pro + check
    # Figure out what files and ranks we need to include
    srcs = [
        a for (a, b), _ in gen_legal_moves(pos)
        if pos.board[a] == pos.board[i] and b == j
    ]
    srcs_file = [
        a for a in srcs if (a - sunfish.A1) % 10 == (i - sunfish.A1) % 10
    ]
    srcs_rank = [
        a for a in srcs if (a - sunfish.A1) // 10 == (i - sunfish.A1) // 10
    ]
    assert srcs, 'No moves compatible with {}'.format(move)
    if len(srcs) == 1: src = ''
    elif len(srcs_file) == 1: src = csrc[0]
    elif len(srcs_rank) == 1: src = csrc[1]
    else: src = csrc
    # Normal moves
    p = pos.board[i]
    cap = 'x' if pos.board[j] != '.' else ''
    return p + src + cap + cdst + check
コード例 #19
0
    def move(self, gn_current):
        #assert(gn_current.board().turn == True)

        if gn_current.move is not None:
            # Apply last_move
            crdn = str(gn_current.move)
            move = (119 - sunfish.parse(crdn[0:2]),
                    119 - sunfish.parse(crdn[2:4]))
            self._pos = self._pos.move(move)
            print 'setting position', move

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

        depth = self._maxd
        t0 = time.time()
        #print 'pos: ', self._pos
        #what is self._pos
        #depth is computation depth in tree
        #alpha is -inf
        #beta is positive inf
        #1 is 1
        #func is the pickle model
        best_value, best_move = negamax(self._pos, depth, alpha, beta, 1,
                                        self._func)
        #print 'bestMove: ', best_move
        crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1])
        #print 'crdn', crdn
        #print depth, best_value, crdn, time.time() - t0

        self._pos = self._pos.move(best_move)
        print 'setting position', best_move
        #print 'crdn[0:2]', crdn[0:2]
        #print 'crdn[2:4]', crdn[2:4]

        #print 'bestMove', best_move
        crdn = sunfish.render(best_move[0]) + sunfish.render(best_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
コード例 #20
0
ファイル: play3.py プロジェクト: SilenceDZ/ConvChess
    def move(self, gn_current):
        assert (gn_current.board().turn == 0)

        if gn_current.move is not None:
            # Apply last_move
            crdn = str(gn_current.move)
            move = (119 - sunfish.parse(crdn[0:2]),
                    119 - sunfish.parse(crdn[2:4]))
            self._pos = self._pos.move(move)

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

        depth = self._maxd
        t0 = time.time()
        bb = pos_board_to_bitboard(self._pos.board)
        if args.multilayer:
            im = convert_bitboard_to_image_2(bb)
        else:
            im = convert_bitboard_to_image(bb)
        im = np.rollaxis(im, 2, 0)
        if args.elo_layer:
            im = np.append(im, elo_layer, axis=0)
        #print im.shape
        best_value, best_move = negamax(im,
                                        depth,
                                        alpha,
                                        beta,
                                        1,
                                        maxm=self._maxm)
        best_move = (sunfish.parse(best_move[0:2]),
                     sunfish.parse(best_move[2:4]))
        crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1])
        print depth, best_value, crdn, time.time() - t0

        self._pos = self._pos.move(best_move)
        crdn = sunfish.render(best_move[0]) + sunfish.render(best_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
コード例 #21
0
def renderFEN(pos, half_move_clock=0, full_move_clock=1):
    color = 'wb'[get_color(pos)]
    if get_color(pos) == BLACK:
        pos = pos.rotate()
    board = '/'.join(pos.board.split())
    board = re.sub(r'\.+', (lambda m: str(len(m.group(0)))), board)
    castling = ''.join(itertools.compress('KQkq', pos.wc[::-1]+pos.bc)) or '-'
    ep = sunfish.render(pos.ep) if not pos.board[pos.ep].isspace() else '-'
    clock = '{} {}'.format(half_move_clock, full_move_clock)
    return ' '.join((board, color, castling, ep, clock))
コード例 #22
0
ファイル: tools.py プロジェクト: mekhami/sunfish
def renderFEN(pos, half_move_clock=0, full_move_clock=1):
    color = 'wb'[get_color(pos)]
    if get_color(pos) == BLACK:
        pos = pos.rotate()
    board = '/'.join(pos.board.split())
    board = re.sub(r'\.+', (lambda m: str(len(m.group(0)))), board)
    castling = ''.join(itertools.compress('KQkq', pos.wc[::-1]+pos.bc)) or '-'
    ep = sunfish.render(pos.ep) if not pos.board[pos.ep].isspace() else '-'
    clock = '{} {}'.format(half_move_clock, full_move_clock)
    return ' '.join((board, color, castling, ep, clock))
コード例 #23
0
ファイル: test.py プロジェクト: AmineYaiche/sunfish
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
コード例 #24
0
ファイル: test.py プロジェクト: NikAlexSer/sunfish
def renderSAN(pos, color, move):
    ''' Assumes board is rotated to position of current player '''
    i, j = move
    csrc, cdst = sunfish.render(i), sunfish.render(j)
    # Rotate flor black
    if color == xboard.BLACK:
        csrc, cdst = sunfish.render(119-i), sunfish.render(119-j)
    # Check
    pos1 = pos.move(move)
    cankill = lambda p: any(p.board[b]=='k' for a,b in p.gen_moves())
    check = ''
    if cankill(pos1.rotate()):
        check = '+'
        if all(cankill(pos1.move(move1)) for move1 in pos1.gen_moves()):
            check = '#'
    # Castling
    if pos.board[i] == 'K' and abs(i-j) == 2:
        if color == xboard.WHITE and j > i or color == xboard.BLACK and j < i:
            return 'O-O' + check
        else:
            return 'O-O-O' + check
    # Pawn moves
    if pos.board[i] == 'P':
        pro = '=Q' if sunfish.A8 <= j <= sunfish.H8 else ''
        cap = csrc[0] + 'x' if pos.board[j] != '.' or j == pos.ep else ''
        return cap + cdst + pro + check
    # Figure out what files and ranks we need to include
    srcs = [a for a,b in gen_legal_moves(pos) if pos.board[a] == pos.board[i] and b == j]
    srcs_file = [a for a in srcs if (a - sunfish.A1) % 10 == (i - sunfish.A1) % 10]
    srcs_rank = [a for a in srcs if (a - sunfish.A1) // 10 == (i - sunfish.A1) // 10]
    assert len(srcs) > 0
    if len(srcs) == 1: src = ''
    elif len(srcs_file) == 1: src = csrc[0]
    elif len(srcs_rank) == 1: src = csrc[1]
    else: src = csrc
    # Normal moves
    p = pos.board[i]
    cap = 'x' if pos.board[j] != '.' else ''
    return p + src + cap + cdst + check
コード例 #25
0
def parseSAN(pos, color, msan):
    # Normal moves
    normal = re.match('([KQRBN])([a-h])?([1-8])?x?([a-h][1-8])', msan)
    if normal:
        p, fil, rank, dst = normal.groups()
        src = (fil or '[a-h]') + (rank or '[1-8]')
    # Pawn moves
    pawn = re.match('([a-h])?x?([a-h][1-8])', msan)
    if pawn:
        p, (fil, dst) = 'P', pawn.groups()
        src = (fil or '[a-h]') + '[1-8]'
    # Castling
    if msan == "O-O-O":
        p, src, dst = 'K', 'e1|d1', 'c1|f1'
    if msan == "O-O":
        p, src, dst = 'K', 'e1|d1', 'g1|b1'
    # Find possible match
    for i, j in pos.genMoves():
        # TODO: Maybe check for check here?
        csrc, cdst = sunfish.render(i), sunfish.render(j)
        if pos.board[i] == p and re.match(dst, cdst) and re.match(src, csrc):
            return (i, j)
コード例 #26
0
ファイル: play3.py プロジェクト: ashudeep/ConvChess
    def move(self, gn_current):
        assert(gn_current.board().turn == 0)

        if gn_current.move is not None:
            # Apply last_move
            crdn = str(gn_current.move)
            move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4]))
            self._pos = self._pos.move(move)

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

        depth = self._maxd
        t0 = time.time()
        bb = pos_board_to_bitboard(self._pos.board)
        if args.multilayer:
            im = convert_bitboard_to_image_2(bb)
        else:
            im = convert_bitboard_to_image(bb)
        im = np.rollaxis(im,2,0)
        if args.elo_layer:
            im = np.append(im,elo_layer,axis=0)
        #print im.shape
        best_value, best_move = negamax(im, depth, alpha, beta, 1, maxm=self._maxm)
        best_move = (sunfish.parse(best_move[0:2]), sunfish.parse(best_move[2:4]))
        crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1])
        print depth, best_value, crdn, time.time() - t0

        self._pos = self._pos.move(best_move)
        crdn = sunfish.render(best_move[0]) + sunfish.render(best_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
コード例 #27
0
ファイル: book_play.py プロジェクト: saurabhk7/deep-murasaki
	def move(self, gn_current):
		import sunfish

		assert(gn_current.board().turn == False)

		# 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
コード例 #28
0
    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 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
コード例 #30
0
ファイル: ChessBot.py プロジェクト: aeturnum/NeonDJBot
	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)
コード例 #31
0
def main():

    md = MoveDetector('http://192.168.178.39/webcam/?action=stream')
    o = Octoprint(api_key=secrets.api_key)

    print('Welcome to 3d printer chess.')
    s = None
    while s != 'n' and s != 'y':
        s = input('Should we home the 3d printer? (y/n)\n')
    if s == 'y':
        o.home()

    print('Homing finished. Parking.')
    o.park()

    hist = [Position(initial, 0, (True,True), (True,True), 0, 0)]
    searcher = Searcher()

    print('Game started')
    while True:
        print_pos(hist[-1])

        if hist[-1].score <= -MATE_LOWER:
            print('You lost')
            break
    
        print('Your move:\a')
        move = None
        while move not in hist[-1].gen_moves():
            match = re.match('([a-h][1-8])'*2, md.getMove())
            if match:
                move = parse(match.group(1)), parse(match.group(2))
            else:
                print('Please enter a move like g8f6')
        hist.append(hist[-1].move(move))

        print_pos(hist[-1].rotate())

        if hist[-1].score <= -MATE_LOWER:
            print('You won')
            break

        start = time.time()
        for _depth, move, score in searcher.search(hist[-1], hist):
            if time.time() - start > 1:
                break

        if score == MATE_UPPER:
            print('Checkmate!')
    
        smove = render(119-move[0]) + render(119-move[1])
        print('My move:', smove)
        hist.append(hist[-1].move(move))

        #print(hist[-1][0])

        xf,yf,xt,yt = parse_move(smove)
        capturing = not new_field_is_empty(xt, yt, hist)
        if capturing:
            pawn = is_pawn(xt,yt, hist, last_move=True)
            #print('Capturing pawn:', pawn)
            o.remove(xt,yt,pawn)
        pawn = is_pawn(xt,yt, hist)
        o.from_to(xf,yf,xt,yt, pawn=pawn)
コード例 #32
0
def mrender(color, pos, m):
    # Sunfish always assumes promotion to queen
    p = 'q' if sunfish.A8 <= m[1] <= sunfish.H8 and pos.board[
        m[0]] == 'P' else ''
    m = m if color == WHITE else (119 - m[0], 119 - m[1])
    return sunfish.render(m[0]) + sunfish.render(m[1]) + p
コード例 #33
0
ファイル: xboard.py プロジェクト: NoahTheDuke/Chess2
def mrender(pos, m):
    # Sunfish always assumes promotion to queen
    p = 'q' if sunfish.A8 <= m[1] <= sunfish.H8 and pos.board[
        m[0]] == 'P' else ''
    if pos.color == 0: m = (119 - m[0], 119 - m[1])
    return sunfish.render(m[0]) + sunfish.render(m[1]) + p
コード例 #34
0
ファイル: xboard.py プロジェクト: NoahTheDuke/Chess2
def mrender(pos, m):
    # Sunfish always assumes promotion to queen
    p = 'q' if sunfish.A8 <= m[1] <= sunfish.H8 and pos.board[m[0]] == 'P' else ''
    if pos.color == 0: m = (119-m[0], 119-m[1])
    return sunfish.render(m[0]) + sunfish.render(m[1]) + p
コード例 #35
0
ファイル: tools.py プロジェクト: denisMihaylov/BattleGround
def mrender(pos, m):
    # Sunfish always assumes promotion to queen
    if sunfish.A8 <= m[1] <= sunfish.H8 and pos.board[m[0]] == 'P':
        p = 'q'
    m = m if get_color(pos) == WHITE else (119-m[0], 119-m[1])
    return sunfish.render(m[0]) + sunfish.render(m[1]) + p
コード例 #36
0
ファイル: tools.py プロジェクト: denisMihaylov/BattleGround
def mrender(pos, m):
    # Sunfish always assumes promotion to queen
    if sunfish.A8 <= m[1] <= sunfish.H8 and pos.board[m[0]] == 'P':
        p = 'q'
    m = m if get_color(pos) == WHITE else (119 - m[0], 119 - m[1])
    return sunfish.render(m[0]) + sunfish.render(m[1]) + p
コード例 #37
0
ファイル: xboard.py プロジェクト: ZirconiumX/sunfish
def mrender(color, pos, m):
	# Sunfish always assumes promotion to queen
	p = 'q' if sunfish.A8 <= m[1] <= sunfish.H8 and pos.board[m[0]] == 'P' else ''
	m = m if color == WHITE else (119-m[0], 119-m[1])
	return sunfish.render(m[0]) + sunfish.render(m[1]) + p