Ejemplo n.º 1
0
 def test_default(self):
     board_none = shogi.Board()
     board_sfen = shogi.Board(shogi.STARTING_SFEN)
     self.assertEqual(board_none, board_sfen)
     self.assertEqual(board_none.sfen(), shogi.STARTING_SFEN)
     self.assertEqual(str(board_none), str(board_sfen))
     self.assertEqual(repr(board_none), repr(board_sfen))
     self.assertEqual(board_none.turn, shogi.BLACK)
Ejemplo n.º 2
0
def setup_board(game):
    if game.variant_name == "From Position":
        board = shogi.Board(game.initial_fen)
    else:
        board = shogi.Board()  # Standard
    moves = game.state["moves"].split()
    for move in moves:
        board = update_board(board, move)

    return board
Ejemplo n.º 3
0
 def test_issue_15(self):
     # Issue: All moves from "9a" are not pseudo legal.
     board = shogi.Board()
     # pass turn to white
     board.push(shogi.Move.from_usi('9h9g'))
     move = shogi.Move.from_usi('9a9b')
     self.assertEqual(board.is_pseudo_legal(move), True)
Ejemplo n.º 4
0
 def test_sfen_piece_in_hand_order(self):
     # ref: https://web.archive.org/web/20080131070731/http://www.glaurungchess.com/shogi/usi.html
     # Invalid sfen, but acceptable in python-shogi
     board = shogi.Board(
         '4k4/9/9/9/9/9/9/9/4K4 b 9p2l2n2s2gbr9P2L2N2S2GBR 1')
     self.assertEqual(board.sfen(),
                      '4k4/9/9/9/9/9/9/9/4K4 b RB2G2S2N2L9Prb2g2s2n2l9p 1')
Ejemplo n.º 5
0
def tokens_to_board(tokens):
    board = shogi.Board()
    while len(tokens) > 0:
        token = tokens.pop(0)
        if token == "position":
            continue
        if token == "moves":
            continue
        if token == "startpos":
            board.reset()
            continue
        if token == "sfen":
            # 後続がsfen
            sfen_str = " ".join(tokens[:4])
            del tokens[:4]
            board.set_sfen(sfen_str)
            continue
        if len(token) > 10:
            # sfenと思われる
            sfen_str = " ".join([token] + tokens[:3])
            del tokens[:3]
            board.set_sfen(sfen_str)
            continue
        move_obj = shogi.Move.from_usi(token)
        if move_obj not in board.generate_legal_moves():
            print(f"Warning: {token} is illegal.")
        board.push_usi(token)
    return board
Ejemplo n.º 6
0
    def _run_single_match(self, black_engine: int) -> MatchResult:
        for i in range(2):
            # ゲームごとにisreadyが必要。
            self._isready_engine(i)
        for i in range(2):
            self._engine_write(i, "usinewgame")
        current_engine = black_engine
        board = shogi.Board()
        draw = False
        winner = None
        gameover_reason = ""
        while True:
            bestmove = self._get_bestmove(board, current_engine)
            if bestmove == "resign":
                winner = 1 - current_engine
                gameover_reason = "resign"
                break
            if bestmove == "win":
                # 宣言勝ち
                # 審査せずに勝ちとみなす
                winner = current_engine
                gameover_reason = "win"
                break
            move_obj = shogi.Move.from_usi(bestmove)
            if move_obj not in board.generate_legal_moves():
                # board.is_legal()は、相手陣から引くときに成る場合がなぜかillegalとなってしまう
                # 非合法手(連続王手の千日手は判定されない)
                winner = 1 - current_engine
                gameover_reason = "illegal_move"
                break
            board.push(move_obj)
            if board.is_fourfold_repetition():
                # 千日手
                if self._check_repetition_with_check(board):
                    # 連続王手の千日手
                    # 最後の指し手が非合法なので、負け
                    winner = 1 - current_engine
                    gameover_reason = "repetition_with_check"
                else:
                    gameover_reason = "repetition"
                    draw = True
                break
            if board.move_number > self.rule.max_moves:
                # 手数制限により引き分け
                # 初形がmove_number==1なので、256手で引き分けなら257で判定
                # 最大手数で詰んでいるときは、例外的に最後の手を指した側の勝ち(stalemateは微妙だが)
                if board.is_game_over():
                    winner = current_engine
                else:
                    draw = True
                gameover_reason = "max_moves"
                break
            current_engine = 1 - current_engine

        for i in range(2):
            win_code = "draw" if draw else ("win" if i == winner else "lose")
            self._engine_write(i, f"gameover {win_code}")

        kifu = list(map(str, board.move_stack))
        return MatchResult(draw, winner, gameover_reason, kifu)
