コード例 #1
0
def run_test_1():
    print('------- Scenario 1: Equivance of Minimax and AlphaBeta --------')
    #-- Scenario 1: Test to make sure MiniMaxAI and AlphaBetaAI are giving the same results
    #-- Here are the various players.
    player_human = HumanPlayer()
    player_mini = MinimaxAI(3, color=True)
    player_alphaBeta = AlphaBetaAI(3, color=True)

    #-- Set up the board in a the following fashion. Remember our AIs are WHITE in these scenarios.
    game = ChessGame(player_human, player_mini)
    game.board.clear_board()
    game.board.set_piece_at(piece=chess.Piece(4, False), square=16)
    game.board.set_piece_at(piece=chess.Piece(2, False), square=8)
    game.board.set_piece_at(piece=chess.Piece(3, False), square=10)
    game.board.set_piece_at(piece=chess.Piece(3, True), square=1)

    #-- Display the board and possible moves.
    print(game)
    print("Possible Moves:")
    for move in game.board.pseudo_legal_moves:
        print(move)

    print('---------------------------')

    #-- Look at the choice for MinimaxAI:
    print('Chosen Move:', player_mini.choose_move(game.board))
    print('---------------------------')

    #-- Look at the choice for AlphaBetaAI:
    print('Chosen Move:', player_alphaBeta.choose_move(game.board))
    print('---------------------------')
コード例 #2
0
    def reset(self):
        chess.Board.clear(self.board)
        agent_rook = chess.Piece(chess.ROOK, self.player_color)
        agent_king = chess.Piece(chess.KING, self.player_color)
        opponent_king = chess.Piece(chess.KING, not self.player_color)
        # An empty board is not a valid board
        while not chess.Board.is_valid(
                self.board
        ):  #This function checks if the board is valid or not. Considers checkmates and checks
            chess.Board.clear_board(self.board)
            agent_rook_pos, agent_king_pos, opponent_king_pos = random.sample(
                range(0, 64), 3)
            map_dict = {
                agent_rook_pos: agent_rook,
                agent_king_pos: agent_king,
                opponent_king_pos: opponent_king
            }
            chess.Board.set_piece_map(self.board,
                                      map_dict)  # position to piece mapping
            self.board.set_castling_fen("-")  # Sets castling rights to none
            self.board.turn = self.player_color
        if self.player_color == chess.BLACK:
            self.engine_move()

        return self._get_current_state()
コード例 #3
0
    def test_piece_to_index(self):
        # Test 1
        board = chess.Board()  # color is True by default
        piece = chess.Piece(chess.ROOK, False)
        index = self.encoder.piece_to_index(piece, board)
        expected = 9

        self.assertEqual(index, expected)

        # Test 2
        board = chess.Board()
        piece = chess.Piece(chess.QUEEN, True)
        index = self.encoder.piece_to_index(piece, board)
        expected = 4

        self.assertEqual(index, expected)

        # Test 3
        board = chess.Board()
        board.turn = False
        piece = chess.Piece(chess.PAWN, True)
        index = self.encoder.piece_to_index(piece, board)
        expected = 6

        self.assertEqual(index, expected)
コード例 #4
0
def read_position(data):
    cursor = 0
    board = chess.Board(fen=None)

    # Side to move
    b, cursor = read_bit(data, cursor)
    if b == 0:
        board.turn = chess.WHITE
    else:
        board.turn = chess.BLACK

    # King positions
    wksq, cursor = read_bits(data, cursor, 6)
    board.set_piece_at(wksq, chess.Piece(chess.KING, chess.WHITE))
    bksq, cursor = read_bits(data, cursor, 6)
    board.set_piece_at(bksq, chess.Piece(chess.KING, chess.BLACK))

    # Piece positions
    for r in range(8)[::-1]:
        for f in range(8):
            sq = chess.square(f, r)
            if sq == wksq or sq == bksq:
                continue

            piece, cursor = read_piece(data, cursor)
            if piece:
                board.set_piece_at(sq, piece)

    # Castling availability
    b, cursor = read_bit(data, cursor)
    if b == 1:
        board.castling_rights |= chess.BB_H1
    b, cursor = read_bit(data, cursor)
    if b == 1:
        board.castling_rights |= chess.BB_A1
    b, cursor = read_bit(data, cursor)
    if b == 1:
        board.castling_rights |= chess.BB_H8
    b, cursor = read_bit(data, cursor)
    if b == 1:
        board.castling_rights |= chess.BB_A8

    # En-passant square
    b, cursor = read_bit(data, cursor)
    if b == 1:
        board.ep_square, cursor = read_bits(data, cursor, 6)

    # 50-move counter, low-bits
    low50, cursor = read_bits(data, cursor, 6)

    # Fullmove counter
    low_full, cursor = read_bits(data, cursor, 8)
    high_full, cursor = read_bits(data, cursor, 8)
    board.fullmove_number = (high_full << 8) | low_full

    # 50-move counter, high-bits
    high50, cursor = read_bit(data, cursor)
    board.halfmove_clock = (high50 << 6) | low50

    return board
コード例 #5
0
def get_random_board(num_pcs=None):
    board = chess.Board(None)
    lst = list(range(64))
    random.shuffle(lst)

    kingw = lst.pop()
    kingb = lst.pop()

    piecew = chess.Piece(chess.KING, True)
    board_map = {kingw: piecew}
    pieceb = chess.Piece(chess.KING, False)
    board_map[kingb] = pieceb

    if num_pcs is None:
        num_pcs = random.randint(0, len(lst))
    for pos in lst[0:num_pcs]:
        min_pcs = 1
        if chess.square_rank(pos) == 0 or chess.square_rank(pos) == 7:
            min_pcs = 2
        p = random.randint(min_pcs, 5)
        col = random.randint(0, 1)
        piece = chess.Piece(p, col)
        board_map[pos] = piece

    board.set_piece_map(board_map)
    return board
コード例 #6
0
ファイル: max_moves.py プロジェクト: alexandru-dinu/chess
def generate_random():
    board = chess.Board()
    board.clear_board()

    board.turn = chess.BLACK

    pos = np.random.choice(chess.SQUARES, replace=False, size=(3, ))

    for i, p in enumerate([chess.KING, chess.QUEEN, chess.QUEEN]):
        board.set_piece_at(pos[i], chess.Piece(p, chess.WHITE))

    while True:
        p = np.random.choice(chess.SQUARES)

        if p in pos:
            continue

        board.set_piece_at(p, chess.Piece(chess.KING, chess.BLACK))
        if board.is_check():
            board.remove_piece_at(p)
            continue

        break

    board.turn = chess.WHITE

    return board
コード例 #7
0
ファイル: max_moves.py プロジェクト: alexandru-dinu/chess
def generate_all():
    xs = []

    board = chess.Board()
    board.clear_board()

    ps = set(list(chess.SQUARES))

    for p1 in tqdm(ps):
        for p2 in (ps - {p1}):
            for p3 in (ps - {p1, p2}):
                for p4 in (ps - {p1, p2, p3}):
                    board = chess.Board()
                    board.clear_board()

                    board.set_piece_at(p1, chess.Piece(chess.KING,
                                                       chess.WHITE))
                    board.set_piece_at(p2, chess.Piece(chess.QUEEN,
                                                       chess.WHITE))
                    board.set_piece_at(p3, chess.Piece(chess.QUEEN,
                                                       chess.WHITE))
                    board.set_piece_at(p4, chess.Piece(chess.KING,
                                                       chess.BLACK))
                    board.turn = chess.BLACK

                    if board.is_check():
                        continue

                    else:
                        board.turn = chess.WHITE
                        xs += [board.fen()]

    return xs
コード例 #8
0
ファイル: test_move.py プロジェクト: haldean/chess
    def testPromotion(self):
        board = """
        __ __ __ __ bK __ __ __
        __ wp __ __ __ __ __ __
        __ __ __ __ __ __ __ __
        __ __ __ __ __ __ __ __
        __ __ __ __ __ __ __ __
        __ __ __ __ __ __ __ __
        __ __ __ __ __ __ __ __
        __ __ __ __ wK __ __ __
        """
        b = chess.Board.parse(board)
        m = chess.Move.on_board((6, 1), (7, 1), b)
        b = b.apply(m)
        self.assertEqual(b[7, 1], chess.Piece(chess.white, chess.queen))

        board = """
        __ __ __ __ bK __ __ __
        __ __ __ __ __ __ __ __
        __ __ __ __ __ __ __ __
        __ __ __ __ __ __ __ __
        __ __ __ __ __ __ __ __
        __ __ __ __ __ __ __ __
        __ __ bp __ __ __ __ __
        __ __ __ __ wK __ __ __
        """
        b = chess.Board.parse(board)
        m = chess.Move.on_board((1, 2), (0, 2), b)
        b = b.apply(m)
        self.assertEqual(b[0, 2], chess.Piece(chess.black, chess.queen))
