cshogi package

Module contents

class cshogi.Board

Bases: object

Board 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

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.

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

Check for a win according to the Nyūgyoku declaration rule (27-point rule).

Returns:

True if the game is in a state of Nyūgyoku declaration (a win by entering king according to the 27-point rule), False otherwise.

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

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:

LegalMoveList

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.

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.

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

Generates a list of pseudo-legal moves from the current board position.

Returns:

An iterator that yields pseudo-legal moves.

Return type:

PseudoLegalMoveList

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:

SvgWrapper

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.DfPn

Bases: object

Class 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.

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

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.

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: object

An iterator class to generate legal moves.

class cshogi.PseudoLegalMoveList

Bases: object

An 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.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.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.CSA module

class cshogi.CSA.Exporter(path=None, append=False, encoding=None)[source]

Bases: object

A 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.

close()[source]

Close the file.

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.

open(path, append=False, encoding=None)[source]

Open the file for writing.

Parameters:
  • path (str) – The file path to export to.

  • append (bool, optional) – Whether to append to the file, defaults to False.

  • encoding (str, optional) – The encoding of the file, defaults to None.

class cshogi.CSA.Parser

Bases: object

A 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: object

A 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.

close()[source]

Close the file.

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.

move(move, comment=None)[source]

Write a move to the file in KI2 format.

Parameters:
  • move (int) – An integer representing the move.

  • comment (str | None) – Optional comment string to be associated with the move.

open(path)[source]

Open a file for writing the KI2 formatted game.

Parameters:

path (str) – Path to the file.

class cshogi.KI2.Parser[source]

Bases: object

A 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:

Parser

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:

Parser

cshogi.KI2.move_to_ki2(move, board)[source]

Convert a given move to Japanese KI2 notation.

Parameters:
  • move (int) – An integer representing the move.

  • board (Board) – A Board object representing the current state of the game.

Returns:

A string representing the move in KI2 notation.

Return type:

str

cshogi.KIF module

class cshogi.KIF.Exporter(path=None)[source]

Bases: object

A 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.

close()[source]

Close the file.

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.

move(move, sec=0, sec_sum=0)[source]

Record a move in the game.

Parameters:
  • move (int) – The move to record.

  • sec (int) – Seconds spent on the move.

  • sec_sum (int) – Total seconds spent so far.

open(path)[source]

Open a file for writing the KIF formatted game.

Parameters:

path (str) – Path to the file.

class cshogi.KIF.Parser[source]

Bases: object

A 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:

Parser

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.

exception cshogi.KIF.ParserException[source]

Bases: Exception

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.KIF.sec_to_time(sec)[source]

cshogi.PGN module

class cshogi.PGN.Exporter(path=None, append=False)[source]

Bases: object

A 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.

close()[source]

Close the file.

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.PGN.move_to_san(move)[source]

cshogi.cli module

cshogi.cli.main(engine1, engine2, options1={}, options2={}, 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)[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) – Optional engine options for engine1.

  • options2 (Dict) – Optional engine options for engine2.

  • names (List[str] | None) – Optional names for the engines.

  • games (int) – 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.

Returns:

Dictionary containing game results and statistics.

Return type:

Dict

cshogi.cli.to_score(m)[source]
cshogi.cli.usi_info_to_csa_comment(board, info)[source]
cshogi.cli.usi_info_to_score(info)[source]

cshogi.elo module

class cshogi.elo.Elo(wins, losses, draws)[source]

Bases: object

A 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.

diff()[source]

Calculates the Elo difference.

Returns:

The Elo difference.

Return type:

float

draw_ratio()[source]

Calculates the draw ratio.

Returns:

The draw ratio.

Return type:

float

error_margin()[source]

Calculates the error margin.

Returns:

The error margin.

Return type:

float

los()[source]

Calculates the likelihood of superiority.

Returns:

The likelihood of superiority, in percentage.

Return type:

float

point_ratio()[source]

Calculates the point ratio.

Returns:

The point ratio.

Return type:

float

cshogi.elo.elo_diff(p)[source]
cshogi.elo.erf_inv(x)[source]
cshogi.elo.phi_inv(p)[source]

Subpackages