Шахматная библиотека на Python

Опубликовано: 24 Марта, 2022

Шахматный модуль - это чистая шахматная библиотека Python с генерацией ходов, проверкой ходов и поддержкой общих форматов. С ним можно играть в шахматы. Это поможет нам переместить короля, ферзя, пешку, слонов и коней. Нам нужно знать основы шахмат, чтобы играть с ними в шахматы. Этот модуль выполняет все задачи на Python, которые возможны в реальной игре.

Установка:

 пип установить шахматы

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

Выход:

<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 particlular piece at 
# e place to 4th postion 
   
# Display chess board  
print(board)

Output:

Change after the move .

To check for a checkmate:

Python3

# Verifying check mate
board.is_checkmate()

Выход:

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

Чтобы проверить, не патовая ли ситуация:

Пат - это ситуация в шахматной игре, когда игрок, чья очередь делать ход, не находится под шахом, но у него нет разрешенного хода. Правила шахмат предусматривают, что при возникновении патовой ситуации игра заканчивается ничьей.

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()

Выход:

 Он вернет логическое значение ИСТИНА или ЛОЖЬ.

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()

Выход:

 Оба они вернут логическое значение ИСТИНА или ЛОЖЬ.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.