Ejemplo n.º 7
0
    def test_match(self):
        tcp = CSA.TCPProtocol('127.0.0.1')
        self.add_response(tcp, 'LOGIN:username OK\n')
        tcp.login('username', 'password')
        self.add_response(tcp, TEST_SUMMARY_STR)
        game_summary = tcp.wait_match()

        board = shogi.Board(game_summary['summary']['sfen'])
        self.add_response(tcp, 'START:20150505-CSA25-3-5-7\n')
        tcp.agree()

        self.add_response(tcp, '+5756FU,T1\n')
        (turn, usi, spend_time, message) = tcp.wait_server_message(board)
        board.push(shogi.Move.from_usi(usi))
        self.assertEqual(turn, shogi.BLACK)
        self.assertEqual(spend_time, 1.0)

        self.assertEqual(board.sfen(), 'lnsgkgsnl/1r5b1/ppppppppp/9/9/4P4/PPPP1PPPP/1B5R1/LNSGKGSNL w - 2')

        next_move = shogi.Move.from_usi('8c8d')
        board.push(next_move)
        self.add_response(tcp, '-8384FU,T2\n')
        response_line = tcp.move(board.pieces[next_move.to_square], shogi.WHITE, next_move)
        (turn, usi, spend_time, message) = tcp.parse_server_message(response_line, board)
        self.assertEqual(turn, shogi.WHITE)
        self.assertEqual(spend_time, 2.0)

        # without spent time ex.) Shogidokoro
        self.add_response(tcp, '+5655FU\n')
        (turn, usi, spend_time, message) = tcp.wait_server_message(board)
        board.push(shogi.Move.from_usi(usi))
        self.assertEqual(turn, shogi.BLACK)
        self.assertEqual(spend_time, None)
Ejemplo n.º 8
0
def disp_test(model, device, dataset):
    model.eval()
    tensor_list = []
    with torch.no_grad():
        #for i in range(len(dataset)):
        for i in [1, 5]:
            sfen_data, sfen_target = dataset[i]
            # sfenを局面情報へ変換
            data = pos_sfen_to_tensor([sfen_data])
            tensor_list.append(data)
            # sfenを手と勝ち負け情報へ変換
            data = data.to(device)
            board = shogi.Board(sfen=sfen_data)
            print(board.kif_str())
            if ' b ' in sfen_data:
                turn = 'b'
            else:
                turn = 'w'
            index = cpp_lib.move_to_index(sfen_target[0], turn)
            policy,value = model(data)
            print("policy BEST:",policy[0][index])
            print("policy_index",index)
            print("policy_max:",torch.max(policy,1))
            print("policy_min:",torch.min(policy,1))
            print("policy_mean:",torch.mean(policy))
            print("value:",value[0])
Ejemplo n.º 9
0
        def in_castle_threshold(board):
            '''
            Return 1 if we are within the threshold of at least one proper castle formation.
            '''
            for sfen in castles.values():
                # Set the proper peerspective for the castle
                sfen = sfen if board.turn == shogi.BLACK else invert(sfen)
                # Initialize the castle
                castle = shogi.Board(sfen)
                # Transform the castle to a square set to get square indicies
                castle_squares = shogi.SquareSet(castle.occupied[board.turn])

                incorrect = 0
                king_in_place = True
                for square in castle_squares:
                    # Get the piece at the corresponding square in the player's board and castle board
                    p_piece = board.piece_at(square)
                    c_piece = castle.piece_at(square)

                    if not p_piece:  # Empty square
                        incorrect += 1
                    elif p_piece.color != board.turn:  # Enemy piece
                        incorrect += 1
                    elif p_piece.piece_type != c_piece.piece_type:  # Wrong piece
                        if c_piece.piece_type == shogi.KING:  # Player's King in wrong place
                            king_in_place = False
                        else:
                            incorrect += 1

                if king_in_place and incorrect <= CASTLE_THRESHOLD:
                    return 1

            # If we made it through all castle formations without finding a match, return 0
            return 0
