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

Problem with node.remove_variation(move). Not able to remove a variation #975

Closed AlessioPoggi99 closed 1 year ago

AlessioPoggi99 commented 1 year ago

Probably it's my fault... I cannot understand how to remove variations...

At the beginning of my code I set node = game, then I have game loop and every played move is added using:

  # Inizializations
  engine = chess.engine.SimpleEngine.popen_uci(r'/usr/local/bin/stockfish')
  board = chess.Board()
  game = chess.pgn.Game()
  node = game

  # Played move and added variation example
  result = engine.play(board, chess.engine.Limit(time=.2))
  node = node.add_variation(result.move)
  board.push(result.move)

Now let's suppose I want to do some step back, so that I want to pop some moves from board and also from variations list...

  move = board.pop()
  node = node.remove_variation(move)

And that's raising an error. I tried in other ways but can't understand. That's the error

  File ".../play_vs_computer.py", line 97, in my_function
      node = node.remove_variation(move)
    File ".../venv/lib/python3.9/site-packages/chess/pgn.py", line 350, in remove_variation
      self.variations.remove(self.variation(move))
    File ".../venv/lib/python3.9/site-packages/chess/pgn.py", line 322, in variation
      return self[move]
    File ".../venv/lib/python3.9/site-packages/chess/pgn.py", line 308, in __getitem__
      raise KeyError(move)
  KeyError: Move.from_uci('h7h5')
niklasf commented 1 year ago

It's not clear from the context, but I would guess that node is not the node that you want to remove the variation from.