示例#1
0
 def setUp(self):
     """
     setup the test with 1 piece on a board.
     :return: None.
     """
     self.piece = Piece()
     self.piece.board = Board(4, 4, [self.piece])
示例#2
0
class TestPieceNoBoard(unittest.TestCase):
    """
    Testing piece functionality without a board set to it.
    """
    def setUp(self):
        """
        setup the test with Piece class.
        :return: None.
        """
        self.piece = Piece()

    def test_row(self):
        """
        test the row getter.
        :return: None.
        """
        with self.assertRaises(InvalidSetupException):
            self.piece.row

    def test_set_row(self):
        """
        test the row setter.
        :return: None.
        """
        with self.assertRaises(InvalidSetupException):
            self.piece.row = 1

    def test_column(self):
        """
        test the column getter.
        :return: None.
        """
        with self.assertRaises(InvalidSetupException):
            self.piece.column

    def test_set_column(self):
        """
        test the column setter.
        :return: None.
        """
        with self.assertRaises(InvalidSetupException):
            self.piece.column = 1

    def test_set_position(self):
        """
        test the position setting functionality.
        :return: None.
        """
        with self.assertRaises(InvalidSetupException):
            self.piece.set_position(1, 1)

    def test_get_moves(self):
        """
        test getting the available moves of a piece.
        :return: None.
        """
        with self.assertRaises(InvalidSetupException):
            self.piece.get_moves()

    def test_update_column_status(self):
        """
        test updating the column `taken` value.
        :return: None.
        """
        self.assertEqual(self.piece.update_column_status(), None)

    def test_can_move(self):
        """
        test the can_move functionality of a piece.
        :return: None.
        """
        with self.assertRaises(InvalidSetupException):
            self.piece.can_move(1, 1, 1)

    def test_move(self):
        """
        test the move functionality of a piece.
        :return: None.
        """
        with self.assertRaises(InvalidSetupException):
            self.piece.move(1, 1)
    def test_invalid_move_down_right(self):
        self.piece.set_coordinates('e', 7)
        self.board[8]['e'] = Piece('red', 'e', 8)

        self.assertFalse(self.piece.valid_move('f', 9, self.board))
    def test_invalid_move_piece_in_the_way_4(self):
        piece = self.klass('black', 'c', 10)
        self.board[9]['b'] = Piece('black', 'b', 9)

        self.assertFalse(piece.valid_move('a', 8, self.board))
    def test_invalid_move_column_not_empty(self):
        self.board[2]['a'] = Piece('red', 'a', 2)

        self.assertFalse(self.piece.valid_move('a', 3, self.board))
    def test_valid_move_column_not_empty(self):
        self.board[4]['b'] = Piece('red', 'b', 4)
        self.board[5]['b'] = Piece('black', 'b', 5)

        self.assertTrue(self.piece.valid_move('b', 5, self.board))
    def test_invalid_move_column_not_empty(self):
        self.board[4]['b'] = Piece('red', 'b', 4)

        self.assertFalse(self.piece.valid_move('b', 5, self.board))
    def test_invalid_move_row_not_empty_2(self):
        self.board[3]['c'] = Piece('red', 'c', 3)
        self.board[3]['d'] = Piece('red', 'd', 3)
        self.board[3]['e'] = Piece('black', 'e', 3)

        self.assertFalse(self.piece.valid_move('e', 3, self.board))
示例#9
0
 def __init__(self, colour, coordinate, name):
     Piece.__init__(self, colour, coordinate, name)
     self.x = coordinate[0]
     self.y = coordinate[1]
示例#10
0
 def __init__(self, color, row, col):
     Piece.__init__(self, color, row, col, "p")
示例#11
0
 def __init__(self, color, type):
     self.firstMove = False
     Piece.__init__(self, color, type)
示例#12
0
def randomPieceGenerator():
    return [Piece.getRandomPiece() for _ in range(3)]
示例#13
0
 def create_piece(self, color, piece_type, position):
     piece = Piece(color, piece_type, self.display_surf)
     piece.set_position(position)
     return piece
示例#14
0
 def hips(self, colour, part = "970"):
 
     # Displacement from torso
     displacement = self.matrix * Vector(0, 32, 0)
     return Piece(colour, self.position + displacement, self.matrix, part,
                  self.group)
示例#15
0
 def backpack(self, colour, displacement = Vector(0, 0, 0), part = "3838"):
 
     # Displacement from torso
     displacement = self.matrix * displacement
     return Piece(colour, self.position + displacement, self.matrix, part,
                  self.group)
