def __init__(self):

        self.pieces = [
            pawn.Pawn("Black"),
            rook.Rook("Black"),
            knight.Knight("Black"),
            bishop.Bishop("Black"),
            queen.Queen("Black"),
            king.King("Black"),
            pawn.Pawn("White"),
            rook.Rook("White"),
            knight.Knight("White"),
            bishop.Bishop("White"),
            queen.Queen("White"),
            king.King("White")
        ]

        self.starting_board = [
            self.__build_rank_with_king(0, 4),
            self.__build_rank_without_king(0, 4),
            ["-", "-", "-", "-", "-", "-", "-", "-"],
            ["-", "-", "-", "-", "-", "-", "-", "-"],
            ["-", "-", "-", "-", "-", "-", "-", "-"],
            ["-", "-", "-", "-", "-", "-", "-", "-"],
            self.__build_rank_without_king(6, 10),
            self.__build_rank_with_king(6, 10)
        ]
Beispiel #2
0
def get_piece(symbol, rank, file, has_moved=False):
    import pawn, knight, bishop, rook, queen, king

    if symbol == ' ':
        return None
    elif symbol > '♙':
        colour = -1
        symbol = chr(ord(symbol) - ord('♚') + ord('♔'))
    else:
        colour = 1

    if symbol == '♔':
        return king.King(colour, rank, file, has_moved)
    elif symbol == '♕':
        return queen.Queen(colour, rank, file)
    elif symbol == '♖':
        return rook.Rook(colour, rank, file, has_moved)
    elif symbol == '♗':
        return bishop.Bishop(colour, rank, file)
    elif symbol == '♘':
        return knight.Knight(colour, rank, file)
    elif symbol == '♙':
        return pawn.Pawn(colour, rank, file)
    else:
        return None
Beispiel #3
0
 def __init__(self):
     self.playBoard = dict()
     self.rows = 7
     self.columns = 8
     for i in range(
             97, 98 + self.rows
     ):  # letters for columns, with 'a' at the top and 'i' at the bottom
         if (i == 97 or i == 98):
             colour = 'B'
         elif (i == 96 + self.rows or i == 97 + self.rows):
             colour = 'W'
         for j in range(
                 1, self.columns + 1
         ):  # numbers for rows, with 1 at the left and 8 at the right
             index = str(chr(i)) + str(j)
             if (i == 97 or i
                     == 97 + self.rows):  # essentially a factory method
                 if (j == 1 or j == 8):
                     self.playBoard[index] = rook.Rook(0, True, colour, j)
                 elif (j == 2 or j == 7):
                     self.playBoard[index] = knight.Knight(
                         0, True, colour, j)
                 elif (j == 3 or j == 6):
                     self.playBoard[index] = bishop.Bishop(
                         0, True, colour, j)
                 elif (j == 4):
                     self.playBoard[index] = queen.Queen(0, True, colour, j)
                 else:
                     self.playBoard[index] = king.King(0, True, colour, j)
             elif (i == 98 or i == 96 + self.rows):
                 self.playBoard[index] = pawn.Pawn(0, True, colour, j)
             else:
                 self.playBoard[index] = '0'
 def __init__(self):
     self.starting_board = [[
         rook.Rook("Black"),
         knight.Knight("Black"),
         bishop.Bishop("Black"),
         queen.Queen("Black"),
         king.King("Black"),
         bishop.Bishop("Black"),
         knight.Knight("Black"),
         rook.Rook("Black")
     ],
                            [
                                pawn.Pawn("Black"),
                                pawn.Pawn("Black"),
                                pawn.Pawn("Black"),
                                pawn.Pawn("Black"),
                                pawn.Pawn("Black"),
                                pawn.Pawn("Black"),
                                pawn.Pawn("Black"),
                                pawn.Pawn("Black")
                            ], ["-", "-", "-", "-", "-", "-", "-", "-"],
                            ["-", "-", "-", "-", "-", "-", "-", "-"],
                            ["-", "-", "-", "-", "-", "-", "-", "-"],
                            ["-", "-", "-", "-", "-", "-", "-", "-"],
                            [
                                pawn.Pawn("White"),
                                pawn.Pawn("White"),
                                pawn.Pawn("White"),
                                pawn.Pawn("White"),
                                pawn.Pawn("White"),
                                pawn.Pawn("White"),
                                pawn.Pawn("White"),
                                pawn.Pawn("White")
                            ],
                            [
                                rook.Rook("White"),
                                knight.Knight("White"),
                                bishop.Bishop("White"),
                                queen.Queen("White"),
                                king.King("White"),
                                bishop.Bishop("White"),
                                knight.Knight("White"),
                                rook.Rook("White")
                            ]]
Beispiel #5
0
    def __init__(self, player):

        Level.__init__(self, player)

        level2 = [[40, 80, 300, 120], [40, 80, 700, 220], [40, 80, 400, 320],
                  [40, 80, 500, 420], [40, 80, 200, 520], [40, 50, 800, 620],
                  [40, 70, 200, 40], [40, 50, 650, 40], [40, 50, 650, 140],
                  [40, 50, 100, 320], [40, 50, 100, 450]]

        level = [[1000, 1, 0, 0], [900, 1, 100, 699], [99, 30, 100, 40],
                 [39, 30, 241, 40], [20, 39, 79, 0], [20, 39, 281, 0],
                 [180, 30, 600, 40], [299, 30, 0, 120], [200, 30, 341, 120],
                 [299, 30, 400, 220], [259, 30, 741, 220], [399, 30, 0, 320],
                 [300, 30, 441, 320], [199, 30, 300, 420], [459, 30, 541, 420],
                 [199, 30, 0, 520], [600, 30, 241, 520], [99, 30, 700, 620],
                 [159, 30, 841, 620]]

        for plat in level:
            block = platform.Platform(plat[0], plat[1])

            block.rect.x = plat[2]
            block.rect.y = plat[3]

            block.player = self.player
            self.platform_list.add(block)

        for lad in level2:
            block = ladder.Ladder(lad[0], lad[1])

            block.rect.x = lad[2]
            block.rect.y = lad[3]

            self.ladder_list.add(block)

        for i in range(50):

            coin = coins.Coins(20, 20)

            coin.rect.x = random.randrange(1000)
            coin.rect.y = random.randrange(700)

            self.coins_list.add(coin)

            for j in self.platform_list:

                plat_coin_hit_list = pygame.sprite.spritecollide(
                    j, self.coins_list, True)

        q = queen.Queen(30, 30)

        q.rect.x = random.randrange(100, 280)
        q.rect.y = 9

        self.queen_list.add(q)