Ejemplo n.º 10
0
def read_kihu(kihu_list_file):
    positions = []
    with open(kihu_list_file, 'r') as f:
        for line in f.readlines():
            filepath = line.rstrip('|r|n')
            kihu = shogi.CSA.Parser.parse_file(filepath)[0]
            win_color = shogi.BLACK if kihu['win'] == 'b' else shogi .WHITE
            board = shogi.Board()
            for move in kihu['moves']:
                if board.turn == shogi.BLACK:
                    piece_bb = copy.deepcopy(board.piece_bb)
                    occupied = copy.deepcopy(board.occupied[shogi.BLACK],
                                             board.occupied[shogi.WHITE])
                    pieces_in_hand = copy.deepcopy(
                        (board.pieces_in_hand[shogi.BLACK],
                         board.pieces_in_hand[shogi.WHITE])
                    )
                else:
                    piece_bb = [bb_rotate_180(bb) for bb in board.piece_bb]
                    occupied = (bb_rotate_180(board.occupied[shogi.WHITE]),
                                bb_rotate_180(board.occupied[shogi.BLACK]))
                    pieces_in_hand
                        = copy.deepcopy((board.pieces_in_hand[shogi.WHITE],
                                        board.pieces_in_hand[shogi.BLACK]))
                #move label
                move_label = make_output_label(shogi.Move.from_usi(move),
                                               board.turn)
                #result
                win = 1 if win_color == board.turn else 0

                positions.append((piece_bb, occupied, pieces_in_hand, move_label, win))
            board.push_usi(move)
        return positions
Ejemplo n.º 11
0
 def _run_single_evaluation(self, kifu: str) -> Tuple[str, str]:
     board = shogi.Board()
     moves = kifu.rstrip().split(" ")[2:]  # startpos moves以外
     for move in moves[:-1]:  # 最後の手以外
         board.push_usi(move)
     bestmove = self._get_bestmove(board, 0)
     return bestmove, moves[-1]  # 予測手と正解
Ejemplo n.º 12
0
def main():
    conn = sqlite3.connect(DB_PATRH)
    c = conn.cursor()

    c.execute('drop table if exists csa_record')

    c.execute('create table csa_record (id integer primary key autoincrement, sfen_pos, sfen_move, winner)')
    
    kif_list = glob.glob(CSA_PATH)
    for i,path in enumerate(kif_list):
        print(i,' ',end='',flush=True)
        kif_info_list = shogi.CSA.Parser.parse_file(path)
        for kif in kif_info_list: 
            board = shogi.Board(sfen=kif['sfen'])
            moves = kif['moves']
            winner = kif['win']
        
            for move in moves:
                # 局面データを追加
                pos_sfen = board.sfen()
                move_sfen = move
                c.execute('insert into csa_record (sfen_pos, sfen_move, winner) values (?,?,?)',(pos_sfen, move_sfen,winner))
                # 次の局面へ移動
                board.push(shogi.Move.from_usi(move))
        if i % 10 == 0:
            conn.commit()

    conn.commit()
    conn.close()
Ejemplo n.º 13
0
    def test_bishop_center(self):
        board = shogi.Board('9/9/9/9/4B4/9/9/9/9 b - 1')
        self.assertTrue(shogi.Move.from_usi('5e4d') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e3c') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e2b') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e1a') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e6f') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e7g') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e8h') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e9i') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e4f') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e3g') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e2h') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e1i') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e6d') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e7c') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e8b') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e9a') in board.legal_moves)

        self.assertTrue(shogi.Move.from_usi('5e3c+') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e2b+') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e1a+') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e7c+') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e8b+') in board.legal_moves)
        self.assertTrue(shogi.Move.from_usi('5e9a+') in board.legal_moves)

        self.assertEqual(len(board.legal_moves), 22)
Ejemplo n.º 14
0
 def test_suicide(self):
     board = shogi.Board('1k7/9/1G7/9/9/9/9/9/9 w - 1')
     self.assertTrue(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('8a8b')))
     self.assertTrue(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('8a9b')))
     self.assertTrue(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('8a7b')))
     self.assertFalse(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('8a6b')))
     self.assertEqual(len(board.legal_moves), 2)