コード例 #9
0
ファイル: test_hichess.py プロジェクト: H-a-y-k/hichesslib
    def testIsPseudoLegalPromotion(self):
        self.boardWidget.setFen(None)

        a = chess.Move(chess.A7, chess.A8)
        b = chess.Move(chess.A2, chess.A1)
        c = chess.Move(chess.A3, chess.A4)
        d = chess.Move(chess.B7, chess.B8)
        e = chess.Move(chess.C7, chess.C8)

        self.assertFalse(self.boardWidget.isPseudoLegalPromotion(a))
        self.assertFalse(self.boardWidget.isPseudoLegalPromotion(b))
        self.assertFalse(self.boardWidget.isPseudoLegalPromotion(c))

        self.boardWidget.addPieceAt(chess.A2,
                                    chess.Piece(chess.PAWN, chess.BLACK))
        self.boardWidget.addPieceAt(chess.A7,
                                    chess.Piece(chess.PAWN, chess.WHITE))
        self.boardWidget.addPieceAt(chess.B7,
                                    chess.Piece(chess.PAWN, chess.BLACK))
        self.boardWidget.addPieceAt(chess.C7,
                                    chess.Piece(chess.ROOK, chess.WHITE))

        self.assertTrue(self.boardWidget.isPseudoLegalPromotion(a))
        self.assertTrue(self.boardWidget.isPseudoLegalPromotion(b))

        self.assertFalse(self.boardWidget.isPseudoLegalPromotion(c))
        self.assertFalse(self.boardWidget.isPseudoLegalPromotion(d))
        self.assertFalse(self.boardWidget.isPseudoLegalPromotion(e))
コード例 #10
0
def get_random_board(seed=222):
    #-- set random seed to get reproduciable results
    random.seed(seed)

    #-- Get random number of white and black pieces to be put on the board
    num_white = random.randint(1, 16)
    num_black = random.randint(1, 16)

    #-- Initialize Board
    board = chess.Board()
    board.clear_board()

    #-- List of all open board positions
    open_positions = [i for i in range(64)]
    #-- Shuffle it cause we're just gonna pop them off later. 
    random.shuffle(open_positions)
    #-- Index of all pieces that can be chosen for white and black.
    pieces = [1,1,1,1,1,1,1,1,2,2,3,3,4,4,5]
    other_pieces_white = copy.deepcopy(pieces)
    other_pieces_black = copy.deepcopy(pieces)
    #-- Shuffle so we can just pop off a random piece
    random.shuffle(other_pieces_black)
    random.shuffle(other_pieces_white)
    
    #-- Set positions for Kings
    board.set_piece_at(open_positions.pop(), chess.Piece(6, True))
    board.set_piece_at(open_positions.pop(), chess.Piece(6, False))

    #-- Set other random pieces in random positions
    for _ in range(num_white - 1):
        board.set_piece_at(open_positions.pop(), chess.Piece(other_pieces_white.pop(), True))
    for _ in range(num_black - 1):
        board.set_piece_at(open_positions.pop(), chess.Piece(other_pieces_black.pop(), False))

    return board
コード例 #11
0
ファイル: logic.py プロジェクト: nadavmoran/Bug-House
def is_transplant_legal(
    board,
    pocket,
    square,
    piece,
):
    '''
    checks if a transplant is legal, if yes it applies it
    :param board:
    a chess.Board object
    :param pocket:
    a chess.Pocket object
    :param square:
    the square the player chose
    :param piece:
    the piece transplanted
    :return:
    true if the transplant legal, else false
    '''
    piece = piece_letter_to_piece_type(piece)
    if not board.is_check():
        board.set_piece_at(square, chess.Piece(piece, board.turn))
        pocket.remove(piece)
        board.push(chess.Move.null())
        return True
    board.set_piece_at(square, chess.Piece(piece, board.turn))
    if board.is_check():
        board.remove_piece_at(square)
        return False
    pocket.remove(piece)
    board.push(chess.Move.null())
    return True