示例#16
0
class TestPiece(unittest.TestCase):
    """
    Testing a piece functionality with a board set to it.
    """
    def setUp(self):
        """
        setup the test with 1 piece on a board.
        :return: None.
        """
        self.piece = Piece()
        self.piece.board = Board(4, 4, [self.piece])

    def test_row(self):
        """
        test the row getter.
        :return: None.
        """
        self.assertEqual(self.piece.row, 0)

    def test_set_row(self):
        """
        test the row setter.
        :return: None.
        """
        self.setUp()
        self.piece.row = 2
        self.assertEqual(self.piece.row, 2)

        with self.assertRaises(InvalidMoveException):
            self.piece.row = -1

        with self.assertRaises(InvalidMoveException):
            self.piece.row = 4

    def test_column(self):
        """
        test the column getter.
        :return: None.
        """
        self.assertEqual(self.piece.column, 0)

    def test_set_column(self):
        """
        test the column setter.
        :return: None.
        """
        self.setUp()
        self.piece.column = 2
        self.assertEqual(self.piece.column, 2)

        with self.assertRaises(InvalidMoveException):
            self.piece.column = -1

        with self.assertRaises(InvalidMoveException):
            self.piece.column = 4

    def test_set_position(self):
        """
        test the position setting functionality.
        :return: None.
        """
        self.setUp()
        self.piece.set_position(2, 2)

        self.assertEqual(self.piece.row, 2)
        self.assertEqual(self.piece.column, 2)

        with self.assertRaises(InvalidMoveException):
            self.piece.set_position(-1, 2)

        with self.assertRaises(InvalidMoveException):
            self.piece.set_position(2, -1)

        with self.assertRaises(InvalidMoveException):
            self.piece.set_position(-1, -1)

        with self.assertRaises(InvalidMoveException):
            self.piece.set_position(4, 2)

        with self.assertRaises(InvalidMoveException):
            self.piece.set_position(2, 4)

        with self.assertRaises(InvalidMoveException):
            self.piece.set_position(4, 4)

    def test_get_moves(self):
        """
        test getting the available moves of a piece.
        :return: None.
        """
        self.assertEqual(self.piece.get_moves(), [])

    def test_update_column_status(self):
        """
        test updating the column `taken` value.
        :return: None.
        """
        self.setUp()
        self.piece.update_column_status()

        self.assertEqual(self.piece.board[0, 1].taken, False)

    def test_can_move(self):
        """
        test the can_move functionality of a piece.
        :return: None.
        """
        self.assertEqual(self.piece.can_move(0, 0, 1), True)

    def test_move(self):
        """
        test the move functionality of a piece.
        :return: None.
        """
        self.setUp()
        self.piece.move(0, 1)

        self.assertEqual(self.piece.row, 0)
        self.assertEqual(self.piece.column, 1)

        self.assertEqual(self.piece.board[0, 1].piece, self.piece)
示例#17
0
 def torso(self, colour, part = "973"):
 
     return Piece(colour, self.position, self.matrix, part, self.group)
示例#18
0
                    count += 1
                    print(peer_tag, f"Did not connect because {e}")
                    # raise

                thread_obj.join()
            except Exception as e:
                pass
            i += 1

        #time.sleep(5 * n_l)
        l1 = this_client._splitPieces()
        q = rarestFirstQueue()

        for i in range(this_client.num_of_pieces):
            if i == this_client.num_of_pieces - 1:
                p1 = Piece(l1[i][0], i, this_client.last_piece_len, bytes())
            else:
                p1 = Piece(l1[i][0], i, this_client.piece_length, bytes())
            for peer in this_client.global_piece_list:
                m = len(this_client.global_piece_list[peer])
                if i >= m:
                    continue
                if this_client.global_piece_list[peer][i] == '1':
                    p1.occurrence += 1
            q.insertPiece(p1)
        print(len(q.piecesQueue))
        time.sleep(2)
        for p in q.piecesQueue:
            peer_list = []
            for peer in this_client.global_piece_list:
                if this_client.global_piece_list[peer][p.index] == '1':
    def test_valid_move_row_not_empty(self):
        self.board[3]['c'] = Piece('red', 'c', 3)
        self.board[3]['d'] = Piece('black', 'd', 3)

        self.assertTrue(self.piece.valid_move('d', 3, self.board))
示例#20
0
def main(white_king, black_king):
    '''
      Representation of the chess board in an array
      Each number in the array represents a piece:

           0 - Empty Space
           1 - Pawn
           2 - Knight
           3 - Bishop
           4 - Rook
           5 - Queen
           6 - King

      Positive values indicate white pieces
      Negative values indicate black pieces

    '''
    # Chess board
    board = [[-4, -2, -3, -5, -6, -3, -2, -4],
             [-1, -1, -1, -1, -1, -1, -1, -1], [0, 0, 0, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1],
             [4, 2, 3, 5, 6, 3, 2, 4]]

    # Important variables
    running = True
    isClicked = False

    curr = 0
    color = 1
    valid = []
    cm = False
    counter = 1
    curr_piece = 10
    canCastle = False
    curr_x, curr_y = 10, 10

    # Setting a gameloop
    while running:

        # Stuff that will run in the background
        createBoard(board, white_king, black_king, valid)
        piece = pieceUnderMouse(board)
        if curr_piece != 0:
            color = curr_piece // abs(curr_piece)
        x, y = getMousePos()

        for event in pygame.event.get():

            # Exits program
            if event.type == pygame.QUIT:
                running = False

            # Checking if the mouse has been pressed
            if event.type == pygame.MOUSEBUTTONDOWN:
                if piece != 0 and not isClicked:

                    # Set the clicked piece as the current piece
                    curr_piece = piece
                    curr_x, curr_y = x, y
                    isClicked = True

            # Checking if the mouse has been released
            if event.type == pygame.MOUSEBUTTONUP:

                if isClicked:
                    # Animation stuff
                    board[curr_x][curr_y] = curr_piece
                    lastPiece = board[x][y]
                    capture = board[x][y]
                    # Checks if the desired move is valid
                    if [curr_x, curr_y, x, y] in valid:
                        # Update the king's positions
                        if abs(curr_piece) == 6:
                            if color > 0:
                                white_king = [x, y]

                            else:
                                black_king = [x, y]

                        Piece.placePiece(board, curr_x, curr_y, x, y, 0)
                        inCheck = check(board, white_king, black_king)
                        counter *= -1

                        if inCheck != 0:
                            """
                            This part checks if there is a checkmate or not

                            It looks one move into the future to determine if 
                            a side has any possible moves that can be played
                            """
                            if inCheck > 0:
                                val = validWhite(board)

                            else:
                                val = validBlack(board)

                            count = 0

                            # Looping through all the possible moves
                            for i in val:

                                x1, y1, x2, y2 = i
                                last = board[x2][y2]
                                """
                                Here, we simulate all the possible moves that a side can
                                play by taking its "validMove" list and placing all of the 
                                moves on the board, one by one.

                                We then check if the king is in check if that move is played
                                and then reset the move so as to not disturb the game   
                                """
                                Piece.placePiece(board, x1, y1, x2, y2, 0)
                                if abs(board[x2][y2]) == 6:
                                    if color < 0:
                                        white_king = [x2, y2]

                                    elif color > 0:
                                        black_king = [x2, y2]

                                inCheck = check(board, white_king, black_king)
                                if inCheck != 0:
                                    count += 1

                                # Reseting the moves
                                Piece.placePiece(board, x2, y2, x1, y1, last)
                                if abs(board[x1][y1]) == 6:
                                    if color < 0:
                                        white_king = [x1, y1]

                                    elif color > 0:
                                        black_king = [x1, y1]

                            # Checking for checkmate
                            if count == len(val):
                                cm = True

                            else:
                                cm = False

                        # If a side puts itself in check
                        if color == inCheck:
                            Piece.placePiece(board, x, y, curr_x, curr_y,
                                             lastPiece)
                            counter *= -1

                        elif color != inCheck:
                            if cm:
                                sys.exit()

                            if capture == 0:
                                pygame.mixer.Sound.play(move_sound)

                            else:
                                pygame.mixer.Sound.play(capture_sound)
                            curr_piece = board[x][y]

                isClicked = False

        # If the mouse button is clicked
        if isClicked:
            board[curr_x][curr_y] = curr_piece
            curr = createPiece(board, curr_piece, curr_x, curr_y)
            valid = curr.validMoves()
            board[curr_x][curr_y] = 0

            # Using drag n' drop functionality to move the piece
            movePiece(curr_piece)

        else:
            # Pawn Promotion functionality
            if abs(curr_piece) == 1 and curr_piece == piece:
                pr = 5
                if canPromote(x):
                    board[x][y] = pr * color
                    curr_piece = board[x][y]

        pygame.display.update()
    def test_invalid_move_column_not_empty_2(self):
        self.board[4]['b'] = Piece('red', 'b', 4)
        self.board[5]['b'] = Piece('red', 'b', 5)
        self.board[6]['b'] = Piece('black', 'b', 6)

        self.assertFalse(self.piece.valid_move('b', 6, self.board))