Beispiel #6
0
 def move(self, move):
     import piece, queen, rook, bishop, knight
     if len(move) > 2:
         switch = {
             'Q': queen.Queen(self.colour, move[0], move[1]),
             'R': rook.Rook(self.colour, move[0], move[1], True),
             'B': bishop.Bishop(self.colour, move[0], move[1]),
             'N': knight.Knight(self.colour, move[0], move[1])
         }
         return switch.get(move[2], None)
     else:
         return piece.get_piece(self.symbol, move[0], move[1])
Beispiel #7
0
    def set_standard_board(self):
        """
        Sets the Board with the standard Chess Opening
        """
        white = 'white'
        black = 'black'

        # Pawn
        for i in range(8):
            self.set_piece(PAWN.Pawn(white), self.alphabet[i], 2)
        for i in range(8):
            self.set_piece(PAWN.Pawn(black), self.alphabet[i], 7)

        # Rooks
        self.set_piece(ROOK.Rook(white), 'A', 1)
        self.set_piece(ROOK.Rook(white), 'H', 1)
        self.set_piece(ROOK.Rook(black), 'A', 8)
        self.set_piece(ROOK.Rook(black), 'H', 8)

        # Knights
        self.set_piece(KNIGHT.Knight(white), 'B', 1)
        self.set_piece(KNIGHT.Knight(white), 'G', 1)
        self.set_piece(KNIGHT.Knight(black), 'B', 8)
        self.set_piece(KNIGHT.Knight(black), 'G', 8)

        # Bishops
        self.set_piece(BISHOP.Bishop(white), 'C', 1)
        self.set_piece(BISHOP.Bishop(white), 'F', 1)
        self.set_piece(BISHOP.Bishop(black), 'C', 8)
        self.set_piece(BISHOP.Bishop(black), 'F', 8)

        # Queens
        self.set_piece(QUEEN.Queen(white), 'D', 1)
        self.set_piece(QUEEN.Queen(black), 'D', 8)

        # Kings
        self.set_piece(KING.King(white), 'E', 1)
        self.set_piece(KING.King(black), 'E', 8)
Beispiel #8
0
    def execute_valid_move(self, start_coordinate, end_coordinate):
        """
        should not be called unless move is 100% verified to be valid
        :param start_coordinate:
        :param end_coordinate:
        :return:
        """
        row1 = start_coordinate[0]
        col1 = start_coordinate[1]
        row2 = end_coordinate[0]
        col2 = end_coordinate[1]
        color = self.grid[row1][col1].piece.color

        previous_grid = self._copy_grid()

        # Grab Squares
        start_square = self.grid[row1][col1]
        end_square = self.grid[row2][col2]

        if end_coordinate[-1] == 'is_queening':
            self.set_piece(QUEEN.Queen(color), row2, col2, debug=True)
        else:
            self.set_piece(start_square.piece, row2, col2, debug=True)
        end_square.piece.update_turn_last_moved(self.turn_count)
        if end_coordinate[-1] == 'is_en_passant':
            self.set_piece(PIECE.Piece(), row1, col2, debug=True)
        start_square.set_piece(PIECE.Piece())

        if end_coordinate[-1] == 'is_castling':
            if col2 - col1 > 0: # King Side Castle
                self.set_piece(self.grid[row2][col2 + 1].piece, row2, col2 - 1, debug=True)
                self.grid[row2][col2 - 1].piece.update_turn_last_moved(self.turn_count)
                self.set_piece(PIECE.Piece(), row2, col2 + 1, debug=True)
            else: # Queen Side Castle
                self.set_piece(self.grid[row2][col2 - 2].piece, row2, col2 + 1, debug=True)
                self.grid[row2][col2 + 1].piece.update_turn_last_moved(self.turn_count)
                self.set_piece(PIECE.Piece(), row2, col2 - 2, debug=True)

        # Add the previous position to history
        self.history.append(previous_grid)

        # Update Turn Variables
        self.turn_count += 1
        self.turn_last_capture += 1
Beispiel #9
0
import pytest
import game
from piece import Piece
import queen

test_queen_b = queen.Queen("Black")
test_queen_w = queen.Queen("White")


@pytest.fixture(autouse=True)
def run_before_tests():
    test_game = game.Game('p1', 'p2')
    return test_game


class TestQueenProperties:
    def test_queen_name(self):
        assert test_queen_b.name == "Queen"
        assert test_queen_w.name == "Queen"

    def test_queen_symbol(self):
        assert test_queen_b.symbol == '♛'
        assert test_queen_w.symbol == '♕'


class TestLegalMoves:
    def test_queen_can_move_diagonally(self):
        assert test_queen_b.invalid_move_types(5, 5, 4, 4) == False

    def test_queen_can_move_laterally(self):
        assert test_queen_b.invalid_move_types(5, 5, 5, 6) == False
Beispiel #10
0
black = 'black'
b_true = BOARD.Board()
b_test = BOARD.Board()

