-1

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.

mykahveli
  • 113
  • 4
  • Please provide a [mre]. What have you tried? What did that give you? _"There's a way to slice the mainline..."_: are you asking us or telling us? – Pranav Hosangadi Sep 20 '21 at 15:32
  • https://python-chess.readthedocs.io/en/latest/pgn.html#chess.pgn.GameNode.mainline `mainline()` _Returns an iterable over the mainline starting after this node._ Do you know what an iterable is, and how to convert it to a list? Once you do this, you can slice the list in the usual way. – Pranav Hosangadi Sep 20 '21 at 15:35

1 Answers1

1

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

ferdy
  • 4,396
  • 2
  • 4
  • 16