Ejemplo n.º 15
0
 def test_is_fourfold_repetition(self):
     board = shogi.Board('ln3g2l/1r2g1sk1/1pp1ppn2/p2ps1ppp/1PP6/2GP4P/P1N1PPPP1/1R2S1SK1/L4G1NL w Bb 44')
     for move_str in ['9d9e', '8h6h', '8b6b', '6h8h', '6b8b', '8h6h', '8b6b', '6h8h',
                      '6b8b', '8h6h', '8b6b', '6h8h']:
         board.push(shogi.Move.from_usi(move_str))
     self.assertFalse(board.is_fourfold_repetition())
     board.push(shogi.Move.from_usi('6b8b'))
     self.assertTrue(board.is_fourfold_repetition())
Ejemplo n.º 16
0
def fv40(sfen):
    # board = shogi.Board('lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1')
    # board = shogi.Board('9/9/9/9/9/k8/9/9/1R2K4 b Gr2b3g4s4n4l18p 1')
    board = shogi.Board(sfen)
    # print(board.kif_str())
    # eval_mat=0
    pindex = []
    qindex = []
    for square in shogi.SQUARES:
        piece = board.piece_at(square)
        index = 0
        index2 = 0
        if piece and piece.piece_type != 8:
            if piece.piece_type < 7:
                index = 12 + piece.color + piece.piece_type * 2
                index2 = 12 + 1 - piece.color + piece.piece_type * 2
            elif piece.piece_type in {9, 10, 11, 12}:
                index = 12 + piece.color + 5 * 2
                index2 = 12 + 1 - piece.color + 5 * 2
            elif piece.piece_type == 7:
                index = 12 + piece.color + 8 * 2
                index2 = 12 + 1 - piece.color + 8 * 2
            elif piece.piece_type == 13:
                index = 12 + piece.color + 7 * 2
                index2 = 12 + 1 - piece.color + 7 * 2
            elif piece.piece_type == 14:
                index = 12 + piece.color + 9 * 2
                index2 = 12 + 1 - piece.color + 9 * 2
    #        print(SQUARES_R90[square], piece.color, piece.piece_type,index,BonaPiece[index])
    # print(SQUARES_R90[square]+BonaPiece[index])
            pindex.append(SQUARES_R90[square] + BonaPiece[index])
            qindex.append(80 - SQUARES_R90[square] + BonaPiece[index2])
            # if piece.color == shogi.BLACK:
            #     eval_mat += material[piece.piece_type]
            # else:
            #     eval_mat -= material[piece.piece_type]

    # print(board.pieces_in_hand)
    for color in shogi.COLORS:
        for piece_type, piece_count in board.pieces_in_hand[color].items():
            index = BonaPiece[color + (piece_type - 1) * 2]
            index2 = BonaPiece[1 - color + (piece_type - 1) * 2]
            for i in range(piece_count):
                # print(index+i)
                pindex.append(index + i)
                qindex.append(index2 + i)
            # if color == shogi.BLACK:
            #     eval_mat += material[piece_type] * piece_count
            # else:
            #     eval_mat -= material[piece_type] * piece_count

    # print(pindex,len(pindex))
    if board.turn == shogi.BLACK:
        return SQUARES_R90[board.king_squares[0]], 80 - SQUARES_R90[
            board.king_squares[1]], pindex, qindex
    else:
        return 80 - SQUARES_R90[board.king_squares[1]], SQUARES_R90[
            board.king_squares[0]], qindex, pindex