示例#22
0
    def square_attacked_by(self, piece, attacker, board=None):
        """ Returns True if square is attacked by inputted piece """
        #print(f"Entered square_attacked_by({piece._id} on {Board.square_name((piece.rank, piece.file))}, attacked by {attacker}?)")
        if not board:
            board = self.board

        file = piece.file
        rank = piece.rank
        attacker = Piece(attacker)

        if attacker.name == PAWN:
            if attacker.colour == WHITE:
                movements = [SW, SE]
            else:
                movements = [NW, NE]
        else:
            movements = attacker.movements

        for movement in movements:
            #print(movement)
            distance = 0
            possible_file = file
            possible_rank = rank

            while distance != attacker.max_distance:
                #print(distance)
                #board.print_board()
                possible_file += movement[1]
                possible_rank += movement[0]

                # If passed edge of board
                if possible_file < 0 or possible_file > 7 or \
                        possible_rank < 0 or possible_rank > 7:
                    #print("off edge of board")
                    break
                #print(board.BOARD[possible_rank][possible_file])
                # If square is occupied
                if board.BOARD[possible_rank][possible_file] is not EMPTY:
                    # If own piece in the way
                    if board.BOARD[possible_rank][
                            possible_file].colour == piece.colour:
                        #print(f"own piece in way: {board.BOARD[possible_rank][possible_file]}")
                        break
                    # If opposition piece in the way
                    else:
                        # If is attacker we are searching for
                        if board.BOARD[possible_rank][
                                possible_file].name == attacker.name:
                            #print(f"Attacker found: {attacker.name}")
                            return True
                        # If attacker is Rook or Bishop, we also search for a Queen
                        elif attacker.name is ROOK or attacker.name is BISHOP:
                            if board.BOARD[possible_rank][
                                    possible_file].name is QUEEN:
                                #print("Queen found while searching for R or B")
                                return True
                        # If is a different piece
                        else:
                            #print("different piece found")
                            break

                # Square not occupied
                distance += 1
    def test_invalid_move_row_not_empty(self):
        self.board[1]['b'] = Piece('red', 'b', 1)

        self.assertFalse(self.piece.valid_move('d', 1, self.board))
