0

应该如何在 python-chess 上使用合法移动功能?

通过运行此代码并输入 e2e4。事实证明,此举是无效的。

import asyncio
import chess
import chess.engine

engine = chess.engine.SimpleEngine.popen_uci("stockfish.exe")

board = chess.Board()
while not board.is_game_over():
    
    legal_count = board.legal_moves.count()
    move_list = list(board.legal_moves) # Find legal moves
    
    print (move_list)
    print(board)
   
    mover = input("Indica tu movimiento: ")

    if mover not in move_list:
        print ("vuelve a introducir una movida válida")
        mover = input("otra movida: ")
    board.push_xboard(mover)
    result = engine.play(board, chess.engine.Limit(time=0.1))
    board.push(result.move)
    
    print(board)
engine.quit()

当我浏览列表时,我发现......具有这种价值:

[Move.from_uci('g1h3'), Move.from_uci('g1f3')

那么,是不是来自legal_moves,我从用户那里得到了合法的动作??

还是假设我必须以这种方式输入值?我不明白。

我想要的是用户通过控制台“e2e4”输入一个值并验证是否可以移动。(顺便说一句,我需要那种坐标“e2e4”,而不是“e4”或“Nf3”)。

谢谢。

4

1 回答 1

0

将用户输入转换为 python-chess 移动格式。

mover = input("Indica tu movimiento: ")
mover = chess.Move.from_uci(mover)  # add this line

然后使用:

board.push(mover)

代替:

board.push_xboard(mover)  # incorrect

由于stockfish 引擎不是xboard 引擎,它是uci 引擎。

输出:

python so_chess.py
[Move.from_uci('g1h3'), Move.from_uci('g1f3'), Move.from_uci('b1c3'), Move.from_uci('b1a3'), Move.from_uci('h2h3'), Move.from_uci('g2g3'), Move.from_uci('f2f3'), Move.from_uci('e2e3'), Move.from_uci('d2d3'), Move.from_uci('c2c3'), Move.from_uci('b2b3'), Move.from_uci('a2a3'), Move.from_uci('h2h4'), Move.from_uci('g2g4'), Move.from_uci('f2f4'), Move.from_uci('e2e4'), Move.from_uci('d2d4'), Move.from_uci('c2c4'), Move.from_uci('b2b4'), Move.from_uci('a2a4')]
r n b q k b n r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R N B Q K B N R
Indica tu movimiento: e2e4
r n b q k b n r
p p . p p p p p
. . . . . . . .
. . p . . . . .
. . . . P . . .
. . . . . . . .
P P P P . P P P
R N B Q K B N R
[Move.from_uci('g1h3'), Move.from_uci('g1f3'), Move.from_uci('g1e2'), Move.from_uci('f1a6'), Move.from_uci('f1b5'), Move.from_uci('f1c4'), Move.from_uci('f1d3'), Move.from_uci('f1e2'), Move.from_uci('e1e2'), Move.from_uci('d1h5'), Move.from_uci('d1g4'), Move.from_uci('d1f3'), Move.from_uci('d1e2'), Move.from_uci('b1c3'), Move.from_uci('b1a3'), Move.from_uci('e4e5'), Move.from_uci('h2h3'), Move.from_uci('g2g3'), Move.from_uci('f2f3'), Move.from_uci('d2d3'), Move.from_uci('c2c3'), Move.from_uci('b2b3'), Move.from_uci('a2a3'), Move.from_uci('h2h4'), Move.from_uci('g2g4'), Move.from_uci('f2f4'), Move.from_uci('d2d4'), Move.from_uci('c2c4'), Move.from_uci('b2b4'), Move.from_uci('a2a4')]
r n b q k b n r
p p . p p p p p
. . . . . . . .
. . p . . . . .
. . . . P . . .
. . . . . . . .
P P P P . P P P
R N B Q K B N R
Indica tu movimiento: g1f3
r n b q k b n r
p p . . p p p p
. . . p . . . .
. . p . . . . .
. . . . P . . .
. . . . . N . .
P P P P . P P P
R N B Q K B . R
于 2021-10-26T21:58:51.580 回答