Ejemplo n.º 17
0
    def test_check_by_dropping_pawn(self):
        # check by dropping pawn
        board = shogi.Board('kn7/9/1G7/9/9/9/9/9/9 b P 1')
        self.assertTrue(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('P*9b')))
        self.assertEqual(len(board.legal_moves), 76)
        board = shogi.Board('kn7/9/9/1NN6/9/9/9/9/9 b P 1')
        self.assertTrue(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('P*9b')))
        self.assertEqual(len(board.legal_moves), 73)

        # king can escape
        board = shogi.Board('k8/9/9/9/9/9/9/9/9 b P 1')
        self.assertFalse(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('P*9b')))
        self.assertEqual(len(board.legal_moves), 72)

        # dropping pawn is not protected and king cannot escape
        board = shogi.Board('kn7/1n7/9/9/9/9/9/9/9 b P 1')
        self.assertFalse(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('P*9b')))
        self.assertEqual(len(board.legal_moves), 71)

        # dropping pawn is protected but king can escape
        board = shogi.Board('kn7/9/9/1N7/9/9/9/9/9 b P 1')
        self.assertFalse(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('P*9b')))
        self.assertEqual(len(board.legal_moves), 73)
        board = shogi.Board('k8/9/1S7/9/9/9/9/9/9 b P 1')
        self.assertFalse(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('P*9b')))
        self.assertEqual(len(board.legal_moves), 81)

        # dropping pawn can be captured other pieces besides king
        board = shogi.Board('kg7/9/1G7/9/9/9/9/9/9 b P 1')
        self.assertFalse(board.is_suicide_or_check_by_dropping_pawn(shogi.Move.from_usi('P*9b')))
        self.assertEqual(len(board.legal_moves), 77)
Ejemplo n.º 18
0
def board_view():

    global BOARD
    BOARD = shogi.Board()

    global BOARD_HISTORY
    BOARD_HISTORY = [copy.deepcopy(BOARD)]

    return render_template("gui.html")
Ejemplo n.º 19
0
    def __init__(self,board=None,state=None):

        if board is None and state is not None:
            # State is given
            self.board = shogi.Board(move_stack = list(state.getBoard().move_stack))
            self.playerNo = state.getPlayerNo()
            self.visitCount = state.getVisitCount()
            self.winScore = state.getWinScore()
        elif board is not None and state is None:
            # Board is given
            self.board = shogi.Board(move_stack = list(board.move_stack))
            self.visitCount = 0
            self.winScore = 0
        else:
            # No data is given
            self.board = shogi.Board()
            self.visitCount = 0
            self.winScore = 0
Ejemplo n.º 20
0
    def test_code(self):
        # tree = MonteCarloTree(copy.deepcopy(shogi.Board())).init()
        # leaf_node = tree.visit(tree._nodes[0], 0)
        # tree.backup(leaf_node, leaf_node.get_win_rate())
        # candidate = tree.main_line(tree._nodes[0], "", 0)

        tree = MonteCarloTree(copy.deepcopy(shogi.Board())).init()
        for i in range(1000):
            tree.playout(i, 3)
Ejemplo n.º 21
0
 def test_double_pawn_in_a_row(self):
     board = shogi.Board('k8/9/9/9/9/9/9/9/P8 b P 1')
     self.assertFalse(shogi.Move.from_usi('P*9b') in board.legal_moves)
     self.assertFalse(shogi.Move.from_usi('P*9c') in board.legal_moves)
     self.assertFalse(shogi.Move.from_usi('P*9d') in board.legal_moves)
     self.assertFalse(shogi.Move.from_usi('P*9e') in board.legal_moves)
     self.assertFalse(shogi.Move.from_usi('P*9f') in board.legal_moves)
     self.assertFalse(shogi.Move.from_usi('P*9g') in board.legal_moves)
     self.assertFalse(shogi.Move.from_usi('P*9h') in board.legal_moves)
     self.assertEqual(len(board.legal_moves), 65)
Ejemplo n.º 22
0
def main():
    board = shogi.Board(
        '+R+N+SGKG+S+N+R/+B+N+SG+LG+S+N+B/P+LPP+LPP+LP/9/9/9/9/1P2P2P1/6k2 b - 200'
    )
    board.push(shogi.Move.from_usi('5e4d'))
    for i in range(10):
        moves = []
        for legal_move in board.legal_moves:
            moves.append(legal_move)
        print(board.kif_str())
        board.push(moves[0])
Ejemplo n.º 23
0
 def update(self, board):
     """
     Like reset, but resets the position to whatever was supplied for board
     :param shogi.Board board: position to reset to
     :return ShogiEnv: self
     """
     self.board = shogi.Board(board)
     self.map_count_state = defaultdict(int)
     self.map_count_state[self.board.sfen().split(" ")[0]] += 1
     self.winner = None
     self.resigned = False
     return self