# Set Boards
#   True Board
b_true.set_piece(PAWN.Pawn(black), 'C', 7)
b_true.set_piece(PAWN.Pawn(black), 'F', 7)
b_true.set_piece(PAWN.Pawn(black), 'H', 7)
b_true.set_piece(PAWN.Pawn(white), 'D', 6)
b_true.set_piece(PAWN.Pawn(white), 'G', 6)
b_true.set_piece(PAWN.Pawn(black), 'A', 5)
b_true.set_piece(PAWN.Pawn(white), 'H', 4)
b_true.set_piece(PAWN.Pawn(black), 'A', 3)
b_true.set_piece(PAWN.Pawn(white), 'F', 3)
b_true.set_piece(QUEEN.Queen(black), 'B', 1)

#   Test Board
b_test.has_king = False
b_test.set_piece(PAWN.Pawn(white), 'A', 2)
b_test.set_piece(PAWN.Pawn(white), 'B', 2)
b_test.set_piece(PAWN.Pawn(white), 'C', 2)
b_test.set_piece(PAWN.Pawn(white), 'D', 2)
b_test.set_piece(PAWN.Pawn(white), 'E', 2)
b_test.set_piece(PAWN.Pawn(white), 'F', 2)
b_test.set_piece(PAWN.Pawn(white), 'G', 2)
b_test.set_piece(PAWN.Pawn(white), 'H', 2)
b_test.set_piece(PAWN.Pawn(black), 'A', 7)
b_test.set_piece(PAWN.Pawn(black), 'B', 7)
b_test.set_piece(PAWN.Pawn(black), 'C', 7)
b_test.set_piece(PAWN.Pawn(black), 'D', 7)
Beispiel #11
0
    def setupBoard(self, board):
        white_king = None
        black_king = None

        # Get all squares of interest
        eligible_squares = [
            square for square in self.squares if square.rank == 1
            or square.rank == 2 or square.rank == 7 or square.rank == 8
        ]

        for square in eligible_squares:

            # Set the colour
            if square.rank == 1 or square.rank == 2:
                colour = 'white'
            else:
                colour = 'black'

            # Determine which piece to be created based on rank and column
            if square.rank == 2 or square.rank == 7:
                piece = pawn.Pawn(square, colour)

            else:
                if square.file == 'A' or square.file == 'H':
                    piece = rook.Rook(square, colour)

                elif square.file == 'B' or square.file == 'G':
                    piece = knight.Knight(square, colour)

                elif square.file == 'C' or square.file == 'F':
                    piece = bishop.Bishop(square, colour)

                elif square.file == 'D':
                    piece = queen.Queen(square, colour)

                else:
                    piece = king.King(square, colour)
                    if square.id == 'E1':
                        white_king = piece
                    else:
                        black_king = piece

            self.pieces.add(piece)

            # While we are here, set square.isOccupied to be True, since when square objects are created, these are set to be False.
            square.isOccupied = True
            square.occupied_colour = colour

            self.screen.blit(piece.image, piece.rect)
            pg.display.update()

        # Add pieces to appropriate groups
        for piece in self.pieces:
            if piece.colour == 'white':
                self.white_pieces.add(piece)
            else:
                self.black_pieces.add(piece)

        # We need to get the legal moves for each piece on startup, since if a king is selected to move
        # we need to check that no opponent's piece is controlling a given surrounding square of that king.
        # But since knights can move before every other piece has been moved, we account for that by getting every piece's available moves right away.
        for piece in self.pieces:

            # Get the legal moves for the current piece.
            if piece.name == 'King':
                piece.get_legal_moves(self.squares, self.pieces, None, None)
                if piece.colour == 'white':
                    white_king = piece
                else:
                    black_king = piece
            else:
                piece.get_legal_moves(self.squares, self.pieces, None, None)

            # Update pawn attribute.
            if piece.name == 'Pawn':
                piece.first_move = True

            # Now get each piece's king and its opponent's king.
            for k in [piece for piece in self.pieces if piece.name == 'King']:
                if piece.colour == k.colour:
                    piece.our_king = k
                else:
                    piece.opponents_king = k

        return white_king, black_king
Beispiel #12
0
# Imports
import sys
sys.path.append('../Pieces')
import queen as QUEEN
sys.path.append('../BoardStuff')
import board as BOARD

# Variables
white = 'white'
black = 'black'
b_true = BOARD.Board()
b_test = BOARD.Board()

# Set Boards
#   True Board
b_true.set_piece(QUEEN.Queen(white), 'F', 7)

#   Test Board
b_test.has_king = False
b_test.set_piece(QUEEN.Queen(white), 'E', 5)
b_test.set_piece(QUEEN.Queen(black), 'A', 2)
b_test.set_piece(QUEEN.Queen(black), 'H', 7)

# Test
true_values = []
test_values = []

