簡體   English   中英

蟒蛇國際象棋:替換。 和 #

[英]python-chess: replace . with #

python 國際象棋棋盤可以根據其源代碼的這一部分返回棋盤的 ascii 表示,其中點為空方塊:

def __str__(self) -> str:
    builder = []

    for square in SQUARES_180:
        piece = self.piece_at(square)

        if piece:
            builder.append(piece.symbol())
        else:
            builder.append(".")

        if BB_SQUARES[square] & BB_FILE_H:
            if square != H1:
                builder.append("\n")
        else:
            builder.append(" ")

    return "".join(builder)

假設我們生成一個板並將其傳遞給打印 function:

>>> import chess
>>> board = chess.Board("rnbq1rk1/ppp1ppbp/3p1np1/8/2PPP3/2N2N2/PP2BPPP/R1BQK2R b KQ - 3 6")
>>> print(board)
r n b q . r k .
p p p . p p b p
. . . p . n p .
. . . . . . . .
. . P P P . . .
. . N . . N . .
P P . . B P P P
R . B Q K . . R

但是我們想用哈希替換所有的點:

r n b q # r k #
p p p # p p b p
# # # p # n p #
# # # # # # # #
# # P P P # # #
# # N # # N # #
P P # # B P P P
R # B Q K # # R

正則表達式庫無法處理板 object:

>>> import re
>>> re.sub(r'\.', r'#', board)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 192, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

在自定義 function 中克隆 object 方法:

def hashboard(board) -> str:
    builder = []
    for square in chess.SQUARES_180:
        piece = board.piece_at(square)
        if piece:
            builder.append(piece.symbol())
        else:
            builder.append("#")
        if chess.BB_SQUARES[square] & chess.BB_FILE_H:
            if square != chess.H1:
                builder.append("\n")
        else:
            builder.append(" ")
    return "".join(builder)

一個解法:

>>> print(hashboard(board))
r n b q # r k #
p p p # p p b p
# # # p # n p #
# # # # # # # #
# # P P P # # #
# # N # # N # #
P P # # B P P P
R # B Q K # # R

我能做得更好嗎? 我是一個業余的、自學成才的程序員。 我很感激任何反饋。

board是國際象棋的一個實例chess.Board object。 __str__方法返回re.sub (或者只是.replace ,在這個簡單的例子中)可以作用的字符串。

這有效:

print(str(board).replace('.', '#'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM