cshogi package
Module contents
- class cshogi.Board
Bases:
objectBoard class to represent a Shogi board.
- Parameters:
sfen (str, optional) – A string representing the board in SFEN format, optional.
board (Board, optional) – A string representing the board in SFEN format, optional.
- Example:
# Initialize board board = Board() # Initialize board with sfen board = Board(sfen="lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1") # Initialize board with board board2 = Board(board=board)
- book_key()
Gets the key for the opening book.
- Returns:
The key for the current board state in the opening book.
- Return type:
long long
- book_key_after(key, move)
Gets the key for the opening book after a specific move.
- Parameters:
key (long long) – The current key.
move (int) – The move to be applied.
- Returns:
The key for the resulting board state in the opening book.
- Return type:
long long
- check_moves
Generates legal checking moves from the current board position.
- Returns:
An iterator that yields checking moves.
- Return type:
- copy()
Creates a copy of the current board.
- Returns:
A new Board object with the same state.
- csa_pos()
Returns the current board position in Computer Shogi Association (CSA) format.
- Returns:
A string representing the board in CSA format.
- Return type:
str
- drop_move(to_square, drop_piece_type)
Make a drop move on the board.
- Parameters:
to_square (int) – The destination square index.
drop_piece_type (int) – The type of piece to drop.
- Returns:
An integer representing the move.
- Return type:
int
- history
Gets the history of moves in the game.
- Returns:
The list of moves.
- Return type:
list
- is_check()
Determines if the king is in check.
- Returns:
True if the king is in check, False otherwise.
- Return type:
bool
- is_draw(ply=None)
Determines whether the current game state represents a draw or another special condition.
- Parameters:
ply (int or None) – Optional parameter to check up to a specific ply. Defaults to maximum int value.
- Returns:
A status that could be one of the following:
REPETITION_DRAW: In case of a repeated position.
REPETITION_WIN: In case of a win due to consecutive checks.
REPETITION_LOSE: In case of a loss due to consecutive checks.
REPETITION_SUPERIOR: In case of a superior position.
REPETITION_INFERIOR: In case of an inferior position.
NOT_REPETITION: If none of the above conditions apply.
- Return type:
int
- is_game_over()
Check if the game is over.
- Returns:
True if the game is over, otherwise False.
- is_legal(move)
Checks if a move is legal.
- Parameters:
move (int) – integer representing the move.
- Returns:
True if the move is legal, False otherwise.
- Return type:
bool
- is_mate(ply)
Checks if a mate condition is met in a given number of ply.
- Parameters:
ply (int) – even integer representing the number of ply.
- Returns:
True if mate, False otherwise.
- Return type:
bool
- is_nyugyoku(rule=1)
Check for a win according to a Nyugyoku declaration rule.
The default is the 27-point rule for backward compatibility. Under the 24-point rule, a draw at 24 to 30 points returns False.
- Parameters:
rule – LAW_24 or LAW_27.
- Returns:
True only when the declaration result is a win.
- Return type:
bool
- is_ok()
Check if the board is in a valid state.
- Returns:
True if the board state is valid, False otherwise.
- Return type:
bool
- is_pseudo_legal(move)
Checks if a move is pseudo-legal.
- Parameters:
move (int) – integer representing the move.
- Returns:
True if the move is pseudo-legal, False otherwise.
- Return type:
bool
- king_square(c)
Returns the square index of the king for a given color.
- Parameters:
c (int) – The color of the king, either BLACK or WHITE.
- Returns:
The square index of the king for the specified color.
- Return type:
int
- legal_moves
Generates a list of legal moves from the current board position.
- Returns:
An iterator that yields legal moves.
- Return type:
- mate_move(ply)
Finds a mating move in a given number of ply.
- Parameters:
ply (int) – odd integer, should be greater or equal to 3, representing the number of ply.
- Returns:
integer representing the mating move.
- Return type:
int
- mate_move_in_1ply()
Finds a mating move in one ply.
- Returns:
integer representing the mating move.
- Return type:
int
- move(from_square, to_square, promotion)
Make a move on the board.
- Parameters:
from_square (int) – The starting square index.
to_square (int) – The destination square index.
promotion (bool) – Whether the move involves a promotion.
- Returns:
An integer representing the move.
- Return type:
int
- move_from_csa(csa)
Make a move on the board using a CSA-formatted string.
- Parameters:
csa (str) – The move in CSA format.
- Returns:
An integer representing the move.
- Return type:
int
- move_from_move16(move16)
Make a move on the board using a 16-bit move code.
- Parameters:
move16 (unsigned short) – The move in 16-bit format.
- Returns:
An integer representing the move.
- Return type:
int
- move_from_psv(move16)
Make a move on the board using a PSV-formatted move code.
- Parameters:
move16 (unsigned short) – The move in PSV format.
- Returns:
An integer representing the move.
- Return type:
int
- move_from_usi(usi)
Make a move on the board using a USI-formatted string.
- Parameters:
usi (str) – The move in USI format.
- Returns:
An integer representing the move.
- Return type:
int
- move_is_draw(move, ply=None)
Check if a given move results in a draw.
- Parameters:
move (int) – The move to check.
ply (int or None) – Optional parameter to check up to a specific ply. Defaults to maximum int value.
- Returns:
A status that could be one of the following:
REPETITION_DRAW: In case of a repeated position.
REPETITION_WIN: In case of a win due to consecutive checks.
REPETITION_LOSE: In case of a loss due to consecutive checks.
REPETITION_SUPERIOR: In case of a superior position.
REPETITION_INFERIOR: In case of an inferior position.
NOT_REPETITION: If none of the above conditions apply.
- Return type:
int
- move_number
Gets the current move number.
- Returns:
Current move number.
- nyugyoku_result(rule=0)
Return the result of a Nyugyoku declaration judgment.
Under the 24-point rule, 31 or more points is a win and 24 to 30 points is a draw. Under the 27-point rule, the winning threshold is 28 points for Black and 27 points for White.
- Parameters:
rule – LAW_24 or LAW_27.
- Returns:
One of NYUGYOKU_NONE, NYUGYOKU_WIN, or NYUGYOKU_DRAW.
- Return type:
int
- peek()
Peek at the last move on the board.
- Returns:
The last move as an integer.
- Return type:
int
- piece(sq)
Returns the piece at a given square.
- Parameters:
sq (int) – The square index.
- Returns:
The piece at the given square.
- Return type:
int
- piece_planes(features)
Generate piece planes representing the current state of the board. The result is stored in the given ndarray.
- Parameters:
features (np.ndarray) – An ndarray with dimensions (FEATURES_NUM, 9, 9) and dtype np.float32, where FEATURES_NUM is defined as len(PIECE_TYPES) * 2 + sum(MAX_PIECES_IN_HAND) * 2.
- piece_planes_rotate(features)
Generate 180-degree rotated piece planes representing the current state of the board. The result is stored in the given ndarray.
- Parameters:
features (np.ndarray) – An ndarray with dimensions (FEATURES_NUM, 9, 9) and dtype np.float32, where FEATURES_NUM is defined as len(PIECE_TYPES) * 2 + sum(MAX_PIECES_IN_HAND) * 2.
- piece_type(sq)
Returns the type of piece at a given square.
- Parameters:
sq (int) – The square index.
- Returns:
The type of piece at the given square.
- Return type:
int
- pieces
Gets the pieces on the board.
- Returns:
An array representing the pieces on the board.
- Return type:
list
- pieces_in_hand
Gets the pieces in hand for both BLACK and WHITE players.
- Returns:
A tuple containing the number of pieces in hand for both BLACK and WHITE players.
- Return type:
tuple
- pop()
Pop the last move from the board.
- Returns:
The move as an integer.
- Return type:
int
- pop_pass()
Pop the last pass move from the board.
- pseudo_legal_move_is_legal(move)
Checks if a pseudo-legal move is legal.
- Parameters:
move (int) – integer representing the move.
- Returns:
True if the move is legal, False otherwise.
- Return type:
bool
- pseudo_legal_moves
Generates a list of pseudo-legal moves from the current board position.
- Returns:
An iterator that yields pseudo-legal moves.
- Return type:
- push(move)
Push a move to the board.
The move is represented as an integer, where each bit has the following meaning:
xxxxxxxx xxxxxxxx xxxxxxxx x1111111: Destination square.
xxxxxxxx xxxxxxxx xx111111 1xxxxxxx: Source square, or PieceType + SquareNum - 1 when dropping a piece.
xxxxxxxx xxxxxxxx x1xxxxxx xxxxxxxx: Promotion flag (1 if promoted).
xxxxxxxx xxxx1111 xxxxxxxx xxxxxxxx: Moving piece’s PieceType, not used when dropping a piece.
xxxxxxxx 1111xxxx xxxxxxxx xxxxxxxx: Captured piece’s PieceType.
- Parameters:
move (int) – The move to be applied to the board, encoded as an integer.
- push_csa(csa)
Push a move to the board in Computer Shogi Association (CSA) format.
- Parameters:
csa (str) – The move in CSA format.
- Returns:
The move as an integer, or 0 if the move is invalid.
- Return type:
int
- push_move16(move16)
Push a 16-bit move to the board.
The move16 is the lower 16 bits of the ingeter move format.
- Parameters:
move16 (unsigned short) – The move in 16-bit format.
- Returns:
The move as an integer.
- Return type:
int
- push_pass()
Push a pass move to the board.
- Returns:
The result of the pass move.
- Return type:
int
- push_psv(move16)
Push a move to the board in PSV format, which is used in YaneuraOu.
- Parameters:
move16 (unsigned short) – The move in PSV format.
- Returns:
The move as an integer.
- Return type:
int
- push_usi(usi)
Push a move to the board in Universal Shogi Interface (USI) format.
- Parameters:
usi (str) – The move in USI format.
- Returns:
The move as an integer, or 0 if the move is invalid.
- Return type:
int
- reset()
Resets the board to its initial state.
- set_hcp(hcp)
Sets the board using HuffmanCodedPos (hcp) format, a compression format used in Apery.
- Parameters:
hcp (np.ndarray) – The HuffmanCodedPos data to set the board.
- Raises:
RuntimeError – If the hcp is incorrect.
- Example:
hcp = np.fromfile("hcpfile", HuffmanCodedPos) board.set_hcp(np.asarray(hcp[0]))
- set_pieces(pieces, pieces_in_hand)
Sets the pieces on the board and pieces in hand.
- Parameters:
pieces (list) – A list of pieces on the board.
pieces_in_hand (tuple) – A tuple representing pieces in hand.
- Example:
# Edit the pieces on the board and the pieces in hand board = Board() pieces_src = board.pieces pieces_in_hand_src = board.pieces_in_hand pieces_dst = pieces_src.copy() pieces_dst[G1] = NONE pieces_dst[F1] = BPAWN pieces_dst[C1] = NONE pieces_in_hand_dst = (pieces_in_hand_src[0].copy(), pieces_in_hand_src[1].copy()) pieces_in_hand_dst[BLACK][HPAWN] = 1 board_dst = board.copy() board_dst.set_pieces(pieces_dst, pieces_in_hand_dst)
- set_position(position)
Sets the position on the board using a given string.
- Parameters:
position (str) – String representing the position to be set.
- Raises:
RuntimeError – If the position string is incorrect.
- Example:
board.set_position("startpos moves 2g2f") board.set_position("sfen lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1")
- set_psfen(psfen)
Sets the board using PackedSfen (psfen) format, a compression format used in YaneuraOu.
- Parameters:
psfen (np.ndarray) – The PackedSfen data to set the board.
- Raises:
RuntimeError – If the psfen is incorrect.
- Example:
psfen = np.fromfile("psfenfile", PackedSfen) board.set_psfen(np.asarray(psfen[0]))
- set_sfen(sfen)
Sets the board state using a given SFEN string.
- Parameters:
sfen (str) – String representing the board state in SFEN.
- Raises:
RuntimeError – If the sfen string is incorrect.
- Example:
board.set_sfen("lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1")
- sfen()
Returns the current board position in Shogi Forsyth-Edwards Notation (SFEN) format.
- Returns:
A string representing the board in SFEN format.
- Return type:
str
- to_bod()
Convert the current state of the board to a Board Diagram (BOD) format.
- Returns:
A string representing the board in BOD format.
- Return type:
str
- to_hcp(hcp)
Converts the current board to HuffmanCodedPos (hcp) format.
- Parameters:
hcp (np.ndarray) – An array to store the hcp data.
- to_psfen(psfen)
Converts the current board to PackedSfen (psfen) format.
- Parameters:
psfen (np.ndarray) – An array to store the psfen data.
- to_svg(lastmove=None, scale=1.0)
Generate an SVG representation of the current board state.
- Parameters:
lastmove (int) – The last move made on the board, if any (default is None).
scale (float) – The scaling factor for the SVG (default is 1.0).
- Returns:
An SVG representation of the current board state.
- Return type:
- turn
Gets the current turn.
- Returns:
The current turn, either BLACK (for the first player) or WHITE (for the second player).
- zobrist_hash()
Calculates the Zobrist hash key for the current board position.
- Returns:
64-bit integer representing the Zobrist hash key.
- Return type:
long long
- class cshogi.CheckMoveList
Bases:
objectAn iterator class to generate legal checking moves.
- class cshogi.DfPn
Bases:
objectClass to perform mate search using the df-pn algorithm.
- Parameters:
depth (int, optional) – Depth of the search.
nodes (int, optional) – Number of nodes in the search.
draw_ply (int, optional) – The number of plies to consider as a draw.
- MATE = 1
- NO_MATE = 2
- UNKNOWN = 0
- get_move(board)
Gets the mating move found by the search.
- Parameters:
board (Board) – Current board position.
- Returns:
The mating move.
- Return type:
int
- get_pv(board)
Gets the principal variation (PV) of the mating sequence found by the search.
- Parameters:
board (Board) – Current board position.
- Returns:
The PV of the mating sequence.
- Return type:
list of unsigned int
- result
Gets the result of the last search.
- search(board)
Perform a checkmate search on the given board.
- Parameters:
board (Board) – Board state.
- Returns:
True if checkmate is found, False otherwise.
- Return type:
bool
- search_andnode(board)
Perform a checkmate search at the AND node.
- Parameters:
board (Board) – Board state.
- Returns:
True if checkmate is found, False otherwise.
- Return type:
bool
- searched_node
Gets the number of nodes searched in the last search.
This is the same count that is compared with the node limit (
nodes): it is incremented each time the df-pn search descends into a child position. The root position and the positions examined by the fixed-depth checks (the mate-in-1 check at the root, the 3-ply check at new OR nodes and the 2-ply check at new AND nodes) are not counted. Therefore it can be 0 even whenresultisMATEorNO_MATE, for example when the root is mate in 1 or has no checking move.- Returns:
Number of nodes searched.
- Return type:
unsigned int
- set_draw_ply(draw_ply)
Sets the number of plies for a draw.
- Parameters:
draw_ply (int) – Number of plies for a draw.
- set_max_depth(max_depth)
Sets the maximum search depth.
- Parameters:
max_depth (int) – Maximum search depth.
- set_max_search_node(max_search_node)
Sets the maximum number of search nodes.
- Parameters:
max_search_node (int) – Maximum number of search nodes.
- stop(stop)
Stop the search.
- Parameters:
stop (bool) – Flag to stop the search.
- class cshogi.LegalMoveList
Bases:
objectAn iterator class to generate legal moves.
- class cshogi.PseudoLegalMoveList
Bases:
objectAn iterator class to generate pseudo-legal moves.
- class cshogi.SvgWrapper
Bases:
str
- cshogi.hand_piece_to_piece_type(hp)
Convert a hand piece identifier to its corresponding piece type.
- Parameters:
hp (int) – The hand piece identifier, typically an integer value representing a specific hand piece.
- Returns:
The corresponding piece type for the given hand piece identifier.
- Return type:
int
- cshogi.make_file(sq)
Determine the file (column) of a square.
- Parameters:
sq (int) – The square index.
- Returns:
The file (column) of the given square.
- Return type:
int
- cshogi.make_rank(sq)
Determine the rank (row) of a square.
- Parameters:
sq (int) – The square index.
- Returns:
The rank (row) of the given square.
- Return type:
int
- cshogi.move16(move)
Convert a move to a 16-bit representation.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
The 16-bit representation of the move.
- Return type:
int
- cshogi.move16_from_psv(move16)
Convert a 16-bit move representation from a move in PSV format.
- Parameters:
move16 (unsigned short) – A 16-bit move representation in PSV format.
- Returns:
The corresponding 16-bit move representation.
- Return type:
unsigned short
- cshogi.move16_to_psv(move16)
Convert a 16-bit move representation to a move in PSV format.
- Parameters:
move16 (unsigned short) – A 16-bit move representation.
- Returns:
The corresponding 16-bit move representation in PSV format.
- Return type:
unsigned short
- cshogi.move_cap(move)
Extract the captured piece of a move.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
The captured piece of the move.
- Return type:
int
- cshogi.move_drop_hand_piece(move)
Extract the hand piece of a drop move.
- Parameters:
move (int) – A drop move represented as an integer.
- Returns:
The hand piece of the move.
- Return type:
int
- cshogi.move_from(move)
Extract the source square of a move.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
The source square of the move.
- Return type:
int
- cshogi.move_from_piece_type(move)
Extract the piece type moved from a move.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
The piece type moved from the move.
- Return type:
int
- cshogi.move_is_drop(move)
Checks if a move is a drop move.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
True if the move is a drop move, False otherwise.
- Return type:
bool
- cshogi.move_is_promotion(move)
Checks if a move is a promotion move.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
True if the move is a promotion move, False otherwise.
- Return type:
bool
- cshogi.move_rotate(move)
Convert a move to a move rotated by 180 degrees.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
The move rotated by 180 degrees.
- Return type:
int
- cshogi.move_to(move)
Extract the destination square of a move.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
The destination square of the move.
- Return type:
int
- cshogi.move_to_csa(move)
Convert a move to the Computer Shogi Association (CSA) format.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
The CSA representation of the move.
- Return type:
str
- cshogi.move_to_usi(move)
Convert a move to the Universal Shogi Interface (USI) format.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
The USI representation of the move.
- Return type:
str
- cshogi.opponent(color)
Gets the opponent’s color.
- Parameters:
color (int) – The player’s color, either BLACK or WHITE.
- Returns:
The opponent’s color, either BLACK or WHITE.
- Return type:
int
- cshogi.piece_to_piece_type(p)
Convert a piece identifier to its corresponding piece type.
- Parameters:
p (int) – The piece identifier, typically an integer value representing a specific piece.
- Returns:
The corresponding piece type for the given piece identifier.
- Return type:
int
- cshogi.rotate_sfen(sfen)
Rotates the board represented by the SFEN string by 180 degrees.
- Parameters:
sfen (str) – The SFEN string representing the board position.
- Returns:
A new SFEN string representing the rotated board position.
- Return type:
str
- cshogi.to_csa(move)
Convert a move to the Computer Shogi Association (CSA) format.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
The CSA representation of the move.
- Return type:
bytes
- cshogi.to_usi(move)
Convert a move to the Universal Shogi Interface (USI) format.
- Parameters:
move (int) – A move represented as an integer.
- Returns:
The USI representation of the move.
- Return type:
bytes
Submodules
cshogi.osl module
- class cshogi.osl.DfPn(depth=1600, nodes=4294967295, draw_ply=2147483646)
Class to perform mate search using the OSL-based df-pn algorithm.
Limitations:
Reaching the move limit (
depthordraw_ply) on one branch can end the current search iteration before other branches are examined. That iteration is treated asUNKNOWN, andsearch()may retry with a larger per-iteration node limit, up tonodes. Thereforeresultcan beUNKNOWNeven when a checkmate withindraw_plyexists, especially when the mate ends at or neardraw_ply. A checkmate that exceedsdraw_plyis never returned asMATE.depthlimits the depth of the search tree with a margin of two plies, sosearch()visits no nodes whendepthis 1 or 2. At those depths,search_andnode()can still examine the root and returnMATEif there is no legal reply to the check.
Use
cshogi.DfPnwhen exact results neardraw_plyare needed.- Parameters:
depth (int) – Depth of the search.
nodes (int) – Number of nodes in the search.
draw_ply (int) – The number of plies to consider as a draw.
- search(board)
Perform a checkmate search on the given board.
- Parameters:
board (Board) – Board state.
- Returns:
True if checkmate is found, False otherwise.
- Return type:
bool
- search_andnode(board)
Perform a checkmate search at the AND node.
- Parameters:
board (Board) – Board state.
- Returns:
True if checkmate is found, False otherwise.
- Return type:
bool
- stop(stop)
Stop the search.
- Parameters:
stop (bool) – Flag to stop the search.
- get_move(board)
Gets the mating move found by the search.
- Parameters:
board (Board) – Current board position.
- Returns:
The mating move.
- Return type:
int
- get_pv(board)
Gets the principal variation (PV) of the mating sequence found by the search.
PV reconstruction can find a mating line even when
resultisUNKNOWN.- Parameters:
board (Board) – Current board position.
- Returns:
The PV of the mating sequence.
- Return type:
list of unsigned int
- set_draw_ply(draw_ply)
Sets the number of plies for a draw.
- Parameters:
draw_ply (int) – Number of plies for a draw.
- set_max_depth(max_depth)
Sets the maximum search depth.
- Parameters:
max_depth (int) – Maximum search depth.
- set_max_search_node(max_search_node)
Sets the maximum number of search nodes.
- Parameters:
max_search_node (int) – Maximum number of search nodes.
- property searched_node
Gets the number of nodes searched in the last search.
It is incremented each time an attacking or defending position is visited, including the root, and each time a fixed-depth check is performed. Positions where the search stops before being counted, because the depth limit is reached or a loop is detected, are not included, so it can be 0 when the depth limit is small.
search()repeats the search while increasing the node limit (iterative deepening), and this is the total over all iterations. Because the node limit (nodes) applies to each iteration and is checked after children are expanded, the total can exceed it.- Returns:
Number of nodes searched.
- Return type:
int
- property result
Gets the result of the last search.
- UNKNOWN = 0
The search has not determined the result.
- MATE = 1
A checkmate was proven.
- NO_MATE = 2
It was proven that there is no checkmate.
cshogi.CSA module
- class cshogi.CSA.Exporter(path=None, append=False, encoding=None, *, stream=None)[source]
Bases:
objectA class to handle the exporting of a game to CSA format.
- Parameters:
path (str | None) – The file path to export to, defaults to None.
append (bool) – Whether to append to the file, defaults to False.
encoding (str | None) – The encoding of the file, defaults to None.
- endgame(endgame, time=None)[source]
Write the endgame result to the file.
- Parameters:
endgame (str) – The result of the endgame.
time (int | None) – The time taken for the endgame, defaults to None.
- info(init_board=None, names=None, var_info=None, comment=None, version=None)[source]
Write game information to the file.
- Parameters:
init_board (str | Board | None) – The initial board state, defaults to None.
names (List[str] | None) – The names of the players, defaults to None.
var_info (Dict | None) – Additional variable information, defaults to None.
comment (str | None) – Comments about the game, defaults to None.
version (str | None) – Version information, defaults to None.
- move(move, time=None, comment=None, sep='\n')[source]
Write a move to the file.
- Parameters:
move (int) – The move to write.
time (int | None) – The time taken for the move, defaults to None.
comment (str | None) – A comment about the move, defaults to None.
sep (str) – Separator character, defaults to newline.
- class cshogi.CSA.Parser
Bases:
objectA class to parse Shogi game records in the CSA standard file format.
- comment
Gets the general comment about the game.
- Returns:
The general comment about the game.
- Return type:
str
- comments
Gets the list of comments for each move of the game.
- Returns:
The list of comments for each move of the game.
- Return type:
list
- endgame
Gets the endgame result of the game.
- Returns:
The endgame result of the game.
- Return type:
str
- moves
Gets the list of moves in the game.
- Returns:
The list of moves in the game.
- Return type:
list
- names
Gets the names of the players.
- Returns:
The names of the players.
- Return type:
list
- parse_csa_file(path)
Parse a CSA standard Shogi game record from a file path.
- Parameters:
path (str) – The file path containing the game record.
- parse_csa_str(csa_str)
Parse a CSA standard Shogi game record from a string.
- Parameters:
csa_str (str) – A string containing the game record.
- static parse_file(file, encoding=None)
Parse CSA standard Shogi game records from a file.
- Parameters:
file (str or file object) – The file path or file object containing the game records.
encoding (str, optional) – The character encoding of the file, defaults to None.
- Returns:
A list of Parser objects representing the parsed game records.
- Return type:
list
- static parse_str(csa_str)
Parse CSA standard Shogi game records from a string.
- Parameters:
csa_str (str) – A string containing one or more Shogi game records.
- Returns:
A list of Parser objects representing the parsed game records.
- Return type:
list
- ratings
Gets the ratings of the players.
- Returns:
The ratings of the players.
- Return type:
list
- scores
Gets the list of scores for each move of the game.
- Returns:
The list of scores for each move of the game.
- Return type:
list
- sfen
Gets the SFEN representation of the initial position.
- Returns:
The SFEN representation of the initial position.
- Return type:
str
- times
Gets the list of times for each move in the game.
- Returns:
The list of times for each move in the game.
- Return type:
list
- var_info
Gets a dictionary containing various information about the game.
- Returns:
A dictionary containing various information about the game.
- Return type:
dict
- version
Gets the version of the CSA standard game record file format.
- Returns:
The version of the CSA standard game record file format.
- Return type:
str
- win
Gets the result of the game.
- Returns:
The result of the game, which can be one of BLACK_WIN, WHITE_WIN, or DRAW.
- Return type:
one of (BLACK_WIN, WHITE_WIN, DRAW)
cshogi.KI2 module
- class cshogi.KI2.Exporter(path=None)[source]
Bases:
objectA class to handle the exporting of a game to KI2 format.
- Parameters:
path (str | None) – Optional path to the file where the KI2 formatted game will be written. If None, no file is opened initially.
- end(reason)[source]
Write the game’s ending condition.
- Parameters:
reason (str) – A string representing the reason for the game’s end (e.g., %TORYO, %SENNICHITE).
- header(names, starttime=None)[source]
Write the game’s header information, including date and player names.
- Parameters:
names (List[str]) – A list containing the names of the players [first_player, second_player].
starttime (datetime | None) – Optional start time of the game. If None, the current time is used.
- class cshogi.KI2.Parser[source]
Bases:
objectA class for parsing Japanese Shogi notation in KI2 format.
- HANDYCAP_SFENS = {'その他': None, '三枚落ち': 'lnsgkgsn1/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '二枚落ち': 'lnsgkgsnl/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '五枚落ち': '2sgkgsn1/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '八枚落ち': '3gkg3/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '六枚落ち': '2sgkgs2/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '十枚落ち': '4k4/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '右香落ち': '1nsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '四枚落ち': '1nsgkgsn1/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '左五枚落ち': '1nsgkgs2/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '平手': 'lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1', '角落ち': 'lnsgkgsnl/1r7/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '飛車落ち': 'lnsgkgsnl/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '飛香落ち': 'lnsgkgsn1/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '香落ち': 'lnsgkgsn1/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1'}
- MOVE_RE = re.compile('(▲|△)(([123456789])([零一二三四五六七八九])|同\u3000?)([歩香桂銀金角飛玉と杏圭全馬龍])(左|直|右)?(上|寄|引)?(打|成|不成)?\\s*')
- RESULT_RE = re.compile('まで(\\d+)手で((先|下|後|上)手の(勝ち|入玉勝ち|反則勝ち|反則負け)|千日手|持将棋|中断)')
- static parse_file(path)[source]
Parses a KI2 format Shogi game notation file.
- Parameters:
path (str) – Path to the file containing the KI2 notation.
- Returns:
An instance of the Parser class containing all the extracted information.
- Raises:
KIF.ParserException – In the case of a parse error.
- Return type:
- static parse_move_str(line, board)[source]
Parses a string of moves and applies them to a given board.
- Parameters:
line (str) – String containing the moves in Japanese Shogi notation.
board (Board) – Board object to apply the moves to.
- Returns:
A list of moves parsed from the line.
- static parse_pieces_in_hand(target)[source]
Parses pieces in hand from a given string.
- Parameters:
target (str) – String containing the description of the pieces in hand.
- Returns:
A dictionary representing the pieces in hand.
- Raises:
KIF.ParserException – In the case of a parse error.
- Return type:
Dict
- static parse_str(kif_str)[source]
Parses a KI2 formatted string into a Parser object.
- Parameters:
kif_str (str) – The KI2 formatted string representing the Shogi game.
- Returns:
An instance of the Parser class containing all the extracted information.
- Raises:
KIF.ParserException – In the case of a parse error.
- Return type:
cshogi.KIF module
- class cshogi.KIF.Exporter(path=None)[source]
Bases:
objectA class to handle the exporting of a game to KIF format.
- Parameters:
path (str | None) – Optional path to the file where the KIF formatted game will be written. If None, no file is opened initially.
- end(reason, sec=0, sec_sum=0)[source]
Record the end of the game.
- Parameters:
reason (str) – The reason for the end of the game (e.g., resign, sennichite).
sec (int) – Seconds spent on the last move.
sec_sum (int) – Total seconds spent during the game.
- header(names, starttime=None, handicap=None)[source]
Write the header information to the file.
- Parameters:
names (List[str]) – List of player names.
starttime (datetime | None) – Start time of the game, defaults to current time.
handicap (str | Board | None) – Handicap settings for the game.
- info(info)[source]
Record additional information related to the game.
- Parameters:
info – A string containing additional information.
- class cshogi.KIF.Parser[source]
Bases:
objectA class for parsing Japanese Shogi notation in KIF format.
- HANDYCAP_SFENS = {'その他': None, '三枚落ち': 'lnsgkgsn1/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '二枚落ち': 'lnsgkgsnl/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '五枚落ち': '2sgkgsn1/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '八枚落ち': '3gkg3/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '六枚落ち': '2sgkgs2/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '十枚落ち': '4k4/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '右香落ち': '1nsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '四枚落ち': '1nsgkgsn1/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '左五枚落ち': '1nsgkgs2/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '平手': 'lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1', '角落ち': 'lnsgkgsnl/1r7/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '飛車落ち': 'lnsgkgsnl/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '飛香落ち': 'lnsgkgsn1/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1', '香落ち': 'lnsgkgsn1/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1'}
- MOVE_RE = re.compile('\\A *[0-9]+\\s+(中断|投了|持将棋|千日手|詰み|切れ負け|反則勝ち|反則負け|(([123456789])([零一二三四五六七八九])|同\u3000)([歩香桂銀金角飛玉と杏圭全馬龍])(打|(成?)\\(([0-9])([0-9])\\)))\\s*(\\( *([:0-9]+)/([:0-9]+)\\))?.*\\Z')
- RESULT_RE = re.compile('\u3000*まで、?(\\d+)手で((先|下|後|上)手の(勝ち|入玉勝ち|反則勝ち|反則負け)|千日手|持将棋|中断)')
- static parse_file(path)[source]
Parses a KI2 format Shogi game notation file.
- Parameters:
path (str) – Path to the file containing the KIF notation.
- Returns:
An instance of the Parser class containing all the extracted information.
- Raises:
KIF.ParserException – In the case of a parse error.
- Return type:
- static parse_move_str(line, board)[source]
Parses a string of moves and applies them to a given board.
- Parameters:
line (str) – String containing the moves in Japanese Shogi notation.
board (Board) – Board object to apply the moves to.
- Returns:
A list of moves parsed from the line.
- static parse_pieces_in_hand(target)[source]
Parses pieces in hand from a given string.
- Parameters:
target – String containing the description of the pieces in hand.
- Returns:
A dictionary representing the pieces in hand.
- Raises:
KIF.ParserException – In the case of a parse error.
- static parse_str(kif_str)[source]
Parses a KIF formatted string into a Parser object.
- Parameters:
kif_str – The KIF formatted string representing the Shogi game.
- Returns:
An instance of the Parser class containing all the extracted information.
- Raises:
KIF.ParserException – In the case of a parse error.
- cshogi.KIF.board_to_bod(board)[source]
Convert a given board to a Board Diagram (BOD) representation.
- Parameters:
board (Board) – A Board object representing the current state of the game.
- Returns:
A string representing the Board Diagram (BOD) of the game.
- Return type:
str
- cshogi.KIF.move_to_bod(move, board)[source]
Convert a given move to a Board Diagram (BOD) representation.
- Parameters:
move (int) – An integer representing a specific move.
board (Board) – A Board object representing the current state of the Shogi game.
- Returns:
A string representing the move in Board Diagram (BOD) format.
- Return type:
str
- cshogi.KIF.move_to_kif(move, prev_move=None)[source]
Convert a given move to Japanese KIF notation.
- Parameters:
move (int) – An integer representing the move.
board – A Board object representing the current state of the game.
prev_move (int | None)
- Returns:
A string representing the move in KIF notation.
- Return type:
str
cshogi.PGN module
- class cshogi.PGN.Exporter(path=None, append=False)[source]
Bases:
objectA class to handle the exporting of a game to PGN (Portable Game Notation) format.
- Parameters:
path (str | None) – Optional path to the file where the PGN formatted game will be written. If None, no file is opened initially.
append (bool) – Whether to append to the existing file or create a new one. Defaults to False.
- movetext(moves)[source]
Write the move text section of the PGN format, containing the actual moves of the game.
- Parameters:
moves (List[int]) – List of moves in the game.
- open(path, append=False)[source]
Open a file for writing the PGN formatted game.
- Parameters:
path (str) – Path to the file.
append (bool) – Whether to append to the existing file or create a new one. Defaults to False.
- tag_pair(names, result, event='?', site='?', starttime=None, round=1)[source]
Write the tag pairs section of the PGN format, containing metadata about the game.
- Parameters:
names (List[str]) – List of player names for White and Black.
result (int) – Game result code.
event (str) – Event name, defaults to “?”.
site (str) – Site of the game, defaults to “?”.
starttime (datetime | None) – Start time of the game, defaults to current time.
round (int) – Round number, defaults to 1.
cshogi.cli module
- class cshogi.cli.Ending(*values)[source]
Bases:
Enum- DECLARATION = ('%KACHI', '入玉宣言')
- ILLEGAL = ('%ILLEGAL_MOVE', '{}の反則負け')
- LOSS = ('%TORYO', '{}の勝ち')
- MOVE_LIMIT = ('%JISHOGI', '持将棋')
- REPETITION_DRAW = ('%SENNICHITE', '千日手')
- REPETITION_LOSS = (None, '{}の反則負け')
- REPETITION_WIN = (None, '{}の反則勝ち')
- TIME = ('%TIME_UP', '{}の切れ負け')
- class cshogi.cli.EngineConfig(command: str, name: str | None, options: dict, byoyomi: int | None, time: int | None, inc: int | None)[source]
Bases:
object- Parameters:
command (str)
name (str | None)
options (dict)
byoyomi (int | None)
time (int | None)
inc (int | None)
- byoyomi: int | None
- command: str
- inc: int | None
- name: str | None
- options: dict
- time: int | None
- class cshogi.cli.GameConfig(resign: int | None, mate_win: bool, draw: int, ponder: bool, opening_moves: int, keep_process: bool, display: bool, debug: bool)[source]
Bases:
object- Parameters:
resign (int | None)
mate_win (bool)
draw (int)
ponder (bool)
opening_moves (int)
keep_process (bool)
display (bool)
debug (bool)
- debug: bool
- display: bool
- draw: int
- keep_process: bool
- mate_win: bool
- opening_moves: int
- ponder: bool
- resign: int | None
- class cshogi.cli.GameResult(spec: cshogi.cli.GameSpec, names: tuple[str, str], winner: int | None, csa_code: str, message: str, moves: tuple[int, ...])[source]
Bases:
object- Parameters:
spec (GameSpec)
names (tuple[str, str])
winner (int | None)
csa_code (str)
message (str)
moves (tuple[int, ...])
- csa_code: str
- message: str
- moves: tuple[int, ...]
- names: tuple[str, str]
- winner: int | None
- class cshogi.cli.GameSpec(index: int, round: int, opening: tuple[str, tuple[str, ...]], black_id: int, white_id: int)[source]
Bases:
object- Parameters:
index (int)
round (int)
opening (tuple[str, tuple[str, ...]])
black_id (int)
white_id (int)
- black_id: int
- index: int
- opening: tuple[str, tuple[str, ...]]
- round: int
- white_id: int
- class cshogi.cli.LeagueTable[source]
Bases:
objectPublish standings in stage order once all games in a stage are recorded.
- games_per_stage = 6
- class cshogi.cli.Match(records, games, print_summary, callback, table=None, sprt=None)[source]
Bases:
object
- class cshogi.cli.MatchSprt(elo0, elo1, alpha, beta, engines)[source]
Bases:
objectFeed completed pairs into the test in schedule order, from engine A’s side.
- class cshogi.cli.Player(config: cshogi.cli.EngineConfig, engine: cshogi.usi.Engine.Engine, listener: cshogi.cli.Listener)[source]
Bases:
object- Parameters:
config (EngineConfig)
engine (Engine)
listener (Listener)
- config: EngineConfig
- class cshogi.cli.SprtConfig(elo0, elo1, alpha=0.05, beta=0.05, engines=None)[source]
Bases:
objectLogistic Elo hypotheses for engine A against B (one-based engine numbers).
- Parameters:
elo0 (float)
elo1 (float)
alpha (float)
beta (float)
engines (tuple[int, int] | None)
- alpha: float
- beta: float
- elo0: float
- elo1: float
- engines: tuple[int, int] | None
- cshogi.cli.league(engine1, engine2, engine3, options1=None, options2=None, options3=None, names=None, *, games=1, resign=None, mate_win=False, byoyomi=None, time=None, inc=None, draw=256, ponder=False, no_swap=False, opening=None, opening_moves=24, opening_seed=None, opening_index=None, keep_process=False, csa=None, multi_csa=False, pgn=None, no_pgn_moves=False, is_display=False, debug=False, concurrency=1, worker_options=None, sprt=None)[source]
Play two games per pairing and opening. Return standings in AB, AC, BC order.
- Parameters:
engine1 (str)
engine2 (str)
engine3 (str)
sprt (SprtConfig | None)
- cshogi.cli.main(engine1, engine2, options1=None, options2=None, names=None, games=1, resign=None, mate_win=False, byoyomi=None, time=None, inc=None, draw=256, ponder=False, no_swap=False, opening=None, opening_moves=24, opening_seed=None, opening_index=None, keep_process=False, csa=None, multi_csa=False, pgn=None, no_pgn_moves=False, is_display=False, debug=False, print_summary=True, callback=None, concurrency=1, worker_options=None, sprt=None)[source]
Executes a series of games between two USI engines.
- Parameters:
engine1 (str) – Path to the first USI engine.
engine2 (str) – Path to the second USI engine.
options1 (dict | None) – Optional engine options for engine1.
options2 (dict | None) – Optional engine options for engine2.
names (list[str] | None) – Optional list with one display name per engine.
games (int) – Non-negative number of games to play.
resign (int | None) – Resignation threshold. If a score falls below the negative of this value, the engine resigns.
mate_win (bool) – Whether a checkmate is considered a win.
byoyomi (int | list[int] | None) – Byoyomi time in milliseconds. It can be different for each engine.
time (int | list[int] | None) – Time control in milliseconds. It can be different for each engine.
inc (int | list[int] | None) – Increment time in milliseconds per move. It can be different for each engine.
draw (int) – Number of moves before a draw is declared.
ponder (bool) – Whether to use pondering.
no_swap (bool) – Whether to disable engine swapping.
opening (str | None) – Path to a file containing opening positions.
opening_moves (int) – Number of opening moves to play.
opening_seed (int | None) – Seed for random shuffling of openings.
opening_index (int | None) – Specific index of an opening to use.
keep_process (bool) – Whether to keep the engine process running after completion.
csa (str | None) – Optional path for CSA file export.
multi_csa (bool) – Whether to use multi-CSA format.
pgn (str | None) – Optional path for PGN file export.
no_pgn_moves (bool) – Whether to omit PGN move listing.
is_display (bool) – Whether to display the game board.
debug (bool) – Whether to enable debugging mode.
print_summary (bool) – Whether to print the summary after the match.
callback (Callable | None) – Optional callback function executed after each game.
concurrency (int) – Number of workers playing independently.
worker_options (list[list[dict] | None] | None) – One entry per engine, either None or one option dictionary per worker.
sprt (SprtConfig | None) – Optional sequential test on color-swapped pairs. Requires an even game limit.
- Returns:
Dictionary containing game results and statistics.
- Return type:
dict
cshogi.elo module
- class cshogi.elo.Elo(wins, losses, draws)[source]
Bases:
objectA class for calculating Elo ratings based on wins, losses, and draws.
- Parameters:
wins (int) – Number of wins.
losses (int) – Number of losses.
draws (int) – Number of draws.
- class cshogi.elo.SPRT(elo0, elo1, alpha=0.05, beta=0.05)[source]
Bases:
objectPentanomial SPRT with logistic Elo hypotheses and fixed Wald bounds.
A sample is the tested engine’s average score over a color-swapped pair. The first decision freezes the LLR and the observed counts.
- Parameters:
elo0 (float)
elo1 (float)
alpha (float)
beta (float)
- property counts: tuple[int, ...]
Observed pair counts in ascending score order, without pseudocounts.