Open In App

Chess Library in Python

Last Updated : 05 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The chess module is a pure Python chess library with move generation, move validation and support for common formats. We can play chess with it. It will help us to move the king queen, pawn, bishops and knights. We need to know the basics of chess to play chess with it. This module does every task in python that is possible in the real game.

Installation:

pip install chess

We just have to import the chess library and with it, we can play chess. When we will import the chess library we have to call the function named board so that we can see the status of the chess board. 

Here is the code for making calling the function board of chess library.

Python3




# import required module
import chess
 
# create board object
board=chess.Board()
 
# display chess board
print(board)


 
 

The photo on left is gui representation and picture on left is the ASCII Board

 We can find out what are the legal moves using the below code:

 

Python3




# legal moves
board.legal_moves


Output:

<LegalMoveGenerator at 0x3586100 (Nh3, Nf3, Nc3, Na3, h3, g3, f3, e3, d3, c3, b3, a3, h4, g4, f4, e4, d4, c4, b4, a4)>

If we have to move any piece, we can check with above command that which moves we can do.

Moving players:

Python3




# moving players
board.push_san("e4")
# It means moving the particular piece at
# e place to 4th position
  
# Display chess board 
print(board)


Output:

Change after the move .

To check for a checkmate:

Python3




# Verifying check mate
board.is_checkmate()


Output:

If There is checkmate then it will be TRUE else FALSE.It will be a boolean value.

To check If it is a stalemate:

Stalemate is a situation in the game of chess where the player whose turn it is to move is not in check but has no legal move. The rules of chess provide that when stalemate occurs, the game ends as a draw.

Python3




# Verifying stalemate
board.is_stalemate()


Output:

It will return a boolean value a TRUE or FALSE.

We can detect check also with help of above function:

Python3




# code
board.is_check()


Output:

It will return a boolean value a TRUE or FALSE.

With the new rules from July 2014, a game ends as a draw (even without a claim) once a fivefold repetition occurs or if there are 75 moves without a pawn push or capture. Other ways of ending a game take precedence. So there methods for checking these things also=

Python3




# code
board.is_fivefold_repetition()
board.is_seventyfive_moves()


Output:

Both of it will return a boolean value a TRUE or FALSE.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads