niklasf / python-chess

A chess library for Python, with move generation and validation, PGN parsing and writing, Polyglot opening book reading, Gaviota tablebase probing, Syzygy tablebase probing, and UCI/XBoard engine communication
https://python-chess.readthedocs.io/en/latest/
GNU General Public License v3.0
2.42k stars 529 forks source link

Question: How else to change the state of the board? #618

Closed PedanticHacker closed 4 years ago

PedanticHacker commented 4 years ago

I know 2 ways of changing the state of the board: one is push() and the other is set_fen(). How else is one able to change the state of the board?

niklasf commented 4 years ago

There are many ways. What are you trying to achieve?

PedanticHacker commented 4 years ago

I am trying to display a particular chessboard position when a move item (QTableWidgetItem) is clicked in the moves widget (QTableWidget).

Just like in lichess.org: when you click on a move item in the moves widget, the chessboard redraws itself to display the position that existed for when that clicked move was played. I wanna do the same.

Any alternatives to push() and set_fen()?

niklasf commented 4 years ago

Here is how to do the operations with python-chess datastructures:

import chess.pgn

# How to append moves to a game
game = chess.pgn.Game()
node = game
node = node.add_variation(chess.Move.from_uci("e2e4"))
node = node.add_variation(chess.Move.from_uci("e7e5"))
node = node.add_variation(chess.Move.from_uci("g1f3"))
node = node.add_variation(chess.Move.from_uci("b8c6"))

# How to get the board of the nth node
n = 3
node = game
for _ in range(n):
    node = node.variations[0]
print(node.board())

You can also easily use your own list of moves.

PedanticHacker commented 4 years ago

What about using the from_board() class attribute instead? So like chess.pgn.Game.from_board(board)?

PedanticHacker commented 4 years ago

Why are you doing that node = game thing? Is this really necessary?