test_values.append(b_test.move_piece(white, 'E', 5, 'B', 8))  # Move 1
true_values.append(True)
test_values.append(b_test.move_piece(white, 'B', 8, 'A', 8))  # Move 2
true_values.append(True)
Beispiel #13
0
    def run(self):

        team_alternator = self.alternate_teams()
        selected_piece = None
        move_made = False
        turn = self.main_player.turn

        our_pieces = [piece for piece in self.main_player.board.pieces if piece.colour == self.main_player.colour]
        opponents_pieces = [piece for piece in self.main_player.board.pieces if piece not in our_pieces]
        our_king = [piece for piece in our_pieces if piece.name == 'King' and piece.colour == self.main_player.colour][0]
        opponents_king = [piece for piece in self.main_player.board.pieces if piece.name == 'King' and piece.colour != self.main_player.colour][0]

        done = False
        while not done:

            mate_check = None
            chess_move = None
            opponents_move = None
            
            # Get our piece sets, and our kings.
            our_pieces = [piece for piece in self.main_player.board.pieces if piece.colour == self.main_player.colour]
            opponents_pieces = [piece for piece in self.main_player.board.pieces if piece not in our_pieces]
            our_king = [piece for piece in our_pieces if piece.name == 'King' and piece.colour == self.main_player.colour][0]
            opponents_king = [piece for piece in self.main_player.board.pieces if piece.name == 'King' and piece.colour != self.main_player.colour][0]
    
            # Get events
            for event in pg.event.get():
                

                # Keep the board live until the game window is exited
                if event.type == pg.QUIT: 
                    done = True
                
                move_to_square = None
                promoted_to_piece = None
                if self.main_player.colour == turn:
                    # Get the current mouse event

                    # Stop the main player's timer.
                    if self.main_player.timer.timer_started:
                        self.main_player.timer.passed_time = pg.time.get_ticks() - self.main_player.timer.start_time
                    
                    time_before = self.main_player.timer.time_before_move
                    time_used = self.main_player.timer.passed_time/1000
                    blittable = self.main_player.timer.font.render(str(format(time_before - time_used, '.2f')), True, (0, 255, 0))

                    # Update the time displayed and the variable keeping track of how much time we have left.
                    pg.draw.rect(self.main_player.board.screen, (0, 0, 0), (self.main_player.timer.position[0], self.main_player.timer.position[1], 100, 20))
                    self.main_player.board.screen.blit(blittable, self.main_player.timer.position)
                    self.main_player.timer.time_before_move = time_before - time_used
                   
                    if event.type == pg.MOUSEBUTTONDOWN:
                        
                        # Get current mouse position and check pieces against that position
                        mouse_down_position = pg.mouse.get_pos()

                        # Start the main player's clock.
                        self.main_player.timer.timer_started = not self.main_player.timer.timer_started
                        if self.main_player.timer.timer_started:
                            self.main_player.timer.start_time = pg.time.get_ticks()

                        castling = False
                        castling_kingside = False
                        castling_queenside = False
                        
                        # Find and move the selected piece
                        for piece in our_pieces:
                            if piece.rect.collidepoint(mouse_down_position) and piece.colour == turn:

                                # Selected piece found - get its data
                                selected_piece = piece
                                fromSquare = selected_piece.curSquare
                                selected_piece.fromSquare = fromSquare

                                # Get the legal moves of every piece on the board before the selected piece has moved.
                                print(f'{selected_piece.colour} {selected_piece.name} selected. Its curSquare is {selected_piece.curSquare.id}')
                                for piece in self.main_player.board.pieces:
                                    if piece.name != 'King':
                                        piece.get_legal_moves(self.main_player.board.squares, self.main_player.board.pieces, selected_piece, our_king)
                                    else:
                                        piece.get_legal_moves(self.main_player.board.squares, self.main_player.board.pieces, selected_piece, our_king)

                                # Get the legal moves of the selected piece.
                                print(f'The selected piece"s available moves are {[square.id for square in selected_piece.legal_moves]}')

                                for square in selected_piece.legal_moves:
                                    pg.draw.circle(self.main_player.board.screen, (144, 238, 144), (square.x + 50, square.y + 50), 15)

                                # 'Erase' the old position of the selected piece, by drawing over it the original square
                                pg.draw.rect(self.main_player.board.screen, fromSquare.colour, (fromSquare.x, fromSquare.y, 100, 100))
                                selected_piece.drag(board, mouse_down_position)
                                break
                                
                    # If we are done dragging, get the square we moved to
                    elif event.type == pg.MOUSEBUTTONUP:
                        up_mouse_position = pg.mouse.get_pos()
                        for square_of_interest in self.main_player.board.squares:
                            if square_of_interest.coords.collidepoint(up_mouse_position) and selected_piece:

                                
                                # 'Erase' the drawn circles.
                                for square in selected_piece.legal_moves:
                                    if square != square_of_interest:
                                        pg.draw.rect(self.main_player.board.screen, square.colour, (square.x, square.y, 100, 100))

                                # Deals with castling
                                if selected_piece.name == 'King':

                                    # If the selected square represents a legal move for the selected king.
                                    if square_of_interest in selected_piece.legal_moves and square_of_interest.id != selected_piece.curSquare.id:

                                        # The case where the selected king is castling.
                                        if files_dict[selected_piece.curSquare.file] == files_dict[square_of_interest.file] + 2 or files_dict[selected_piece.curSquare.file] == files_dict[square_of_interest.file] - 2:
                                            castling = True
                                            selected_piece, chess_move, square_of_interest, promoted_to_piece = self.castle(self.main_player.board.screen, square_of_interest, selected_piece, fromSquare, castling, our_king, opponents_king, our_pieces, opponents_pieces, turn)
                                            move_to_square = square_of_interest
                                        # The case where the selected king is making a non-castling move.
                                        else:
                                            selected_piece, chess_move, square_of_interest, promoted_to_piece = self.format_move(self.main_player.board.screen, selected_piece, square_of_interest, fromSquare, castling, castling_kingside, castling_queenside, our_king, opponents_king, our_pieces, opponents_pieces, turn, promoted_to_piece)
                                            move_to_square = square_of_interest
                                    # If the square we clicked on isn't a legal move for the selected king, then put the king back to its starting square.
                                    else:
                                        print('Invalid move. Try again.')
                                        selected_piece.update(self.main_player.board.screen, fromSquare, fromSquare)

                                        if selected_piece.first_move:
                                            selected_piece.first_move = True
                                        selected_piece.draw(self.main_player.board.screen)
                                        selected_piece = None
                                
                                # For every piece that is not a king.
                                else:
                                    
                                    # If the square of interest represents a legal move for the selected piece.
                                    if square_of_interest in selected_piece.legal_moves:
                                        selected_piece, chess_move, square_of_interest, promoted_to_piece = self.format_move(self.main_player.board.screen, selected_piece, square_of_interest, fromSquare, castling, castling_kingside, castling_queenside, our_king, opponents_king, our_pieces, opponents_pieces, turn, promoted_to_piece)
                                        move_to_square = square_of_interest
                                    # If the square of interest represents an illegal move for the selected piece, then return that piece to its fromSquare.
                                    else:
                                        print('Invalid move. Try again.')
                                        selected_piece.update(self.main_player.board.screen, fromSquare, fromSquare)
                                        selected_piece.draw(self.main_player.board.screen)
                                        selected_piece = None
                            

                    if chess_move:
                        self.main_player.has_moved = True
                
                elif self.main_player.colour != turn:

                    # Player whose turn it isn't hangs here until their opponent has made a move.
                    while opponents_move is None:
                        
                        opponents_move = self.net.client.recv(2048).decode()
                        
                        mate_check = False
                
                        # Non-castling moves. Update the board of the player whose turn it isn't.
                        if opponents_move.split()[0] != 'O-O' and opponents_move.split()[0] != 'O-O-O':
                            turn, fromSquare, newSquare, piece_taken, promoted_to_piece, our_king_in_check = self.parse_data(opponents_move)

                            # Update our table
                            table = self.main_player.board.move_table.tableWidget
                            rowPosition = table.rowCount()

                            if self.main_player.colour == 'white':
                                if rowPosition != 0:
                                    table.setItem(rowPosition - 1, 1, QTableWidgetItem(f'{fromSquare.id}-{newSquare.id}'))
                                else:
                                    table.setItem(rowPosition, 1, QTableWidgetItem(f'{fromSquare.id}-{newSquare.id}')) 
                            else:
                                if table.rowCount() == 0:
                                    table.insertRow(rowPosition)
                                rowPosition = table.rowCount()
                                print(rowPosition)
                                if rowPosition != 0:
                                    table.setItem(rowPosition - 1, 0, QTableWidgetItem(f'{fromSquare.id}-{newSquare.id}'))
                                else:
                                    table.setItem(rowPosition, 0, QTableWidgetItem(f'{fromSquare.id}-{newSquare.id}'))

                            # Check for piece taken.
                            if piece_taken == 'True':
                                pg.draw.rect(self.main_player.board.screen, newSquare.colour, (newSquare.x, newSquare.y, 100, 100))

                            # If the opponent promoted, then we need to add that piece to our screen and our list of pieces etc...
                            if promoted_to_piece != 'None':
                                print(promoted_to_piece)

                                # First, remove the promoted-pawn from the sets that it belongs to.
                                for piece in opponents_pieces:
                                    
                                    # Blit the fromSquare and remove that piece from its sets.
                                    if piece.curSquare == fromSquare:
                                        
                                        pg.draw.rect(self.main_player.board.screen, piece.curSquare.colour, (piece.curSquare.x, piece.curSquare.y, 100, 100))
                                        if piece.colour == 'white':
                                            self.main_player.board.white_pieces.remove(piece)
                                        else:
                                            self.main_player.board.black_pieces.remove(piece)
                                        self.main_player.board.pieces.remove(piece)
                                        break


                                # Add the promoted piece to our set of pieces.
                                new_piece = None
                                new_colour = None
                                if self.main_player.colour == 'white':
                                    new_colour = 'black'
                                else:
                                    new_colour = 'white'

                                if promoted_to_piece == 'Queen':
                                    new_piece = queen.Queen(newSquare, new_colour)

                                elif promoted_to_piece == 'Rook':
                                    new_piece = rook.Rook(newSquare, new_colour)

                                elif promoted_to_piece == 'Bishop':
                                    new_piece = bishop.Bishop(newSquare, new_colour)

                                elif promoted_to_piece == 'Knight':
                                    new_piece = knight.Knight(newSquare, new_colour)
                                
                                self.main_player.board.pieces.add(new_piece)

                                if self.main_player.colour == 'white':
                                    self.main_player.board.white_pieces.add(new_piece)
                                else:
                                    self.main_player.board.black_pieces.add(new_piece)
                                # our_pieces = [piece for piece in self.main_player.board.pieces if piece.colour == self.main_player.colour]
                                # opponents_pieces = [piece for piece in self.main_player.board.pieces if piece not in our_pieces]

                                # Draw in the new piece and continue.
                                pg.draw.rect(self.main_player.board.screen, newSquare.colour, (newSquare.x, newSquare.y, 100, 100))
                                new_piece.update(self.main_player.board.screen, fromSquare, newSquare)
                                new_piece.draw(self.main_player.board.screen)
                                new_piece.get_legal_moves(self.main_player.board.squares, self.main_player.board.pieces, None, our_king)
                                opponents_pieces = [piece for piece in self.main_player.board.pieces if piece.colour != self.main_player.colour]

                            for piece in opponents_pieces:
                                if piece.curSquare == fromSquare:

                                    pg.draw.rect(self.main_player.board.screen, piece.curSquare.colour, (piece.curSquare.x, piece.curSquare.y, 100, 100))
                                    piece.update(self.main_player.board.screen, fromSquare, newSquare)
                                    piece.draw(self.main_player.board.screen)

                                piece.get_legal_moves(self.main_player.board.squares, self.main_player.board.pieces, None, our_king)

                            for piece in opponents_pieces:
                                print(f'{piece.name} {piece.curSquare.id} {[square.id for square in piece.legal_moves]}')

                            if our_king_in_check == 'True':
                                our_king.in_check = True
                                print('our king in check')
                                for piece in opponents_pieces:
                                    if our_king.curSquare in piece.legal_moves:
                                        our_king.checking_piece = piece
                                        our_king = our_king.how_in_check(our_king)
                                        our_king.list_of_checking_pieces.append((piece, piece.curSquare.id))

                        elif opponents_move.split()[0] == 'O-O':
                            turn = opponents_move.split()[1]

                            # If we are white, then other player is black.  Castling kingside then implies which rook moved.
                            if self.main_player.colour == 'white':
                                # Update the board of the person whose turn it isn't.
                                # Update the king.
                                for piece in opponents_pieces:
                                    if piece.name == 'King':
                                        pg.draw.rect(self.main_player.board.screen, piece.curSquare.colour, (piece.curSquare.x, piece.curSquare.y, 100, 100))
                                        piece.update(self.main_player.board.screen, piece.curSquare, self.get_square('G8', self.main_player.board.squares))
                                        piece.draw(self.main_player.board.screen)
                                        break
                                
                                # Update the rook.
                                for piece in opponents_pieces:
                                    if piece.curSquare.id == 'H8':
                                        print(len(self.main_player.board.squares))
                                        pg.draw.rect(self.main_player.board.screen, piece.curSquare.colour, (piece.curSquare.x, piece.curSquare.y, 100, 100))
                                        piece.update(self.main_player.board.screen, piece.curSquare, self.get_square('F8', self.main_player.board.squares))
                                        piece.draw(self.main_player.board.screen)
                                        break

                            # If we are black, then other player is white.  Castling kingside then implies which rook moved.
                            else:
                                # Update the king.
                                for piece in opponents_pieces:
                                    if piece.name == 'King':
                                        pg.draw.rect(self.main_player.board.screen, piece.curSquare.colour, (piece.curSquare.x, piece.curSquare.y, 100, 100))
                                        piece.update(self.main_player.board.screen, piece.curSquare, self.get_square('G1', self.main_player.board.squares))
                                        piece.draw(self.main_player.board.screen)
                                        break
                                
                                # Update the rook.
                                for piece in opponents_pieces:
                                    if piece.curSquare.id == 'H1':
                                        pg.draw.rect(self.main_player.board.screen, piece.curSquare.colour, (piece.curSquare.x, piece.curSquare.y, 100, 100))
                                        piece.update(self.main_player.board.screen, piece.curSquare, self.get_square('F1', self.main_player.board.squares))
                                        piece.draw(self.main_player.board.screen)
                                        break

                        elif opponents_move.split()[0] == 'O-O-O':
                            turn = opponents_move.split()[1]

                            # If we are white, then other player is black.  Castling kingside then implies which rook moved.
                            if self.main_player.colour == 'white':
                                # Update the board of the person whose turn it isn't.
                                # Update the king.
                                for piece in opponents_pieces:
                                    if piece.name == 'King':
                                        pg.draw.rect(self.main_player.board.screen, piece.curSquare.colour, (piece.curSquare.x, piece.curSquare.y, 100, 100))
                                        piece.update(self.main_player.board.screen, piece.curSquare, self.get_square('C8', self.main_player.board.squares))
                                        piece.draw(self.main_player.board.screen)
                                        break
                                
                                # Update the rook.
                                for piece in opponents_pieces:
                                    if piece.curSquare.id == 'A8':
                                        pg.draw.rect(self.main_player.board.screen, piece.curSquare.colour, (piece.curSquare.x, piece.curSquare.y, 100, 100))
                                        piece.update(self.main_player.board.screen, piece.curSquare, self.get_square('D8', self.main_player.board.squares))
                                        piece.draw(self.main_player.board.screen)
                                        break

                            # If we are black, then other player is white.  Castling kingside then implies which rook moved.
                            else:
                                # Update the king.
                                for piece in opponents_pieces:
                                    if piece.name == 'King':
                                        pg.draw.rect(self.main_player.board.screen, piece.curSquare.colour, (piece.curSquare.x, piece.curSquare.y, 100, 100))
                                        piece.update(self.main_player.board.screen, piece.curSquare, self.get_square('C1', self.main_player.board.squares))
                                        piece.draw(self.main_player.board.screen)
                                        break
                                
                                # Update the rook.
                                for piece in opponents_pieces:
                                    if piece.curSquare.id == 'A1':
                                        pg.draw.rect(self.main_player.board.screen, piece.curSquare.colour, (piece.curSquare.x, piece.curSquare.y, 100, 100))
                                        piece.update(self.main_player.board.screen, piece.curSquare, self.get_square('D1', self.main_player.board.squares))
                                        piece.draw(self.main_player.board.screen)
                                        break
                
                for piece in our_pieces:
                    piece.get_legal_moves(self.main_player.board.squares, self.main_player.board.pieces, None, our_king)
            
            if not mate_check:
                self.check_for_mate(our_king, our_pieces)
                mate_check = True
            
            if self.main_player.has_moved and turn == self.main_player.colour:
                if turn == 'white':
                    turn = 'black'
                else:
                    turn = 'white'
                print(f'Updated the turn.  Now it is {turn}s turn.')
                
                info = chess_move + " " + turn + " " + str(move_to_square.piece_taken) + " " + str(promoted_to_piece) + " " + str(opponents_king.in_check)
                
                table = self.main_player.board.move_table.tableWidget
                
                rowPosition = table.rowCount()
                print(rowPosition)
                print(chess_move.split()[0])
                if self.main_player.colour == 'white':
                    table.insertRow(rowPosition)
                    rowPosition = table.rowCount()
                    if rowPosition == 0:
                        if chess_move.split()[0] == 'None':
                            table.setItem(rowPosition, 0, QTableWidgetItem(chess_move.split()[1]))
                        else:
                            table.setItem(rowPosition - 1, 0, QTableWidgetItem(chess_move))
                        #table.setItem(rowPosition , 1, QTableWidgetItem(chess_move))
                    else:
                        if chess_move.split()[0] == 'None':
                            table.setItem(rowPosition - 1, 0, QTableWidgetItem(chess_move.split()[1]))
                        else:
                            table.setItem(rowPosition - 1, 0, QTableWidgetItem(chess_move))
                    #table.setItem(rowPosition , 1, QTableWidgetItem(chess_move))
                else:
                    table.insertRow(rowPosition)
                    if rowPosition == 0:
                        if chess_move.split()[0] == 'None':
                            table.setItem(rowPosition, 1, QTableWidgetItem(chess_move.split()[1]))
                        else:
                            table.setItem(rowPosition - 1, 1, QTableWidgetItem(chess_move))
                        #table.setItem(rowPosition , 1, QTableWidgetItem(chess_move))
                    else:
                        if chess_move.split()[0] == 'None':
                            table.setItem(rowPosition - 1, 1, QTableWidgetItem(chess_move.split()[1]))
                        else:
                            table.setItem(rowPosition - 1, 1, QTableWidgetItem(chess_move))
                        #table.setItem(rowPosition - 1, 1, QTableWidgetItem(chess_move))
                    
                
                # self.board.move_table.layout.tableWidget.rowCount()
                self.net.client.send(str.encode(info))
                self.main_player.has_moved = False

            pg.display.update()
