我想對Ruby的幾行Python的轉換,從由托馬斯客戶簽署本優秀的文章:http://wordaligned.org/articles/drawing-chess-positions代碼翻譯,用Python和Ruby
(注:我是一個真正做大的Python小白)
這裏是原來的Python版本的副本:
def expand_blanks(fen):
'''Expand the digits in an FEN string into spaces
>>> expand_blanks("rk4q3")
'rk q '
'''
def expand(match):
return ' ' * int(match.group(0))
return re.compile(r'\d').sub(expand, fen)
def outer_join(sep, ss):
'''Like string.join, but encloses the result with outer separators.
Example:
>>> outer_join('|', ['1', '2', '3'])
'|1|2|3|'
'''
return '%s%s%s' % (sep, sep.join(ss), sep)
def ascii_draw_chess_position(fen):
'''Returns an ASCII picture of pieces on a chessboard.'''
pieces = expand_blanks(fen).replace('/', '')
divider = '+-+-+-+-+-+-+-+-+\n'
rows = ((outer_join('|', pieces[r: r + 8]) + '\n')
for r in range(0, 8 * 8, 8))
return outer_join(divider, rows)
用例:
>>> fen = "r2q1rk1/pp2ppbp/1np2np1/2Q3B1/3PP1b1/2N2N2/PP3PPP/3RKB1R"
>>> print ascii_draw_chess_position(fen)
+-+-+-+-+-+-+-+-+
|r| | |q| |r|k| |
+-+-+-+-+-+-+-+-+
|p|p| | |p|p|b|p|
+-+-+-+-+-+-+-+-+
| |n|p| | |n|p| |
+-+-+-+-+-+-+-+-+
| | |Q| | | |B| |
+-+-+-+-+-+-+-+-+
| | | |P|P| |b| |
+-+-+-+-+-+-+-+-+
| | |N| | |N| | |
+-+-+-+-+-+-+-+-+
|P|P| | | |P|P|P|
+-+-+-+-+-+-+-+-+
| | | |R|K|B| |R|
+-+-+-+-+-+-+-+-+
我已經嘗試做了一些修改,以在Ruby中的每一行轉換......我不知道,如果是糟糕的開局:秒,但我無論如何發佈:
def expand_blanks(fen)
def expand(match)
return ' ' * int(match.group(0))
end
# bugged:
re.compile(r'\d').sub(expand, fen)
end
def outer_join(sep, ss)
sep + sep.join(ss) + sep
end
def ascii_draw_chess_position(fen)
pieces = expand_blanks(fen).replace('/', '')
puts pieces.class
divider = "+-+-+-+-+-+-+-+-+\n"
# bugged lines:
rows = ((outer_join('|', pieces[r, r + 8]) + '\n')
for r in range(0, 8 * 8, 8))
return outer_join(divider, rows)
end
end
fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR"
puts ascii_draw_chess_position(fen)
如果你看到一些線,我可以解決,我會對我很酷。謝謝你們。
非常感謝Mikej和Grifaton。現在我得到了我所要做的每件事。再次感謝! 此致敬禮。 – Denis 2010-01-24 23:57:08