Пример #1
0
 def loadAll(self, screen, width, height):
     for row in range(len(self.board)):
         for col in range(len(self.board[row])):
             thing = self.board[row][col]
             if thing != 0:
                 temp = Pieces([row, col],
                               self.board_to_physical(
                                   width, height, row, col),
                               self.str_to_info(thing))
                 temp.load_image(screen, width, height)
Пример #2
0
    def __init__(self, bin="", last_move=None):
        self.pieces = Pieces()
        self.whoseTurn = "D"
        self.max_x = 7
        self.max_y = 7
        self.bin_str = bin
        self.last_moved = last_move

        if self.bin_str:
            self.from_binary(self.bin_str)
Пример #3
0
    def game_begin(self):

        from Pieces import Pieces

        uniDict = {
            "white": {
                "Pawn": "♙",
                "Rook": "♖",
                "Knight": "♘",
                "Bishop": "♗",
                "King": "♔",
                "Queen": "♕"
            },
            "black": {
                "Pawn": "♟",
                "Rook": "♜",
                "Knight": "♞",
                "Bishop": "♝",
                "King": "♚",
                "Queen": "♛"
            }
        }

        pieces_list = [
            "Rook", "Knight", "Bishop", "Queen", "King", "Bishop", "Knight",
            "Rook"
        ]

        for i in range(0, 8):
            # board(y,x)
            self.board[(i, 0)] = Pieces(x=0,
                                        y=i,
                                        colour="white",
                                        name=uniDict["white"][pieces_list[i]],
                                        direction=1,
                                        category=pieces_list[i])
            self.board[(i, 1)] = Pieces(x=1,
                                        y=i,
                                        colour="white",
                                        name=uniDict["white"]["Pawn"],
                                        direction=1,
                                        category="Pawn")
            self.board[(i, 6)] = Pieces(x=1,
                                        y=i,
                                        colour="black",
                                        name=uniDict["black"]["Pawn"],
                                        direction=-1,
                                        category="Pawn")
            self.board[(i, 7)] = Pieces(x=7,
                                        y=i,
                                        colour="black",
                                        name=uniDict["black"][pieces_list[i]],
                                        direction=1,
                                        category=pieces_list[i])
        return self.board
Пример #4
0
 def __init__(self, destination: pygame.Surface, board: Board):
     """
     This function is default c'tor and it loads the pieces and other
     graphics relevant to the board.
     """
     self.pieces_graphics = Pieces.load_pieces()
     self.destination = destination
     self.board = board
Пример #5
0
    def init_Game(self):
        """
        Starts a new game.

        Here is the normal start state of a standard 8 by 8 checkerboard

              0  1  2  3  4  5  6  7
            0 __ B  __ B  __ B  __ B
            1 B  __ B  __ B  __ B  __
            2 __ B  __ B  __ B  __ B
            3 __ __ __ __ __ __ __ __
            4 __ __ __ __ __ __ __ __
            5 R  __ R  __ R  __ R  __
            6 __ R  __ R  __ R  __ R
            7 R  __ R  __ R  __ R  __

        """
        size = self.size

        for i in range(size):
            if i % 2 == 0:
                self.board[(i, 5)] = Pieces(i, 5, RED)
                self.board[(i, 7)] = Pieces(i, 7, RED)
                self.board[(i, 1)] = Pieces(i, 1, BLUE)
            else:
                self.board[(i, 0)] = Pieces(i, 0, BLUE)
                self.board[(i, 2)] = Pieces(i, 2, BLUE)
                self.board[(i, 6)] = Pieces(i, 6, RED)
Пример #6
0
 def get_piece_color_at(self, row, col):
     """ 
     This function returns piece color on coordinates row x col. If there is
     no piece, then the function returns the color of cell.
     :param: row, is the row of the cell. 
     :param: col, is the col of the cell. 
     :return: The color of the piece, if there is one. If no, the color of
     the cell.
     """
     piece = self.get_piece_at(row, col)
     if piece == Pieces.NONE:
         return self.get_cell_color_at(row, col)
     return Pieces.get_piece_color(piece)
Пример #7
0
    def __init__(self,
                 copy=False,
                 size=None,
                 turn=None,
                 board=None,
                 piece_taken=None):
        """
        Initializes the board
        """
        if copy:
            self.size = size
            self.turn = turn
            self.board = board
            self.piece_taken = piece_taken
        else:
            self.size = 8
            self.turn = RED

            self.board = dict([((x, y), Pieces(x, y, 0))
                               for x in range(self.size)
                               for y in range(self.size)])
            self.init_Game()
            self.piece_taken = False
Пример #8
0
 def __init__(self, color, x, y, grid):
     Pieces.__init__(self, x, y, color, grid)
Пример #9
0
	def __init__(self, name = "King", color="BLACK", position = (0,0)):
		Pieces.__init__(self, name, color, position)

		self.checked = False
		self.checkmated = False
		self.type = "King"
Пример #10
0
 def __init__(self, color, x, y, grid):
     Pieces.__init__(self, x, y, color, grid)
     self.prevx = self.revWidth.get(self.width.get(self.x) - 1)
     self.nextx = self.revWidth.get(self.width.get(self.x) + 1)
Пример #11
0
    def move(self, curr_piece, move):
        """

        :param curr_piece: A piece object
        :param move: A tuple holding the change in coordinates (dx, dy) of the given piece
        :return: The next state of the board after the move is played
        """
        if curr_piece.get_team() == 0:
            raise ValueError("Invalid Move, Blank spot has no piece")

        # Checking so that a non-king piece is not moving backwards

        if curr_piece.get_team() * move[1] < 0 and not curr_piece.is_king():
            raise ValueError("Invalid Move, not a king")

        # Checking so that a move strictly diagonal and within a 1 or 2 unit radius
        if abs(move[1]) != abs(move[0]) or (abs(move[0]) > 2 or move[0] == 0):
            raise ValueError("Invalid Move, bad move")

        if abs(move[0]) == 1 and self.force_jump():
            raise ValueError("You must take the opponent's piece!")

        curr_pos = curr_piece.get_position()
        # new_spot is the new location of the curr_piece
        new_spot = (curr_pos[0] + move[0], curr_pos[1] + move[1])

        # Checks if the new_spot is within the board's boundaries
        if not self.inBounds(new_spot):
            raise ValueError("Invalid Move, out of bounds")

        # Checking so that moves are valid

        # Checking if a piece is not currently at the new_spot

        if self.board[new_spot].get_team() != 0:
            raise ValueError("Invalid Move, new spot is occupied")

        # Calculate the current and opposite teams
        curr_team = curr_piece.get_team()
        opp_team = RED
        if curr_team == RED:
            opp_team = BLUE
        opp_index = int((opp_team + 1) / 2)

        if abs(move[0]) == 1:
            curr_piece.change_position(new_spot[0], new_spot[1])
            self.board[curr_pos] = Pieces(curr_pos[0], curr_pos[1], 0)

            promotion_row = (opp_index * (self.size - 1) - self.size + 1) * -1
            if new_spot[1] == promotion_row and not curr_piece.is_king():
                curr_piece.promote()
            self.board[new_spot] = curr_piece.deep_copy_piece()
            self.piece_taken = False
            self.turn *= -1
            return

        # A jump is taking place, so an opposing color piece must be in between the jump
        else:
            # Calculate the space on the board that is jumped over
            jump_spot = (curr_pos[0] + (move[0] / 2),
                         curr_pos[1] + (move[1] / 2))

            if self.board[jump_spot].get_team() == self.turn * -1:
                curr_piece.change_position(new_spot[0], new_spot[1])
                self.board[curr_pos] = Pieces(curr_pos[0], curr_pos[1], 0)

                promotion_row = (opp_index *
                                 (self.size - 1) - self.size + 1) * -1
                if new_spot[1] == promotion_row and not curr_piece.is_king():
                    curr_piece.promote()

                self.board[jump_spot] = Pieces(jump_spot[0], jump_spot[1], 0)
                self.board[curr_pos] = Pieces(curr_pos[0], curr_pos[1], 0)
                self.board[new_spot] = curr_piece.deep_copy_piece()
                if not self.force_jump():
                    self.turn *= -1
                self.piece_taken = True

                return
            # Program reaches here if there is no opposing team's piece is in the jump_spot
            raise ValueError("Invalid Move, empty jump")