Beispiel #14
0
    def format_move(self, board, selected_piece, square_of_interest, fromSquare, castling, castling_kingside, castling_queenside, our_king, opponents_king, our_pieces, opponents_pieces, turn, promoted_to_piece):

        # If the selected piece is about to capture an opponent's piece, then that piece must be removed from pieces.
        # Also need to update the checking variables here, since otherwise they won't get updated afterwards.
        if square_of_interest and square_of_interest.occupied_colour != selected_piece.colour:
            for piece in opponents_pieces:
                if piece.curSquare == square_of_interest:
                    if piece == our_king.checking_piece:
                        our_king.in_check(piece, our_king)
                    square_of_interest.piece_taken = True
                    self.main_player.board.pieces.remove(piece)
                    opponents_pieces.remove(piece)
                    break
        
        # Update the main player's board.
        pg.draw.rect(self.main_player.board.screen, square_of_interest.colour, (square_of_interest.x, square_of_interest.y, 100, 100))
        selected_piece.update(board, fromSquare, square_of_interest)
        selected_piece.draw(self.main_player.board.screen)
        
        print(f'{selected_piece.colour} {selected_piece.name} released. Its curSquare is {selected_piece.curSquare.id}\n')
        print()

        # Update the legal moves for every piece on the board now.
        # After the move is made, we need to update the available moves for every piece on the board (I think).
        for piece in self.main_player.board.pieces:
            if piece.name == 'Pawn' and piece == selected_piece:
                piece.first_move = False
                piece.taking_squares = []

                # If the selected pawn is promoting, then we need to remove that pawn from the list of pieces, as well as the set of pieces in which it lies.
                # Then we need to add the desired promoted-to piece to pieces, as well as the set of pieces to which it belongs.
                if self.check_promotion(piece):
                    
                    # Run promotion box as a subprocess.
                    promoted_to_piece = subprocess.check_output(["python", "promotion_box.py", f"{selected_piece.colour}"]).strip().decode('ascii')

                    # Remove the selected pawn from the sets it belongs to.
                    pg.draw.rect(board, selected_piece.curSquare.colour, (selected_piece.curSquare.x, selected_piece.curSquare.y, 100, 100))
                    self.main_player.board.pieces.remove(selected_piece)

                    if piece.colour == 'white':
                        self.main_player.board.white_pieces.remove(selected_piece)
                    else:
                        self.main_player.board.black_pieces.remove(selected_piece)

                    # Add the promoted piece to our set of pieces.
                    if promoted_to_piece == 'Queen':
                        selected_piece = queen.Queen(selected_piece.curSquare, selected_piece.colour)

                    elif promoted_to_piece == 'Rook':
                        selected_piece = rook.Rook(selected_piece.curSquare, selected_piece.colour)

                    elif promoted_to_piece == 'Bishop':
                        selected_piece = bishop.Bishop(selected_piece.curSquare, selected_piece.colour)

                    elif promoted_to_piece == 'Knight':
                        selected_piece = knight.Knight(selected_piece.curSquare, selected_piece.colour)
                    
                    self.main_player.board.pieces.add(selected_piece)
                    if self.main_player.colour == 'white':
                        self.main_player.board.white_pieces.add(selected_piece)
                    else:
                        self.main_player.board.black_pieces.add(selected_piece)
                    # our_pieces = [piece for piece in self.main_player.board.pieces if piece.colour == self.main_player.colour]
                    # opponents_pieces = [piece for piece in self.main_player.board.pieces if piece not in our_pieces]

                    # Draw in the new piece and continue.
                    selected_piece.update(board, fromSquare, square_of_interest)
                    selected_piece.draw(board)
                    selected_piece.get_legal_moves(self.main_player.board.squares, self.main_player.board.pieces, selected_piece, our_king)
                    break

            piece.get_legal_moves(self.main_player.board.squares, self.main_player.board.pieces, selected_piece, our_king)
        

        # Check if the move just made delivered a check to the opponent's king. If it did, then set up the appropriate checking variables.
        if self.opponent_in_check(opponents_king, turn):
            print(f'Opponents {opponents_king.checking_piece.name} on {opponents_king.checking_piece.curSquare.id} is checking you!')
            print('CHECK!')

            # Determine the details of how the opponent's king is in check.
            opponents_king.how_in_check(opponents_king)

            # Update the legal moves for every piece on the board now.
            # After the move is made, we need to update the available moves for every piece on the board (I think).
            for piece in self.main_player.board.pieces:
                piece.get_legal_moves(self.main_player.board.squares, self.main_player.board.pieces, selected_piece, opponents_king)

        else:
            # Update the legal moves for every piece on the board now.
            # After the move is made, we need to update the available moves for every piece on the board (I think).
            for piece in self.main_player.board.pieces:
                piece.get_legal_moves(self.main_player.board.squares, self.main_player.board.pieces, selected_piece, opponents_king)

        print(f'Now its available moves are {[square.id for square in selected_piece.legal_moves]}')
        print(f'{selected_piece.name} moved from {fromSquare.id} to {square_of_interest.id}.  Its new square is {selected_piece.curSquare.id}\n')

        if castling_kingside:
            chess_move = 'O-O'
        elif castling_queenside:
            chess_move = 'O-O-O'
        else:   
            if selected_piece.name == 'Pawn':
                chess_move = f'None {selected_piece.fromSquare.id}-{selected_piece.curSquare.id}'
            else:
                chess_move = f'{selected_piece.name} {selected_piece.fromSquare.id}-{selected_piece.curSquare.id}'

        # Note. TODO: Will need to keep track of how many pieces are left on each team throughout the game, since this depends on that.
        self.check_for_mate(opponents_king, opponents_pieces)

        print('\n----------------------\n')

        selected_piece = None   

        return selected_piece, chess_move, square_of_interest, promoted_to_piece