コード例 #12
0
ファイル: test_move.py プロジェクト: haldean/chess
    def testCastle(self):
        board = """
        bR __ __ __ bK __ __ bR
        bp __ bp bp __ bp bp bp
        __ __ __ __ __ __ __ __
        __ __ wR __ __ __ __ wR
        __ bp __ __ __ __ __ __
        wp __ __ __ __ __ __ __
        __ wp wp wp wp wp wp wp
        __ wN wB wQ wK wB wN __
        """
        b = chess.Board.parse(board)
        self.assertTrue(b.can_castle(chess.black, chess.kingside))

        ks_m = chess.Move.on_board((7, 4), (7, 6), b)
        self.assertTrue(ks_m.is_castle)
        self.assertEqual(ks_m.castle, (chess.black, chess.kingside))
        self.assertEqual("0-0", ks_m.algebraic)
        self.assertEqual(ks_m, chess.parse_algebraic(b, chess.black, "0-0"))
        ks_b = b.apply(ks_m)
        self.assertFalse(ks_b.can_castle(chess.black, chess.kingside))
        self.assertFalse(ks_b.can_castle(chess.black, chess.queenside))
        self.assertEqual(ks_b[7, 5], chess.Piece(chess.black, chess.rook))

        qs_m = chess.Move.on_board((7, 4), (7, 2), b)
        self.assertTrue(qs_m.is_castle)
        self.assertEqual(qs_m.castle, (chess.black, chess.queenside))
        self.assertEqual("0-0-0", qs_m.algebraic)
        self.assertEqual(qs_m, chess.parse_algebraic(b, chess.black, "0-0-0"))
        qs_b = b.apply(qs_m)
        self.assertFalse(qs_b.can_castle(chess.black, chess.kingside))
        self.assertFalse(qs_b.can_castle(chess.black, chess.queenside))
        self.assertEqual(qs_b[7, 3], chess.Piece(chess.black, chess.rook))
コード例 #13
0
    def get_raw(self, idx):
        if self.file is None:
            self.file = open(self.filename, 'r+b')
            self.bytes = mmap.mmap(self.file.fileno(), 0)

        base = PACKED_SFEN_VALUE_BYTES * idx
        br = BitReader(self.bytes, base)

        bd = chess.Board(fen=None)
        bd.turn = not br.readBits(1)
        white_king_sq = br.readBits(6)
        black_king_sq = br.readBits(6)
        bd.set_piece_at(white_king_sq, chess.Piece(chess.KING, chess.WHITE))
        bd.set_piece_at(black_king_sq, chess.Piece(chess.KING, chess.BLACK))

        assert (black_king_sq != white_king_sq)

        for rank_ in range(8)[::-1]:
            br.refill()
            for file_ in range(8):
                i = chess.square(file_, rank_)
                assert (i == rank_ * 8 + file_)
                if white_king_sq == i or black_king_sq == i:
                    continue
                if br.readBits(1):
                    assert (bd.piece_at(i) == None)
                    piece_index = br.readBits(3)
                    piece = HUFFMAN_MAP[piece_index]
                    color = br.readBits(1)
                    bd.set_piece_at(i, chess.Piece(piece, not color))
                    br.refill()

        br.seek(base + 32)
        next_val = br.readBits(16)
        score = twos(next_val, 16)

        move = br.readBits(16)
        to_ = move & 63
        from_ = (move & (63 << 6)) >> 6

        br.refill()
        ply = br.readBits(16)
        #bd.fullmove_number = ply // 2

        white_ori = ply & 3
        black_ori = (ply >> 2) & 3

        move = chess.Move(from_square=chess.SQUARES[from_],
                          to_square=chess.SQUARES[to_])

        # 1, 0, -1
        game_result = br.readBits(8)
        outcome = {1: 1.0, 0: 0.5, 255: 0.0}[game_result]
        outs = bd.fen().split()[:2]
        print(
            convert_fen(outs[0], white_ori, black_ori) + " " + outs[1].upper())
        print("outcome: ", outcome)
        print("score: ", score)
        print("oris : ", white_ori, black_ori)
        return bd, move, outcome, score
コード例 #14
0
def get_pawn_start():
    board = chess.Board()
    board.clear()
    board.set_piece_at(12, chess.Piece(chess.PAWN, True))
    board.set_piece_at(4, chess.Piece(chess.KING, True))
    board.set_piece_at(60, chess.Piece(chess.KING, False))
    board.turn = True
    return board
コード例 #15
0
def get_rook_start():
    board = chess.Board()
    board.clear()
    board.set_piece_at(1, chess.Piece(chess.ROOK, True))
    board.set_piece_at(2, chess.Piece(chess.KING, True))
    board.set_piece_at(60, chess.Piece(chess.KING, False))
    board.turn = True
    return board
コード例 #16
0
def num_to_piece(n):
    if n == 0:
        return None
    else:
        if n < 7:
            return chess.Piece(n, True)
        else:
            return chess.Piece(n - 6, False)
コード例 #17
0
 def generate_position_maps(self):
     for i, j in itertools.permutations(chess.SQUARES, 2):
         if self.white_piece == chess.PAWN and chess.square_rank(j) == 8:
             continue  # Pawn in 8th rank is already promoted
         yield {
             i: chess.Piece(chess.KING, chess.BLACK),
             j: chess.Piece(self.white_piece, chess.WHITE)
         }
コード例 #18
0
def get_knight_bishop_start():
    board = chess.Board()
    board.clear()
    board.set_piece_at(0, chess.Piece(chess.BISHOP, True))
    board.set_piece_at(1, chess.Piece(chess.KNIGHT, True))
    board.set_piece_at(2, chess.Piece(chess.KING, True))
    board.set_piece_at(56, chess.Piece(chess.KING, False))
    board.turn = True
    return board
コード例 #19
0
    def get_raw(self, idx):
        if self.file is None:
            self.file = open(self.filename, 'r+b')
            self.bytes = mmap.mmap(self.file.fileno(), 0)

        base = PACKED_SFEN_VALUE_BYTES * idx
        br = BitReader(self.bytes, base)

        bd = chess.Board(fen=None)
        bd.turn = not br.readBits(1)
        white_king_sq = br.readBits(6)
        black_king_sq = br.readBits(6)
        bd.set_piece_at(white_king_sq, chess.Piece(chess.KING, chess.WHITE))
        bd.set_piece_at(black_king_sq, chess.Piece(chess.KING, chess.BLACK))

        assert (black_king_sq != white_king_sq)

        for rank_ in range(8)[::-1]:
            br.refill()
            for file_ in range(8):
                i = chess.square(file_, rank_)
                if white_king_sq == i or black_king_sq == i:
                    continue
                if br.readBits(1):
                    assert (bd.piece_at(i) == None)
                    piece_index = br.readBits(3)
                    piece = HUFFMAN_MAP[piece_index]
                    color = br.readBits(1)
                    bd.set_piece_at(i, chess.Piece(piece, not color))
                    br.refill()

        br.seek(base + 32)
        score = twos(br.readBits(16), 16)
        move = br.readBits(16)
        to_ = move & 63
        from_ = (move & (63 << 6)) >> 6

        br.refill()
        ply = br.readBits(16)
        bd.fullmove_number = ply // 2

        move = chess.Move(from_square=chess.SQUARES[from_],
                          to_square=chess.SQUARES[to_])

        # 1, 0, -1
        game_result = br.readBits(8)
        outcome = {1: 1.0, 0: 0.5, 255: 0.0}[game_result]

        if abs(score) > 400:
            next_idx = (idx + 1) % self.len
            return self.get_raw(next_idx)

        if not is_quiet(bd, from_, to_):
            next_idx = (idx + 1) % self.len
            return self.get_raw(next_idx)

        return bd, move, outcome, score
コード例 #20
0
ファイル: test_chessLogic.py プロジェクト: surrsurus/YACS
 def test_remove(self):
     wking = chess.Piece(1, "E", True, chess.PieceType.king, True)
     bking = chess.Piece(8, "E", True, chess.PieceType.king, False)
     self.board.addpiece(wking)
     self.board.addpiece(bking)
     self.logic.remove(wking, self.board)
     self.assertFalse(wking.active)
     self.assertTrue(
         self.board.getpos(5, 1).gettype() == chess.PieceType.empty)
コード例 #21
0
    def test_get_set(self):
        """Tests the get and set methods."""
        pos = chess.Position()
        self.assertEqual(pos["b1"], chess.Piece("N"))

        del pos["e2"]
        self.assertEqual(pos[chess.Square("e2")], None)

        pos[chess.Square("e4")] = chess.Piece("r")
        self.assertEqual(pos["e4"], chess.Piece("r"))
