简体   繁体   中英

How do slice and print the mainline with the python-chess library?

There's a way to slice the mainline like we slice lists on Python? For example:

  • mainline[start:stop] # moves start through stop-1
  • mainline[start:] # moves start through the rest of the mainline
  • mainline[:stop] # moves from the beginning through stop-1

or

  • mainline[start:stop:step] # start through not past stop, by step.

The idea is, having the main_sicilian object:

1. e4 c5 2. b4 cxb4 3. d4 d5 4. e5 Nc6 5. a3 Qb6 6. Ne2 Bf5 7. axb4 Nxb4 8. Na3 Rc8 9. Nf4 Bxc2 10. Qg4 e6 *

I would like to have:

main_sicilian[1:5] = 1. e4 c5 2. b4 cxb4 3. d4 d5 4. e5 Nc6 5. a3 Qb6

Also, by defining where it would finish. For example, until white's 3rd move:

1. e4 c5 2. b4 cxb4 3. d4

I tried the documentation but I find it hard to use for a Python beginner.

Try this.

code

import io
import chess
import chess.pgn


pgn = io.StringIO("1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 *")
game = chess.pgn.read_game(pgn)

var = []
for node in game.mainline():
    var.append(node.move)

# Slice up to 3 plies.
sliced_var = var[0:3]

# Convert to SAN format.
b = chess.Board()
san_sliced_var = b.variation_san(sliced_var)
print(san_sliced_var)

Output

1. e4 c5 2. Nf3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM