我有一个 FEN 位置列表,我希望能够将其转换为 PGN 文件以进行保存。我需要 python 中的这段代码。
PGN文件可以存成字符串,也可以直接存,我不管,只要能用就行
这是我的代码:
import stockfish
import time
def detectffrep(lst):
"""
thank you ChatGPT for writing this, big much very thanks
detects fivefold repetitions in a list
"""
count = 1
for i in range(len(lst) - 1):
if lst[i] == lst[i+1]:
count += 1
if count > 5:
return True
else:
count = 1
return False
whereFish = input("wheres my fish? ")
x = stockfish.Stockfish(whereFish)
curplayer = True # white
repre = {
True: "White",
False: "Black"
}
game = []
while True:
best = x.get_top_moves()
# print(best[0], flush=False)
x.make_moves_from_current_position([best[0]["Move"]])
curplayer = not curplayer
print("%s's move" % (repre[curplayer]), flush=False)
print(x.get_board_visual())
game += [x.get_fen_position()]
if best[0]["Mate"] or detectffrep(game):
break
if not detectffrep(game):
print("Mate")
else:
print("Repeated game")
with open("game_%s.fen" % str(int(time.time())), "a") as file:
for i in game:
file.write(i + "\n")
在最后几行中,您可以看到我尝试将 FEN 位置保存为一行分隔文件,但没有任何国际象棋引擎可以真正打开它。
我似乎无法弄清楚这一点,你们能帮帮我吗?
这里是读取包含位置的 fen 文件并将其保存到 pgn 文件的代码。
def gen_pgn(fn, outpgn):
with open(outpgn, 'a') as pgn:
with open(fn, 'r') as f:
for lines in f:
fen = lines.rstrip()
pgn.write(f'[Event "Just a FEN setup"]\n')
pgn.write(f'[Result "*"]\n')
pgn.write(f'[FEN "{fen}"]\n\n')
pgn.write('*\n\n')
if __name__ == '__main__':
fn = 'myfens.fen'
outpgn = 'myfens.pgn'
gen_pgn(fn, outpgn)
[Event "Just a FEN setup"]
[Result "*"]
[FEN "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6"]
*
[Event "Just a FEN setup"]
[Result "*"]
[FEN "rnbqkbnr/ppp1pppp/8/8/2Pp4/5N2/PP1PPPPP/RNBQKB1R w KQkq - 0 3"]
*