コード例 #22
0
ファイル: test_chessLogic.py プロジェクト: surrsurus/YACS
    def test_getValidKingMoves(self):
        wking = chess.Piece(1, "E", True, chess.PieceType.king, True)
        bking = chess.Piece(8, "E", True, chess.PieceType.king, False)
        wking2 = chess.Piece(4, "E", True, chess.PieceType.king, True)
        wking3 = chess.Piece(8, "H", True, chess.PieceType.king, True)
        wking4 = chess.Piece(4, "H", True, chess.PieceType.king, True)
        wpawn = chess.Piece(7, "E", True, chess.PieceType.pawn, True)
        bpawn = chess.Piece(7, "D", True, chess.PieceType.pawn, False)
        wrook = chess.Piece(1, "A", True, chess.PieceType.rook, True)
        wrook2 = chess.Piece(1, "H", True, chess.PieceType.rook, True)

        self.board.addpieces(wking, bking, wking2, wking3, wking4, wpawn,
                             bpawn, wrook, wrook2)
        wkingmoves = [((5, 1), (6, 1)), ((5, 1), (6, 2)), ((5, 1), (4, 1)),
                      ((5, 1), (4, 2)), ((5, 1), (5, 2)),
                      ((5, 1), (7, 1, chess.SpecialMove.king_castle)),
                      ((5, 1), (3, 1, chess.SpecialMove.queen_castle))]
        bkingmoves = [((5, 8), (6, 8)), ((5, 8), (6, 7)), ((5, 8), (4, 8)),
                      ((5, 8), (5, 7))]
        wking2moves = [((5, 4), (6, 4)), ((5, 4), (6, 3)), ((5, 4), (4, 4)),
                       ((5, 4), (4, 5)), ((5, 4), (5, 5)), ((5, 4), (5, 3)),
                       ((5, 4), (6, 5)), ((5, 4), (4, 3))]
        self.assertTrue(
            set(
                self.logic.getValidKingMoves(wking.getpos().getPosAsPair(),
                                             self.board)) == set(wkingmoves))
        self.assertTrue(
            set(
                self.logic.getValidKingMoves(bking.getpos().getPosAsPair(),
                                             self.board)) == set(bkingmoves))
        self.assertTrue(
            set(
                self.logic.getValidKingMoves(wking2.getpos().getPosAsPair(),
                                             self.board)) == set(wking2moves))
コード例 #23
0
ファイル: test_chessLogic.py プロジェクト: surrsurus/YACS
 def test_getAnyMoves(self):
     wking = chess.Piece(1, "E", True, chess.PieceType.king, True)
     bking = chess.Piece(8, "E", True, chess.PieceType.king, False)
     wrook1 = chess.Piece(8, "A", True, chess.PieceType.rook, True)
     wrook2 = chess.Piece(7, "B", True, chess.PieceType.rook, True)
     self.board.addpiece(wking)
     self.board.addpiece(bking)
     self.board.addpiece(wrook1)
     self.board.addpiece(wrook2)
     self.assertFalse(self.logic.getAnyMoves(False, self.board))
     self.assertTrue(self.logic.getAnyMoves(True, self.board))
コード例 #24
0
ファイル: test_chessLogic.py プロジェクト: surrsurus/YACS
    def test_move(self):

        wking = chess.Piece(1, "E", True, chess.PieceType.king, True)
        bking = chess.Piece(8, "E", True, chess.PieceType.king, False)
        self.board.addpiece(wking)
        self.board.addpiece(bking)
        self.logic.move(wking, (6, 1), self.board)
        self.assertTrue(self.board.getpos(6, 1) is wking)
        self.assertTrue(
            self.board.getpos(5, 1).gettype() == chess.PieceType.empty)
        self.assertTrue(wking.getpos().getPosAsPair() == (6, 1))
コード例 #25
0
    def getInitBoard(self):

        b = chess.Board()
        b.clear()

        # Setup white pawns
        for white in range(8, 16):
            b.set_piece_at(white, chess.Piece(chess.PAWN, chess.WHITE))

        for black in range(48, 56):
            b.set_piece_at(black, chess.Piece(chess.PAWN, chess.BLACK))
        return b