Beispiel #15
0
# How I append horse3 to a list is something we don't want to do. Just immediately append them to the list.
# Look into cases which should be used here and see if it is less code and/or more effective.
# Make a function Init pieces.
# This could be done wayyyyyyyyyyyyy nicer
for i in WHITE:
    if i[0] == "Pawn":
        WHITE2.append(pawn.Pawn(i[1],i[2], "WHITE"))
    elif i[0] == "Knight":
        WHITE2.append(knight.Knight(i[1],i[2], "WHITE"))
    elif i[0] == "Bishop":
        WHITE2.append(bishop.Bishop(i[1],i[2], "WHITE"))
    elif i[0] == "King":
        WHITE2.append(king.King(i[1],i[2], "WHITE"))
    elif i[0] == "Queen":
        WHITE2.append(queen.Queen(i[1],i[2], "WHITE"))
    elif i[0] == "Rook":
        WHITE2.append(rook.Rook(i[1],i[2], "WHITE"))

for i in BLACK:
    if i[0] == "Pawn":
        BLACK2.append(pawn.Pawn(i[1],i[2], "BLACK"))
    elif i[0] == "Knight":
        BLACK2.append(knight.Knight(i[1],i[2], "BLACK"))
    elif i[0] == "Bishop":
        BLACK2.append(bishop.Bishop(i[1],i[2], "BLACK"))
    elif i[0] == "King":
        BLACK2.append(king.King(i[1],i[2], "BLACK"))
    elif i[0] == "Queen":
        BLACK2.append(queen.Queen(i[1],i[2], "BLACK"))
    elif i[0] == "Rook":
 def check_pawn_promotion(self, board, piece, row, col):
     if piece.name == "Pawn" and (row == 0 or row == 7):
         board[row][col] = queen.Queen(piece.colour)
