Krishnan Shankar
Krishnan Shankar

Reputation: 942

Get Location of Piece in Python-Chess

I am currently building a chess game using Python-Chess, and I am trying to use the SVG module to generate SVG images of the board. One of the parameters for generating an svg is check (here), which is a "square to be marked indicating a check". However, from the docs, I couldn't find a way to figure out where the player's king is.

What I want to happen is, whenever board.is_check() I want it to generate the svg with check=, using the current location of the current player's king. How do I figure this out? Do I have to iterate through every square and check what piece is on there until I find the correct king? Or is there a function for this that I didn't see? Any help is appreciated, Thanks in advance!

Upvotes: 1

Views: 2024

Answers (1)

Dalton Pearson
Dalton Pearson

Reputation: 570

There is a function for getting the position of the king which is documented here: https://python-chess.readthedocs.io/en/latest/core.html#chess.BaseBoard.king

Here is some example code:

import chess
board = chess.Board()
# get the current square index of the white king
king_square_index = board.king(chess.WHITE)
# get the current square name of the white king
king_square_name = chess.square_name(king_square_index)
print(king_square_name) # e1
# Move white pawn to e4
board.push_san("e4")
# Move black pawn to e5
board.push_san("e5")
# Move white king to e2
board.push_san("Ke2")
# get the current square index of the white king
king_square_index = board.king(chess.WHITE)
# get the current square name of the white king
king_square_name = chess.square_name(king_square_index)
print(king_square_name) # e2

Upvotes: 4

Related Questions