コード例 #26
0
ファイル: test_chessLogic.py プロジェクト: surrsurus/YACS
 def test_checkState(self):
     wking = chess.Piece(1, "E", True, chess.PieceType.king, True)
     bking = chess.Piece(8, "E", True, chess.PieceType.king, False)
     brook = chess.Piece(3, "E", True, chess.PieceType.rook, False)
     bqueen = chess.Piece(2, "E", True, chess.PieceType.queen, False)
     wrook = chess.Piece(6, "E", True, chess.PieceType.rook, True)
     wqueen = chess.Piece(7, "E", True, chess.PieceType.queen, True)
     wqueen2 = chess.Piece(6, "E", True, chess.PieceType.queen, True)
     wbishop = chess.Piece(7, "E", True, chess.PieceType.bishop, True)
     bqueen2 = chess.Piece(3, "E", True, chess.PieceType.queen, False)
     bbishop = chess.Piece(2, "E", True, chess.PieceType.bishop, False)
     self.board.addpieces(wking, bking)
     self.assertTrue(
         self.logic.checkState(self.board, True) ==
         chess.ChessState.inProgress)
     self.board.setEmptyBoard()
     self.board.addpieces(wking, bking, bqueen)
     self.assertTrue(
         self.logic.checkState(self.board, True) ==
         chess.ChessState.whiteChecked)
     self.board.setEmptyBoard()
     self.board.addpieces(wking, bking, brook)
     self.assertTrue(
         self.logic.checkState(self.board, True) ==
         chess.ChessState.whiteChecked)
     self.board.setEmptyBoard()
     self.board.addpieces(wking, bking, brook, bqueen)
     self.assertTrue(
         self.logic.checkState(self.board, True) ==
         chess.ChessState.whiteCheckmated)
     self.board.setEmptyBoard()
     self.board.addpieces(wking, bking, wqueen)
     self.assertTrue(
         self.logic.checkState(self.board, False) ==
         chess.ChessState.blackChecked)
     self.board.setEmptyBoard()
     self.board.addpieces(wking, bking, wrook)
     self.assertTrue(
         self.logic.checkState(self.board, False) ==
         chess.ChessState.blackChecked)
     self.board.setEmptyBoard()
     self.board.addpieces(wking, bking, wrook, wqueen)
     self.assertTrue(
         self.logic.checkState(self.board, False) ==
         chess.ChessState.blackCheckmated)
     self.board.setEmptyBoard()
     self.board.addpieces(wking, bking, wbishop, wqueen2)
     self.assertTrue(
         self.logic.checkState(self.board, False) == chess.ChessState.draw)
     self.board.setEmptyBoard()
     self.board.addpieces(wking, bking, bbishop, bqueen2)
     self.assertTrue(
         self.logic.checkState(self.board, True) == chess.ChessState.draw)
コード例 #27
0
ファイル: test_hichess.py プロジェクト: H-a-y-k/hichesslib
    def testSetPieceAt(self):
        self.boardWidget.setPieceAt(chess.A4,
                                    chess.Piece(chess.PAWN, chess.WHITE))
        w = self.boardWidget.cellWidgetAtSquare(chess.A4)
        self.assertTrue(w.isPiece())
        self.assertFalse(w.isHighlighted())
        self.assertFalse(w.isMarked())
        self.assertTrue(w.isCheckable())
        self.assertEqual(w.objectName(), "cell_white_pawn")

        self.boardWidget = hichess.BoardWidget(sides=hichess.ONLY_WHITE_SIDE)
        self.boardWidget.setPieceAt(chess.A4,
                                    chess.Piece(chess.PAWN, chess.WHITE))
        w = self.boardWidget.cellWidgetAtSquare(chess.A4)

        self.assertTrue(w.isPiece())
        self.assertFalse(w.isHighlighted())
        self.assertFalse(w.isMarked())
        self.assertTrue(w.isCheckable())
        self.assertEqual(w.objectName(), "cell_white_pawn")

        self.boardWidget = hichess.BoardWidget(fen=chess.STARTING_FEN,
                                               sides=hichess.ONLY_BLACK_SIDE)
        self.boardWidget.setPieceAt(chess.A4,
                                    chess.Piece(chess.PAWN, chess.WHITE))
        w = self.boardWidget.cellWidgetAtSquare(chess.A4)

        self.assertTrue(w.isPiece())
        self.assertFalse(w.isHighlighted())
        self.assertFalse(w.isMarked())
        self.assertEqual(w.objectName(), "cell_white_pawn")

        self.boardWidget = hichess.BoardWidget(sides=hichess.ONLY_BLACK_SIDE)
        self.boardWidget.setPieceAt(chess.A4,
                                    chess.Piece(chess.PAWN, chess.BLACK))
        w = self.boardWidget.cellWidgetAtSquare(chess.A4)

        self.assertTrue(w.isPiece())
        self.assertFalse(w.isHighlighted())
        self.assertFalse(w.isMarked())
        self.assertTrue(w.isCheckable())
        self.assertEqual(w.objectName(), "cell_black_pawn")

        self.boardWidget = hichess.BoardWidget(sides=hichess.BOTH_SIDES)
        self.boardWidget.setPieceAt(chess.A4,
                                    chess.Piece(chess.PAWN, chess.BLACK))
        w = self.boardWidget.cellWidgetAtSquare(chess.A4)

        self.assertTrue(w.isPiece())
        self.assertFalse(w.isHighlighted())
        self.assertFalse(w.isMarked())
        self.assertEqual(w.objectName(), "cell_black_pawn")