Beispiel #17
0
Wpawn6 = pawn.Pawn('C2', 'white', game)
Wpawn7 = pawn.Pawn('B2', 'white', game)
Wpawn8 = pawn.Pawn('A2', 'white', game)

Wknight1 = knight.Knight("B1", "white", game)
Wknight2 = knight.Knight("G1", "white", game)

Wbishop1 = bishop.Bishop("F1", "white", game)
Wbishop2 = bishop.Bishop("C1", "white", game)

Wrook1 = rook.Rook("H1", "white", game)
Wrook2 = rook.Rook("A1", "white", game)

Wking = king.King("D1", "white", game)

Wqueen = queen.Queen("E1", "white", game)

#team black
Bpawn1 = pawn.Pawn('H7', 'black', game)
Bpawn2 = pawn.Pawn('G7', 'black', game)
Bpawn3 = pawn.Pawn('F7', 'black', game)
Bpawn4 = pawn.Pawn('E7', 'black', game)
Bpawn5 = pawn.Pawn('D7', 'black', game)
Bpawn6 = pawn.Pawn('C7', 'black', game)
Bpawn7 = pawn.Pawn('B7', 'black', game)
Bpawn8 = pawn.Pawn('A7', 'black', game)

Bknight1 = knight.Knight("G8", "black", game)
Bknight2 = knight.Knight("B8", "black", game)