Ejemplo n.º 24
0
 def reset(self):
     """
     Resets to begin a new game
     :return ShogiEnv: self
     """
     self.board = shogi.Board()
     self.num_halfmoves = 0
     self.map_count_state = defaultdict(int)
     self.map_count_state[self.board.sfen().split(" ")[0]] += 1
     self.winner = None
     self.resigned = False
     return self
Ejemplo n.º 25
0
 def match(self, rounds, pipe, pid, log_lev=1):
     if log_lev == 1:
         log = {
             1: collections.defaultdict(int),
             -1: collections.defaultdict(int)
         }
         win = {
             1: collections.defaultdict(int),
             -1: collections.defaultdict(int)
         }
         board = {}
     if log_lev == 2:
         win = collections.Counter()
     for R in range(rounds):
         if log_lev == 1:
             round = {
                 1: collections.defaultdict(int),
                 -1: collections.defaultdict(int)
             }
         b = shogi.Board([[-2, -1, -3], [0, -4, 0], [0, 4, 0], [3, 1, 2]],
                         [])
         side = 1
         turn = 0
         while turn < 100:
             nb = self.player[side].make_move(side, b)
             if nb is None:
                 break
             if log_lev == 1:
                 board[nb.__hash__()] = nb
                 log[side][nb.__hash__()] += 1
                 round[side][nb.__hash__()]
             side = -side
             b = nb
             turn += 1
         if turn == 200:
             print "draw"
             continue
         winner = -side
         print(winner)
         if log_lev == 1:
             for b in round[winner].iterkeys():
                 win[winner][b] += 1
         if log_lev == 2:
             win[winner] += 1
     print("thread {} done".format(pid))
     if log_lev == 1:
         pipe.send((log, win, board))
     if log_lev == 2:
         print(win)
         #pipe.send(win)
         pass
Ejemplo n.º 26
0
 def Play(self, threads, fen, depth):
     if fen in self.Premoves:
         return self.Premoves[fen]
     else:
         brd = shogi.Board()
         brd.set_fen(fen)
         pmoves = list(brd.legal_moves)
         if len(pmoves) == 1:
             return pmoves[0].uci()
         else:
             threadid = 0
             self.UnusedThreads = threads
             div = int(len(pmoves) / threads)
             if div < 1:
                 self.UnusedThreads -= len(pmoves)
                 for move in pmoves:
                     self.threadlist.append(
                         threading.Thread(target=self.ProcessMove,
                                          args=(
                                              [move],
                                              brd,
                                              depth,
                                              [threadid],
                                          )))
                     self.threadlist[-1].start()
                     time.sleep(0.8)
                     threadid += 1
             else:
                 for i in range(threads - 1):
                     self.threadlist.append(
                         threading.Thread(target=self.ProcessMove,
                                          args=(
                                              pmoves[div * i:div * (i + 1)],
                                              brd,
                                              depth,
                                              [threadid],
                                          )))
                     self.threadlist[-1].start()
                     time.sleep(0.8)
                     threadid += 1
                 self.threadlist.append(
                     threading.Thread(target=self.ProcessMove,
                                      args=(
                                          pmoves[len(pmoves) -
                                                 div:len(pmoves)],
                                          brd,
                                          depth,
                                          [threadid],
                                      )))
                 self.threadlist[-1].start()
             return None
Ejemplo n.º 27
0
def read_kif24(kifu_list_files):
    positions = []
    with open(kifu_list_files, "r") as f:
        for line in f.readlines():
            #rstrip:指定文字列の削除
            filepath = line.rstrip("\r\n")
            kifu = shogi.KIF.Parser.parse_file(filepath)[0]
            # レーティング情報の追加
            kifu["rate"] = [0, 0]
            # アカウント名のみ抽出
            kifu["names"][0], kifu["rate"][0] = kifu["names"][0].rstrip(
                ")").split("(")
            kifu["names"][1], kifu["rate"][1] = kifu["names"][1].rstrip(
                ")").split("(")
            #条件式が真の場合の値 if 条件式 else 条件式が偽の場合の値
            win_color = shogi.BLACK if kifu["win"] == "b" else shogi.WHITE
            board = shogi.Board()
            for move in kifu["moves"]:
                #盤面の回転(後手番の場合180度回転)
                if board.turn == shogi.BLACK:
                    #先手番
                    piece_bb = copy.deepcopy(board.piece_bb)
                    occupied = copy.deepcopy((board.occupied[shogi.BLACK],
                                              board.occupied[shogi.WHITE]))
                    piece_in_hand = copy.deepcopy(
                        (board.pieces_in_hand[shogi.BLACK],
                         board.pieces_in_hand[shogi.WHITE]))
                else:
                    #後手番
                    piece_bb = [bb_rotate_180(bb) for bb in board.piece_bb]
                    occupied = (bb_rotate_180(board.occupied[shogi.WHITE]),
                                bb_rotate_180(board.occupied[shogi.BLACK]))
                    piece_in_hand = copy.deepcopy(
                        (board.pieces_in_hand[shogi.WHITE],
                         board.pieces_in_hand[shogi.BLACK]))

                #指し手ラベル
                move_label = make_output_label(shogi.Move.from_usi(move),
                                               board.turn)

                #結果
                win = 1 if win_color == board.turn else 0

                positions.append(
                    (piece_bb, occupied, piece_in_hand, move_label, win))
                board.push_usi(move)
    return positions