Пример #12
0
 def __init__(self, x, y, grid):
     Pieces.__init__(self, x, y, "n", grid)
Пример #13
0
class BoardState:
    def __init__(self, bin="", last_move=None):
        self.pieces = Pieces()
        self.whoseTurn = "D"
        self.max_x = 7
        self.max_y = 7
        self.bin_str = bin
        self.last_moved = last_move

        if self.bin_str:
            self.from_binary(self.bin_str)

    # TODO: how can a move know if it's valid without the pieces?
    def resolve_move(self, last_move):
        if not last_move.is_valid():  # There's a smell here
            return
        moved_piece = self.pieces.get_piece_at(last_move.end_loc)
        if not moved_piece:  # No piece at end of move... throw?
            return
        piece_loc = moved_piece.get_location()
        for dir in DIRECTIONS:
            neighbor_loc = piece_loc + dir
            far_neighbor_loc = neighbor_loc + dir

            neighbor_piece = self.pieces.get_piece_at(neighbor_loc)
            if neighbor_piece and moved_piece.is_enemy(neighbor_piece):
                far_neighbor_piece = self.pieces.get_piece_at(far_neighbor_loc)
                if far_neighbor_piece and not moved_piece.is_enemy(
                        far_neighbor_piece):
                    pass
                    # TODO: Capture neighbor piece

    # Take in a string of 1's and 0's as passed as a board state
    def from_binary(self, boardBits):
        kingX = int(boardBits[0:3], 2)
        kingY = int(boardBits[3:6], 2)
        self.pieces.add_piece(King(x=kingX, y=kingY))

        locIndex = 0
        strIndex = 6
        while locIndex < 44:
            if boardBits[strIndex] == '1':  # piece found here
                newLoc = BoardLocations.gen_from_index(locIndex)
                if boardBits[strIndex + 1] == '1':
                    self.pieces.add_piece(Attacker(location=newLoc))
                else:
                    self.pieces.add_piece(Defender(location=newLoc))
                strIndex += 1  # advance one for the data payload
            locIndex += 1
            strIndex += 1

        self.whoseTurn = "D"
        if boardBits[-2] == "1":
            self.whoseTurn = "A"

    def is_attacker_turn(self):
        return self.whoseTurn == "A"

    def is_defender_turn(self):
        return self.whoseTurn == "D"

    def dump(self):
        self.pieces.dump_pieces()

    # Emit a string of 1's and 0's as passed as a board state
    def to_binary(self):
        ret = ""
        ret += self.pieces.king.to_binary()
        non_king_piece_count = 0
        for locIndex in range(44):
            location = BoardLocations.gen_from_index(locIndex)
            piece = self.pieces.get_piece_at(location)
            if piece:
                if piece.is_king():
                    ret += "0"
                else:
                    ret += piece.to_binary()
                    non_king_piece_count += 1
            else:
                ret += "0"

        # Add on zeros for captured pieces as padding
        for i in range(12 - non_king_piece_count):
            ret += "0"

        # Add on the bit for whose turn it is
        if self.whoseTurn == "A":
            ret += "1"
        else:
            ret += "0"
        ret += "0"  # Reserved padding bit
        return ret

    # TODO: Change this to functions, geez Crandall
    def gen_child_states(self):
        ret = []
        moveList = None
        realTurn = self.whoseTurn

        if self.whoseTurn == "A":  # Move attackers
            moveList = self.pieces.attackers
            self.whoseTurn = "D"
        else:  # Move Defenders
            moveList = self.pieces.defenders
            self.whoseTurn = "A"
        for currPiece in moveList:
            start_location = currPiece.get_location()
            startX = start_location.x
            startY = start_location.y
            # print("Startx = {0} , Starty = {1}".format(startX, startY))

            maxX = 7
            minX = -1
            maxY = 7
            minY = -1
            if not currPiece.is_king():
                if startY == 0 or startY == 6:  # corners
                    maxX = 6
                    minX = 0
                if startX == 0 or startX == 6:  # corners
                    maxY = 6
                    minY = 0

            for curr_x in range(startX + 1, maxX):  # move right
                new_loc = Location(x=curr_x, y=startY)
                print(new_loc)
                piece = self.pieces.get_piece_at(new_loc)
                if not piece:
                    currPiece.set_location(new_loc)
                    ret.append(self.to_binary())
                else:
                    break  # hit another piece
            currPiece.set_location(start_location)

            for curr_x in range(startX - 1, minX, -1):  # move left
                new_loc = Location(x=curr_x, y=startY)
                print(new_loc)
                piece = self.pieces.get_piece_at(new_loc)
                if not piece:
                    currPiece.set_location(new_loc)
                    ret.append(self.to_binary())
                else:
                    break  # hit another piece
            currPiece.set_location(start_location)

            for curr_y in range(startY - 1, minY, -1):  # move upwards
                new_loc = Location(x=startX, y=curr_y)
                print(new_loc)
                piece = self.pieces.get_piece_at(new_loc)
                if not piece:
                    currPiece.set_location(new_loc)
                    ret.append(self.to_binary())
                else:
                    break  # hit another piece - stop looping
            currPiece.set_location(start_location)

            for curr_y in range(startY + 1, maxY):  # move downwards
                new_loc = Location(x=startX, y=curr_y)
                print(new_loc)
                piece = self.pieces.get_piece_at(new_loc)
                if not piece:
                    currPiece.set_location(new_loc)
                    ret.append(self.to_binary())
                else:
                    break  # hit another piece - stop looping
            currPiece.set_location(start_location)

        self.whoseTurn = realTurn
        return ret

    # Create a metrics object from the current board state for heuristics use
    def generate_metrics(self):
        metrics = BoardMetrics()
        metrics.update_metrics(self.pieces)
        return metrics

    # Returns a string representing the board visually for terminal output
    def get_terminal_string(self, indicies=False):
        # pragma: nocover
        ret = ""
        if indicies is True:
            ret += " X "
            for i in range(self.max_x):
                ret += "{:<2}".format(i)
            ret += "\n"
        for y in range(self.max_y):
            if indicies is True:
                if y == 0:
                    ret += "Y "
                else:
                    ret += "  "
            ret += "+-" * self.max_x + "+\n"
            if indicies is True:
                ret += "{:<2}".format(y)
            for x in range(self.max_x):
                currLoc = Location(x=x, y=y)
                piece = self.pieces.get_piece_at(currLoc)
                draw = " "
                if currLoc in KING_TILES:  # Really, a total hack
                    draw = chr(0x2318)
                if piece:
                    draw = piece.get_terminal_string()
                ret += "|" + draw
            ret += "|\n"
        if indicies is True:
            ret += "  "
        ret += "+-" * self.max_x + "+\n"
        return ret
Пример #14
0
from board import Board
from Pieces import Pieces
pygame.init()

# Constants
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800

win = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption(('Chess'))

running = True

board = Board(win)
board.draw_board()
piece1 = Pieces(*board.boxes[0].center,'B',0,0,board)
piece2 = Pieces(*board.boxes[1].center,'W',1,0,board)
board.boards[0][0] = [1,piece1]
board.boards[1][0] = [1,piece2]
all_pieces = pygame.sprite.Group()
all_pieces.add(piece1)
all_pieces.add(piece2)

while running:
    for event in pygame.event.get():
        all_pieces.update(event)
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False

        elif event.type == QUIT:
Пример #15
0
	def __init__(self, name = "Knight", color="BLACK", position = (0,0)):
		Pieces.__init__(self, name, color, position)
		self.weight = 15
		self.type = "Knight"
Пример #16
0
	def __init__(self, name = "Pawn", color="BLACK", position = (0,0)):
		Pieces.__init__(self, name, color, position)
		self.weight = 10
		self.threat = 10
		self.type = "Pawn"