我正在使用 Python 国际象棋库编写一个小型国际象棋 GUI。昨天,我运行了我的代码很多次,没有任何问题。然后我安装了一些其他的Python库。今天我注意到一个奇怪的错误:board.legel_moves 生成错误的动作。我尝试重新安装Python 3.13.1和最新的Python国际象棋库,错误仍然存在。
代码很短:
import chess
board = chess.Board()
starting_position=board.fen()
for move in board.legal_moves:
print(starting_position)
board.set_fen(starting_position)
print(move)
board.push(move)
print(f' board pushed move {board.fen()}')
print()
错误的结果从第五步h7h6开始直到结束。应该是h2h3。我只展示前六个例子。
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
g1h3
board pushed move rnbqkbnr/pppppppp/8/8/8/7N/PPPPPPPP/RNBQKB1R b KQkq - 1 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
g1f3
board pushed move rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R b KQkq - 1 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
b1c3
board pushed move rnbqkbnr/pppppppp/8/8/8/2N5/PPPPPPPP/R1BQKBNR b KQkq - 1 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
b1a3
board pushed move rnbqkbnr/pppppppp/8/8/8/N7/PPPPPPPP/R1BQKBNR b KQkq - 1 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
h7h6
board pushed move rnbqkbnr/ppppppp1/7P/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
g7g6
board pushed move rnbqkbnr/pppppp1p/6P1/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1
如果我注释掉板推移动部分board.push(move),一切正常。
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
g1h3
board pushed move rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
g1f3
board pushed move rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
b1c3
board pushed move rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
b1a3
board pushed move rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
h2h3
board pushed move rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
g2g3
board pushed move rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
如果我注释掉 board.set_fen(starting_position) 并在最后添加 board.pop(),没有错误。
有人可以给我一些建议吗? 谢谢
不知道为什么,推了会影响板子。复制一份板子,就没有问题了。
import chess
import copy
board = chess.Board()
starting_position=board.fen()
new_board= copy.copy(board)
for move in board.legal_moves:
print(starting_position)
board=copy.copy(new_board)
board.set_fen(starting_position)
print(move)
board.push(move)
print(f' board pushed move {board.fen()}')
print()