Ejemplo n.º 28
0
    def __init__(self, master):
        super().__init__(master, width=CANVAS_SIZE[0], height=CANVAS_SIZE[1])

        # 盤面の駒画像
        self.img = [[0] * 10 for i in range(11)]
        # 先手の持ち駒の駒画像
        self.senteImg = [0] * 7
        # 後手の持ち駒の駒画像
        self.goteImg = [0] * 7
        # 盤面
        self.board = shogi.Board()
        self.komaimg = imgset.komaimgset()
        self.Value1 = None
        self.Value2 = None
        self.Value3 = None
        self.banDisplay()
        self.komaDisplay()
Ejemplo n.º 29
0
def read_kifu(kifu_list):
    positions = []
    parser = cshogi.Parser()
    for filepath in kifu_list:
        kifu = shogi.CSA.Parser.parse_file(filepath)[0]
        board = shogi.Board()
        for move in kifu['moves']:
            # bitboard
            piece_bb = copy.deepcopy(board.piece_bb)
            occupied = copy.deepcopy(
                (board.occupied[shogi.BLACK], board.occupied[shogi.WHITE]))
            pieces_in_hand = copy.deepcopy((board.pieces_in_hand[shogi.BLACK],
                                            board.pieces_in_hand[shogi.WHITE]))

            positions.append(
                (piece_bb, occupied, pieces_in_hand, move, kifu['win']))
            board.push_usi(move)
    return positions
Ejemplo n.º 30
0
def read_kifu(kifu_list_file):
    positions = []
    with open(kifu_list_file, 'r') as f:
        for line in f.readlines():
            try:
                filepath = line.rstrip('\r\n')

                #print("kifu file : " , filepath)

                kifu = shogi.CSA.Parser.parse_file(filepath)[0]
                win_color = shogi.BLACK if kifu['win'] == 'b' else shogi.WHITE
                board = shogi.Board()
                for move in kifu['moves']:
                    if board.turn == shogi.BLACK:
                        piece_bb = copy.deepcopy(board.piece_bb)
                        occupied = copy.deepcopy((board.occupied[shogi.BLACK],
                                                  board.occupied[shogi.WHITE]))
                        pieces_in_hand = copy.deepcopy(
                            (board.pieces_in_hand[shogi.BLACK],
                             board.pieces_in_hand[shogi.WHITE]))
                    else:
                        piece_bb = [bb_rotate_180(bb) for bb in board.piece_bb]
                        occupied = (bb_rotate_180(board.occupied[shogi.WHITE]),
                                    bb_rotate_180(board.occupied[shogi.BLACK]))
                        pieces_in_hand = copy.deepcopy(
                            (board.pieces_in_hand[shogi.WHITE],
                             board.pieces_in_hand[shogi.BLACK]))

                    # move label
                    move_label = make_output_label(shogi.Move.from_usi(move),
                                                   board.turn)

                    # result
                    win = 1 if win_color == board.turn else 0

                    positions.append(
                        (piece_bb, occupied, pieces_in_hand, move_label, win))
                    #print(len(piece_bb)) # + " " + str(occupied) + " " + str(pieces_in_hand) + " " + str(move_label) + " " + str(win))
                    board.push_usi(move)
            except:
                print("[NG] " + line)
                #print(sys.exc_info())

    return positions