Bbishop1 = bishop.Bishop("F8", "black", game)
Beispiel #18
0
    def makeChessboard(self):
        # # Make Square Objects
        # # column
        # current_num = 1
        # for y in range(1, 9):
        #     # row
        #     for x in range(1, 9):
        #         if current_num % 2 == 0:
        #             color = "WHITE"
        #         else:
        #             color = "BLACK"
        #         SSquare = [x, y, color]
        #         self.squares.append(SSquare)
        #         current_num += 1
        # for i in range(len(self.squares)):
        #     temp_square = Square.Square(self.squares[i][0], self.squares[i][1], self.squares[i][2])  # make a square object
        #     self.squareObjs.append(temp_square)

        y = 1  # row
        x = 1  # column
        number = 1
        count = "Piece" + str(number)
        # WHITE PIECES
        for i in range(17):
            team = "WHITE"
            if x > 8:
                x = 1
                y += 1
            if y == 2:
                piece = pawn.Pawn(x, y, team, count)
                self.list_of_pieces.append(piece)
                self.dict_of_pieces[count] = piece
                number += 1
                x += 1
                continue
            elif x == 1 or x == 8:
                piece = rook.Rook(x, y, team, count)
            elif x == 2 or x == 7:
                piece = knight.Knight(x, y, team, count)
            elif x == 3 or x == 6:
                piece = bishopBase.Bishop(x, y, team, count)
            elif x == 4:
                piece = queen.Queen(x, y, team, count)
            elif x == 5:
                piece = king.King(x, y, team, count)
            self.list_of_pieces.append(piece)
            self.dict_of_pieces[count] = piece
            x += 1
            number += 1
        r = 7
        c = 1
        # BLACK PIECES
        number = 17
        count = "Piece" + str(number)
        for i in range(33):
            team = "BLACK"
            if c > 8:
                c = 1
                r += 1
            if r == 7:
                piece = pawn.Pawn(c, r, team, count)
                self.list_of_pieces.append(piece)
                self.dict_of_pieces[count] = piece
                number += 1
                c += 1
                continue
            elif c == 1 or c == 8:
                piece = rook.Rook(c, r, team, count)
            elif c == 2 or c == 7:
                piece = knight.Knight(c, r, team, count)
            elif c == 3 or c == 6:
                piece = bishopBase.Bishop(c, r, team, count)
            elif c == 4:
                piece = queen.Queen(c, r, team, count)
            elif c == 5:
                piece = king.King(c, r, team, count)
            self.list_of_pieces.append(piece)
            self.dict_of_pieces[count] = piece
            number += 1
            c += 1