示例#24
0
    def get_possible_squares(self, piece=None, square=None):
        """ Returns a list of possible squares availale to move to.
            Input needed: One of: piece or square, or both
            piece can be one of: string - 'K'
                                 Piece - Piece('K')
            square can be one of: string - 'E4'
                                  array coordinates - [3,5]
            Usage:  get_possible_squares(piece='K', square='E4')
                    get_possible_squares(square='E4')
                    get_possible_squares(piece=<Piece>)  // Piece with .file and .rank
                    get_possible_squares(square=<Piece>) // Piece with .file and .rank
            """
        #print(f"piece:{piece}, square:{square}")

        # if both piece and square are None
        if not piece and not square:
            return None

        # piece can be string or Piece object or empty
        if type(piece) is str:
            piece_obj = Piece(piece)
        elif type(piece) is Piece:
            piece_obj = piece
        else:
            piece_obj = self.board.BOARD[RANK[square[1]]][FILE[square[0]]]

        # square can be empty, string or array coordinates
        if not square:
            file = piece_obj.file
            rank = piece_obj.rank
        elif type(square) is str:
            file = FILE[square[0]]
            rank = RANK[square[1]]
        else:
            file = square[1]
            rank = square[0]

        # If no piece enterred and square is EMPTY:
        if not piece and self.board.BOARD[rank][file] is EMPTY:
            return None

        # If piece is newly created without file and rank
        if not piece_obj.file:
            piece_obj.file = file
            piece_obj.rank = rank

        # If not active colour
        if piece_obj.colour is not self.whose_move():
            return None

        #print(f"get_possible_squares({piece_obj._id} on {Board.square_name((piece_obj.rank, piece_obj.file))})")

        # Loop through directions of piece movements
        possible_squares = []
        for movement in piece_obj.movements:
            distance = 0
            possible_file = file
            possible_rank = rank
            max_distance = piece_obj.max_distance

            # Loop until range of piece is exceeded
            while distance != max_distance:

                # If pawn on starting position
                if piece_obj.name is PAWN:
                    if piece_obj.colour == WHITE and rank == 1 or \
                       piece_obj.colour == BLACK and rank == 6:
                        max_distance = 2

                # copy board for testing in_check conditions
                possible_board = Board(self.board.BOARD)
                possible_file += movement[1]
                possible_rank += movement[0]

                # If passed edge of board
                if possible_file < 0 or possible_file > 7 or \
                   possible_rank < 0 or possible_rank > 7:
                    #print("Can't move: off edge of board")
                    break

                possible_square = possible_board.BOARD[possible_rank][
                    possible_file]

                # If square is occupied
                if possible_square is not EMPTY:
                    # If own piece in the way
                    if possible_square.colour == piece_obj.colour:
                        break
                    # If opposition piece in the way
                    else:
                        # If moving piece is a pawn
                        if piece_obj.name == PAWN:
                            # If forward pawn move
                            if movement in piece_obj.normal_movements:
                                break

                        # Test for putting self in check
                        possible_board.remove_piece((rank, file))
                        possible_board.place_piece(square=possible_square,
                                                   piece=piece_obj._id)

                        if self.in_check(board=possible_board,
                                         colour=piece_obj.colour):
                            break
                        # Can capture piece
                        else:
                            possible_squares.append(
                                [possible_rank, possible_file])
                            break

                # Square not occupied
                else:
                    # If pawn
                    if piece_obj.name == PAWN:
                        # Can't move diagonal if not capturing unless en-passant
                        if movement in piece_obj.capture_movements:
                            if not self.en_passant_sq:
                                break
                            elif self.en_passant_sq and \
                                    Board.square_name((possible_rank, possible_file)) != self.en_passant_sq.upper():
                                break

                        # If not on 2nd rank(WHITE) or 7th rank(BLACK): Can't move two squares
                        if piece_obj.colour == WHITE and rank != 1 and distance == 1 or \
                           piece_obj.colour == BLACK and rank != 6 and distance == 1:
                            break

                    # If Castling King
                    if piece_obj.name is KING and piece_obj.colour is WHITE:
                        if movement is E and self.castling_rights[0]:
                            if max_distance == 1:
                                max_distance = 2
                        if movement is W and self.castling_rights[1]:
                            if max_distance == 1:
                                max_distance = 2
                    elif piece_obj.name is KING and piece_obj.colour is BLACK:
                        if movement is E and self.castling_rights[2]:
                            if max_distance == 1:
                                max_distance = 2
                        if movement is W and self.castling_rights[3]:
                            if max_distance == 1:
                                max_distance = 2

                    # Test for putting self in check
                    possible_board.remove_piece((rank, file))
                    possible_board.place_piece(square=(possible_rank,
                                                       possible_file),
                                               piece=piece_obj._id)
                    if not self.in_check(board=possible_board,
                                         colour=piece_obj.colour):
                        possible_squares.append([possible_rank, possible_file])
                    else:
                        # Can't castle through a check
                        if piece_obj.name is KING:
                            max_distance = 1

                distance += 1
        if not possible_squares:
            return None
        else:
            return possible_squares
    def test_invalid_move_piece_in_the_way_2(self):
        self.board[2]['d'] = Piece('red', 'd', 2)

        self.assertFalse(self.piece.valid_move('e', 3, self.board))
示例#26
0
 def __init__(self, pos, color):
     Piece.__init__(self, pos, color)
     self.p_type = 'pawn'
    def test_valid_move_to_see_other_general_red(self):
        self.board[10]['d'] = self.klass('black', 'd', 9)
        self.board[9]['d'] = Piece('black', 'd', 9)

        self.assertTrue(self.piece.valid_move('d', 1, self.board))
示例#28
0
文件: knight.py 项目: jackhamby/chess
 def __init__(self, tile, team):
     Piece.__init__(self, tile, team)
    def test_invalid_move_up_left(self):
        self.piece.set_coordinates('e', 7)
        self.board[6]['e'] = Piece('red', 'e', 6)

        self.assertFalse(self.piece.valid_move('d', 5, self.board))
示例#30
0
 def __init__(self, tile, player):
     Piece.__init__(self, tile, player)
     self.is_first_move = True
示例#31
0
 def setUp(self):
     """
     setup the test with Piece class.
     :return: None.
     """
     self.piece = Piece()
示例#32
0
 def __init__(self, color, type):
     Piece.__init__(self, color, type)
示例#33
0
 def test_piece_constructor_abstract(self):
     """Check an abstract piece cannot be created."""
     self.assertRaises(TypeError, Piece())
示例#34
0
文件: chess.py 项目: tdrmk/pychess
 def _possible_moves_(self, piece: Piece) -> List[Move]:
     # returns valid moves the piece of the player [current turn] can make
     return [
         move for move in piece.possible_moves()
         if self._can_make_move_(move)
     ]