コード例 #28
0
ファイル: test_chessLogic.py プロジェクト: surrsurus/YACS
    def test_getValidKnightMoves(self):
        wking = chess.Piece(1, "E", True, chess.PieceType.king, True)
        bking = chess.Piece(8, "E", True, chess.PieceType.king, False)
        bknight = chess.Piece(6, "D", True, chess.PieceType.knight, False)
        self.board.addpieces(wking, bking, bknight)
        bknightmoves = [((4, 6), (6, 7)), ((4, 6), (6, 5)), ((4, 6), (5, 4)),
                        ((4, 6), (2, 5)), ((4, 6), (2, 7)), ((4, 6), (3, 4)),
                        ((4, 6), (3, 8))]

        self.assertTrue(
            set(
                self.logic.getValidKnightMoves(bknight.getpos().getPosAsPair(
                ), self.board)) == set(bknightmoves))
コード例 #29
0
ファイル: helper.py プロジェクト: duelistone/cna
def load_new_game_from_piece_list(piece_list_string):
    words = piece_list_string.split()
    isWhiteMarker = lambda x: x.lower() in ["w:", "w", "white:", "white"]
    isBlackMarker = lambda x: x.lower() in ["b:", "b", "black:", "black"]

    # Determine turn
    turn = parse_side(words[-1])
    if turn == None:
        turn = chess.WHITE
    else:
        words = words[:-1]

    # Get pieces
    if len(words) < 1 and not isWhiteMarker(words[0]):
        return False
    i = 1
    whitePieces = []
    blackPieces = []
    currentList = whitePieces
    while i < len(words):
        if isBlackMarker(words[i]):
            currentList = blackPieces
            i += 1
            continue

        # Get square
        parsed_word = parse_piece_list_word(words[i])
        if parsed_word != None:
            currentList.extend(parsed_word)

        i += 1

    # Place pieces
    board = chess.Board(fen=None)
    board.turn = turn
    for pt, sq in whitePieces:
        p = chess.Piece(pt, chess.WHITE)
        board.set_piece_at(sq, p)
    for pt, sq in blackPieces:
        p = chess.Piece(pt, chess.BLACK)
        board.set_piece_at(sq, p)

    # Load game
    try:
        game = chess.pgn.Game()
        game.setup(board)
        load_new_game_from_game(game, player=turn)
    except:
        return False

    return True
コード例 #30
0
    def check_for_promotion(self, mv_frm, mv_to):
        'Checks for client-side promotion'
        white_queen = chess.Piece(piece_type=chess.QUEEN, color=chess.WHITE)
        black_queen = chess.Piece(piece_type=chess.QUEEN, color=chess.BLACK)

        if self.board.piece_at(mv_frm).piece_type == chess.PAWN:
            if chess.square_rank(mv_to) == 7:
                if self.board.piece_at(mv_frm).color == chess.WHITE:
                    promoted_binary = bin(self.pieces['Q'])[2:].zfill(4)
                    self.board.set_piece_at(square=mv_frm, piece=white_queen)
            elif chess.square_rank(mv_to) == 0:
                if self.board.piece_at(mv_frm).color == chess.BLACK:
                    promoted_binary = bin(self.pieces['q'])[2:].zfill(4)
                    self.board.set_piece_at(square=mv_frm, piece=black_queen)