def __init__(self, grid, screen): # White grid[0][0] = Pieces.Rook("White", 0, 0, screen) grid[0][7] = Pieces.Rook("White", 0, 7, screen) grid[0][1] = Pieces.Knight("White", 0, 1, screen) grid[0][6] = Pieces.Knight("White", 0, 6, screen) grid[0][2] = Pieces.Bishop("White", 0, 2, screen) grid[0][5] = Pieces.Bishop("White", 0, 5, screen) grid[0][4] = Pieces.Queen("White", 0, 4, screen) grid[0][3] = Pieces.King("White", 0, 3, screen) for x in range(8): grid[1][x] = Pieces.Pawn("White", 1, x, screen) # Black changes in some comments grid[7][0] = Pieces.Rook("Black", 7, 0, screen) grid[7][7] = Pieces.Rook("Black", 7, 7, screen) grid[7][1] = Pieces.Knight("Black", 7, 1, screen) grid[7][6] = Pieces.Knight("Black", 7, 6, screen) grid[7][2] = Pieces.Bishop("Black", 7, 2, screen) grid[7][5] = Pieces.Bishop("Black", 7, 5, screen) grid[7][4] = Pieces.Queen("Black", 7, 4, screen) grid[7][3] = Pieces.King("Black", 7, 3, screen) for y in range(8): grid[6][y] = Pieces.Pawn("Black", 6, y, screen) self.grid = grid return
def readyToPlay(self): board = [ [ Pieces.Rook(Color.WHITE, self), Pieces.Knight(Color.WHITE, self), Pieces.Bishop(Color.WHITE, self), Pieces.King(Color.WHITE, self), Pieces.Queen(Color.WHITE, self), Pieces.Bishop(Color.WHITE, self), Pieces.Knight(Color.WHITE, self), Pieces.Rook(Color.WHITE, self), ], [Pieces.Pawn(Color.WHITE, self) for i in range(8)], [PieceName.NONE for i in range(8)], [PieceName.NONE for i in range(8)], [PieceName.NONE for i in range(8)], [PieceName.NONE for i in range(8)], [Pieces.Pawn(Color.BLACK, self) for i in range(8)], [ Pieces.Rook(Color.BLACK, self), Pieces.Knight(Color.BLACK, self), Pieces.Bishop(Color.BLACK, self), Pieces.King(Color.BLACK, self), Pieces.Queen(Color.BLACK, self), Pieces.Bishop(Color.BLACK, self), Pieces.Knight(Color.BLACK, self), Pieces.Rook(Color.BLACK, self), ], ] for i in range(8): for j in range(8): self.__playboard[i][j].piece_setter(board[i][j]) return
def setup_initial_pieces(self): for [row, colour] in [[0, "BLACK"], [7, "WHITE"]]: self.board[row][0] = pcs.Rook(colour) self.board[row][1] = pcs.Knight(colour) self.board[row][2] = pcs.Bishop(colour) self.board[row][5] = pcs.Bishop(colour) self.board[row][6] = pcs.Knight(colour) self.board[row][7] = pcs.Rook(colour) for column in range(8): if colour == "BLACK": self.board[row + 1][column] = pcs.Pawn(colour) else: self.board[row - 1][column] = pcs.Pawn(colour) #temp self.board[row][0].update_role(roles.BasicRole()) self.board[row][1].update_role(roles.BasicRole()) self.board[row][2].update_role(roles.BasicRole()) self.board[row][5].update_role(roles.BasicRole()) self.board[row][6].update_role(roles.BasicRole()) self.board[row][7].update_role(roles.BasicRole()) self.board[0][3] = pcs.Queen("BLACK") self.board[0][4] = pcs.King("BLACK") self.board[7][3] = pcs.King("WHITE") self.board[7][4] = pcs.Queen("WHITE") #temp self.board[0][3].update_role(roles.BasicRole()) self.board[0][4].update_role(roles.BasicRole()) self.board[7][3].update_role(roles.BasicRole()) self.board[7][4].update_role(roles.BasicRole())
def __init__(self, textmode=False): self.textmode = textmode self.pieces.append(Pieces.Rook(self.BLACK)) self.pieces.append(Pieces.Knight(self.BLACK)) self.pieces.append(Pieces.Bishop(self.BLACK)) self.pieces.append(Pieces.Queen(self.BLACK)) self.pieces.append(Pieces.King(self.BLACK)) self.pieces.append(Pieces.Bishop(self.BLACK)) self.pieces.append(Pieces.Knight(self.BLACK)) self.pieces.append(Pieces.Rook(self.BLACK)) for i in range(9, 17): self.pieces.append(Pieces.Pawn(self.BLACK)) for i in range(17, 65 - 16): self.pieces.append(None) for i in range(65 - 16, 65 - 8): self.pieces.append(Pieces.Pawn(self.WHITE)) self.pieces.append(Pieces.Rook(self.WHITE)) self.pieces.append(Pieces.Knight(self.WHITE)) self.pieces.append(Pieces.Bishop(self.WHITE)) self.pieces.append(Pieces.Queen(self.WHITE)) self.pieces.append(Pieces.King(self.WHITE)) self.pieces.append(Pieces.Bishop(self.WHITE)) self.pieces.append(Pieces.Knight(self.WHITE)) self.pieces.append(Pieces.Rook(self.WHITE))
def init(color): #intialization of board based on the color if color.lower() == "white": board[0][0] = Pieces.Rook("Black") board[0][1] = Pieces.Knight("Black") board[0][2] = Pieces.Bishop("Black") board[0][3] = Pieces.Queen("Black") board[0][4] = Pieces.King("Black") board[0][5] = Pieces.Bishop("Black") board[0][6] = Pieces.Knight("Black") board[0][7] = Pieces.Rook("Black") for x in range(8): board[1][x] = Pieces.Pawn("Black") board[7][0] = Pieces.Rook("White") board[7][1] = Pieces.Knight("White") board[7][2] = Pieces.Bishop("White") board[7][3] = Pieces.Queen("White") board[7][4] = Pieces.King("White") board[7][5] = Pieces.Bishop("White") board[7][6] = Pieces.Knight("White") board[7][7] = Pieces.Rook("White") for x in range(8): board[6][x] = Pieces.Pawn("White") else: board[0][0] = Pieces.Rook("White") board[0][1] = Pieces.Knight("White") board[0][2] = Pieces.Bishop("White") board[0][3] = Pieces.King("White") board[0][4] = Pieces.Queen("White") board[0][5] = Pieces.Bishop("White") board[0][6] = Pieces.Knight("White") board[0][7] = Pieces.Rook("White") for x in range(8): board[1][x] = Pieces.Pawn("White") board[7][0] = Pieces.Rook("Black") board[7][1] = Pieces.Knight("Black") board[7][2] = Pieces.Bishop("Black") board[7][3] = Pieces.King("Black") board[7][4] = Pieces.Queen("Black") board[7][5] = Pieces.Bishop("Black") board[7][6] = Pieces.Knight("Black") board[7][7] = Pieces.Rook("Black") for x in range(8): board[6][x] = Pieces.Pawn("Black")
def init_board(self): piece_dict = { "P": lambda row, col, board, color: p.Pawn(row, col, board, color, self. special_move_mem), "N": lambda row, col, board, color: p.Knight(row, col, board, color), "B": lambda row, col, board, color: p.Bishop(row, col, board, color), "Q": lambda row, col, board, color: p.Queen(row, col, board, color), "K": lambda row, col, board, color: p.King(row, col, board, color), "R": lambda row, col, board, color: p.Rook(row, col, board, color), } for row in range(0, 8): for col in range(0, 8): piece = self.string_board[row][col] if piece != "..": piece_color = piece[0] if piece_color == 'b': piece_color = "black" else: piece_color = "white" piece_type = piece[1] self.string_board[row][col] = piece_dict[piece_type]( row, col, self.string_board, piece_color) if piece_color == "black": self.black_playable_pieces.append( self.string_board[row][col]) else: self.white_playable_pieces.append( self.string_board[row][col]) return self.string_board
def place_piece_event(self, event): pos_x, pos_y = event.pos x, y = self.screen_to_coord(pos_x, pos_y) colour = self.board.player new_event = pygame.event.wait() if new_event.type == pygame.KEYDOWN: key = new_event.key piece = None if key == ord("a"): piece = Pieces.Ant(colour) elif key == ord("q"): piece = Pieces.Queen(colour) elif key == ord("b"): piece = Pieces.Beetle(colour) elif key == ord("g"): piece = Pieces.Grasshopper(colour) elif key == ord("s"): piece = Pieces.Spider(colour) if piece: Moves.place_piece(self.board, x, y, piece) self.render_step()
def pawnPromotion(flag, start_row, start_col, end_row, end_col, name_of_piece): attacking_list = brd.isAttacked(gc.GAME_COLOR) row_of_king, col_of_king = brd.findPieceOfSameColor(gc.GAME_COLOR, "King") if (row_of_king, col_of_king) not in attacking_list: brd.board[row_of_king][col_of_king].setIncheck(False) global pawn_with_enpassant color = "" if (flag == 0): if (gc.GAME_COLOR == "Black"): color = "White" else: color = "Black" else: color = gc.GAME_COLOR pawn_with_enpassant = (-1, -1) brd.board[start_row][start_col] = None if name_of_piece.lower() == "Queen".lower(): brd.board[end_row][end_col] = Pieces.Queen(color) if name_of_piece.lower() == "Rook".lower(): brd.board[end_row][end_col] = Pieces.Rook(color) if name_of_piece.lower() == "Bishop".lower(): brd.board[end_row][end_col] = Pieces.Bishop(color) if name_of_piece.lower() == "Knight".lower(): brd.board[end_row][end_col] = Pieces.Knight(color) attacking_list = brd.isAttacked(gc.GAME_COLOR) row_of_king, col_of_king = brd.findPieceOfSameColor(gc.GAME_COLOR, "King") if (row_of_king, col_of_king) not in attacking_list: brd.board[row_of_king][col_of_king].setIncheck(False)
def __init__(self): super(Chess, self).__init__(600, 600, resizable=False, caption='Chess', config=pyglet.gl.Config(double_buffer=True), vsync=False) self.wKing = p.King(4, 0) self.bKing = p.King(4, 7, False) self.board = [[ p.Rook(0, 0), p.Knight(1, 0), p.Bishop(2, 0), p.Queen(3, 0), self.wKing, p.Bishop(5, 0), p.Knight(6, 0), p.Rook(7, 0) ], [p.Pawn(i, 1) for i in range(8)], [None for i in range(8)], [None for i in range(8)], [None for i in range(8)], [None for i in range(8)], [p.Pawn(i, 6, False) for i in range(8)], [ p.Rook(0, 7, False), p.Knight(1, 7, False), p.Bishop(2, 7, False), p.Queen(3, 7, False), self.bKing, p.Bishop(5, 7, False), p.Knight(6, 7, False), p.Rook(7, 7, False) ]] self.validsprites = [] for i in range(8): rowsprites = [] for j in range(8): sprite = pyglet.sprite.Sprite(self.validImg, 75 * j, 75 * i) sprite.visible = False rowsprites.append(sprite) self.validsprites.append(rowsprites) self.wQueen = pyglet.sprite.Sprite(self.spritesheet[7], 131.25, 225) self.wRook = pyglet.sprite.Sprite(self.spritesheet[10], 218.75, 225) self.wBishop = pyglet.sprite.Sprite(self.spritesheet[8], 306.25, 225) self.wKnight = pyglet.sprite.Sprite(self.spritesheet[9], 393.75, 225) self.bQueen = pyglet.sprite.Sprite(self.spritesheet[1], 131.25, 225) self.bRook = pyglet.sprite.Sprite(self.spritesheet[4], 218.75, 225) self.bBishop = pyglet.sprite.Sprite(self.spritesheet[2], 306.25, 225) self.bKnight = pyglet.sprite.Sprite(self.spritesheet[3], 393.75, 225)
def create_pieces(self): # Kings self.pieces['white'].append(Pieces.King(True, (4, 0))) self.pieces['black'].append(Pieces.King(False, (4, 7))) # Pawns for x in range(8): self.pieces['white'].append(Pieces.Pawn(True, (x, 1))) #self.pieces['black'].append(Pieces.Pawn(False, (x, 6))) # White Pieces # TODO: Move List # TODO: Win Screen # TODO: Resign and draw # TODO: Clock #self.pieces['white'].append(Pieces.Knight(True, (1, 0))) #self.pieces['white'].append(Pieces.Knight(True, (6, 0))) #self.pieces['white'].append(Pieces.Bishop(True, (2, 0))) self.pieces['white'].append(Pieces.Bishop(True, (5, 0))) self.pieces['white'].append(Pieces.Rook(True, (0, 0))) #self.pieces['white'].append(Pieces.Rook(True, (7, 0))) self.pieces['white'].append(Pieces.Queen(True, (3, 0))) # Black Pieces #self.pieces['black'].append(Pieces.Knight(False, (1, 7))) #self.pieces['black'].append(Pieces.Knight(False, (6, 7))) #self.pieces['black'].append(Pieces.Bishop(False, (2, 7))) self.pieces['black'].append(Pieces.Bishop(False, (5, 7))) #self.pieces['black'].append(Pieces.Rook(False, (0, 7))) self.pieces['black'].append(Pieces.Rook(False, (7, 7))) self.pieces['black'].append(Pieces.Queen(False, (3, 7))) # TODO: Move this to end of turn # Show pieces for x in self.pieces['white']: self.pieces_grid[x.pos] = x self.labels[x.pos[0]][x.pos[1]].config(text=' ' + x.display + ' ', fg='silver') for x in self.pieces['black']: self.pieces_grid[x.pos] = x self.labels[x.pos[0]][x.pos[1]].config(text=' ' + x.display + ' ', fg='brown')
def getValidMoves(self, board, piece, colour, enforceCaptures=True): moves = [] fr = piece # First, we get a (strictly optimistic) list of plausible places this piece could move to, # ignoring line of sight and promotions. # This is faster than checking validity of all possible moves. destList = board.pieces[fr[0]*8+fr[1]].getPlausibleMoves(fr) for to in destList: m = Move.Move(fr, to) try: self.validate( m, board, colour, enforceCaptures ) moves.append( m ) except RulesViolation as e: pass # Now consider promotion moves promotionPieces = [Pieces.Queen(colour), Pieces.Rook(colour), Pieces.Knight(colour), Pieces.Bishop(colour), Pieces.King(colour)] if isinstance(board.pieces[fr[0]*8+fr[1]], Pieces.Pawn): row = fr[0] if colour==0 and row==1: for col in [fr[1]-1, fr[1], fr[1]+1]: to = [0, col] for pp in promotionPieces: m = Move.PromotionMove(fr, to, pp) try: self.validate( m, board, colour, enforceCaptures ) moves.append( m ) except RulesViolation as e: pass elif colour==1 and row==6: for col in [fr[1]-1, fr[1], fr[1]+1]: to = [7, col] for pp in promotionPieces: m = Move.PromotionMove(fr, to, pp) try: self.validate( m, board, colour, enforceCaptures ) moves.append( m ) except RulesViolation as e: pass return moves
def fromNotation(m, colour): try: mm = [m[0:2], m[2:4]] # e.g. e2e4 fr = [0, 0] to = [0, 0] conv = dict(a=0, b=1, c=2, d=3, e=4, f=5, g=6, h=7) fr[1] = conv[mm[0][0]] fr[0] = 7 - (int(mm[0][1]) - 1) to[1] = conv[mm[1][0]] to[0] = 7 - (int(mm[1][1]) - 1) # Promotion? promotionDict = dict(Q=Pieces.Queen(colour), R=Pieces.Rook(colour), N=Pieces.Knight(colour), B=Pieces.Bishop(colour), K=Pieces.King(colour)) if len(m) > 4: return PromotionMove(fr, to, promotionDict[m[4]]) else: return Move(fr, to) except Exception as e: print e raise
import Pieces as P W_ROOKS = [P.Rook(0, P.WHITE), P.Rook(5, P.WHITE)] W_KNIGHTS = [P.Knight(1, P.WHITE), P.Knight(6, P.WHITE)] W_BISHOPS = [P.Bishop(2, P.WHITE), P.Bishop(7, P.WHITE)] W_QUEEN = P.Queen(3, P.WHITE) W_KING = P.King(4, P.WHITE) W_PAWNS = [] B_ROOKS = [P.Rook(8, P.BLACK), P.Rook(13, P.BLACK)] B_KNIGHTS = [P.Knight(9, P.BLACK), P.Knight(14, P.BLACK)] B_BISHOPS = [P.Bishop(10, P.BLACK), P.Bishop(15, P.BLACK)] B_QUEEN = P.Queen(11, P.BLACK) B_KING = P.King(12, P.BLACK) B_PAWNS = [] EMPTY = P.Empty() for i in range(0, 8): W_PAWNS.append(P.Pawn(16 + i, P.WHITE)) B_PAWNS.append(P.Pawn(24 + i, P.BLACK)) class Board(): def __init__(self, blank=False): self.board = [ ] # The game's current state, represented as a 2d array of Piece and Empty objects self.unmoved = list(range( 0, 32)) # The ids of all pieces that haven't moved self.whiteChecked = False # True when white's king is in check self.blackChecked = False # True when black's king is in check
def move_piece(state, selX, selY, move): st = state.copy() st.undoPositionalPieceVal(st.board[selX][selY], selX, selY) """Update total piece value if there's a capture""" if (isinstance(st.board[move.x()][move.y()], P.Piece)): if st.board[move.x()][move.y()].color == P.WHITE: st.whiteTotalPieceVal -= st.board[move.x()][move.y()].value elif st.board[move.x()][move.y()].color == P.BLACK: st.blackTotalPieceVal -= st.board[move.x()][move.y()].value st.undoPositionalPieceVal(st.board[move.x()][move.y()], move.x(), move.y()) st.board[move.x()][move.y()] = st.board[selX][selY] st.board[selX][selY] = EMPTY piece = st.board[move.x()][move.y()] #Update the piece's value st.positionalPieceVal(piece, move.x(), move.y(), updateTotal=False) if move.special == P.EN_PASSENT: adjust = -1 if (st.board[move.x()][move.y()].color == P.BLACK): adjust = 1 if st.board[move.x()][move.y() + adjust].color == P.WHITE: st.whiteTotalPieceVal -= st.board[move.x()][move.y() + adjust].value st.whitePosPieceVal -= st.board[move.x()][move.y() + adjust].value elif st.board[move.x()][move.y() + adjust].color == P.BLACK: st.blackTotalPieceVal -= st.board[move.x()][move.y() + adjust].value st.blackPosPieceVal -= st.board[move.x()][move.y() + adjust].value st.board[move.x()][move.y() + adjust] = EMPTY elif move.special == P.CASTLE: if (move.x() == 2): st.board[3][move.y()] = st.board[0][move.y()] st.board[0][move.y()] = EMPTY st.unmoved.remove(st.board[3][move.y()].ident) elif (move.x() == 6): st.board[5][move.y()] = st.board[7][move.y()] st.board[7][move.y()] = EMPTY st.unmoved.remove(st.board[5][move.y()].ident) elif (isinstance(st.board[move.x()][move.y()], P.Pawn) and ((piece.color == P.WHITE and move.y() == 7) or (piece.color == P.BLACK and move.y() == 0))): promotion = P.Queen(piece.ident, piece.color) if (piece.color == P.WHITE): st.whiteTotalPieceVal += (P.QUEEN_VAL - P.PAWN_VAL) st.whitePosPieceVal -= piece.value elif (piece.color == P.BLACK): st.blackTotalPieceVal += (P.QUEEN_VAL - P.PAWN_VAL) st.blackPosPieceVal -= piece.value st.board[move.x()][move.y()] = promotion st.positionalPieceVal(promotion, move.x(), move.y(), updateTotal=False) """Need to figure out how to let the user select the promotion""" kingId = 0 enemyKingId = 0 if (st.turn == P.WHITE): kingId = st.whiteKingId enemyKingId = st.blackKingId else: kingId = st.blackKingId enemyKingId = st.whiteKingId """Check if the moving player's King wasn't put in danger. Throw out the board if he is in danger, and indicate this by returning None""" king, kingSpace = P.searchForPiece(kingId, st.board) if ((st.turn == P.WHITE and kingSpace in P.getValidMoves(P.BLACK, st)) or (st.turn == P.BLACK and kingSpace in P.getValidMoves(P.WHITE, st))): return None if (st.passentable != None): st.passentable = None """Determining if the pawn that just moved can suffer from en-passenting""" if (isinstance(piece, P.Pawn) and (st.pieceUnmoved(piece.ident) and abs(selY - move.y()) == 2)): st.passentable = move.space st.whiteChecked = False st.blackChecked = False if (st.pieceUnmoved(piece.ident)): st.unmoved.remove(piece.ident) set_check(st) st.turn = P.swapTurn(st.turn) return st
import pytest import Board as B import Pieces as P import Logic from DecisionTree import aiSearch, endStateCheck, Node stalemate = B.Board(True) stalemate.board[3][3] = P.King(stalemate.whiteKingId, P.WHITE) stalemate.board[0][4] = P.Rook(100, P.BLACK) stalemate.board[2][0] = P.Queen(101, P.BLACK) stalemate.board[5][1] = P.Knight(102, P.BLACK) stalemate.board[7][2] = P.Rook(103, P.BLACK) stalemate.board[7][7] = P.King(stalemate.blackKingId, P.BLACK) stalemate.unmoved = [] stalemate.initializePosVals() unknownError = B.Board() unknownError = Logic.move_piece(unknownError, 4, 1, P.Move((4, 3), P.NON_CAPTURE)) unknownError = Logic.move_piece(unknownError, 6, 6, P.Move((6, 4), P.NON_CAPTURE)) unknownError = Logic.move_piece(unknownError, 3, 0, P.Move((5, 2))) unknownError = Logic.move_piece(unknownError, 5, 7, P.Move((6, 6))) unknownError = Logic.move_piece(unknownError, 5, 0, P.Move((2, 3))) unknownError = Logic.move_piece(unknownError, 0, 6, P.Move((0, 4), P.NON_CAPTURE)) unknownError = Logic.move_piece(unknownError, 5, 2, P.Move((5, 6))) unknownError.initializePosVals() crash = B.Board(True)
def make_move(self, move, is_test=False): piece_moved = self.board[move.start_row][move.start_col] if piece_moved == "..": print("something is wrong") raise NameError("Piece moved is empty") piece_captured = self.board[move.end_row][move.end_col] self.board[move.start_row][ move. start_col] = ".." # adds an empty piece to the starting row and col of the move if piece_captured != "..": # if the square where the piece wants to go has another piece self.change_cords( piece_captured, 8, 8, True ) # change the co-ordinates of the piece and mark it as being captured if piece_captured.color == "black": # appends the non-empty piece to the captured_pieces list self.black_playable_pieces.remove(piece_captured) else: self.white_playable_pieces.remove(piece_captured) self.board[move.end_row][move.end_col] = piece_moved self.change_cords(piece_moved, move.end_row, move.end_col, False) self.move_log.append(move) if move.is_pawn_promotion: # add a queen in it's place replacement_piece = p.Queen(move.end_row, move.end_col, self.board, piece_moved.color) self.board[move.end_row][move.end_col] = replacement_piece # adds the replacement piece to the playable pieces array and removes the replaced piece if replacement_piece.color == "white": self.white_playable_pieces.append(replacement_piece) self.white_playable_pieces.remove(piece_moved) else: self.black_playable_pieces.append(replacement_piece) self.black_playable_pieces.remove(piece_moved) self.change_cords(piece_moved, 8, 8, True) if move.is_enpassant == True: piece_captured = self.board[move.start_row][move.end_col] if piece_captured == "..": print("Piece captured in pawn promo is empty") self.change_cords( piece_captured, 8, 8, True ) # change the co-ordinates of the piece and mark it as being captured if piece_captured.color == "black": # appends the non-empty piece to the captured_pieces list self.black_playable_pieces.remove(piece_captured) else: self.white_playable_pieces.remove(piece_captured) self.board[move.start_row][move.end_col] = ".." move.piece_captured = piece_captured # update the enpassant square if a pawn is moved if piece_moved.name == "pawn" and abs(move.start_row - move.end_row) == 2: self.special_move_mem.enpassant_sq = ( (move.start_row + move.end_row) // 2, move.end_col) else: # reset the enpassant square self.special_move_mem.enpassant_sq = () # if move.is_castle: # if move.end_col - move.start_col == 2: # kingside castle move # new_rook = p.Rook(move.end_row, move.end_col-1, self.board, piece_moved.color) # create a new rook piece # old_rook = self.board[move.start_row][move.start_col + 3] # remove the old rook piece and reset it's coords # if piece_moved.color == "black": # self.black_playable_pieces.remove(old_rook) # self.black_playable_pieces.append(new_rook) # else: # self.white_playable_pieces.remove(old_rook) # self.white_playable_pieces.append(new_rook) # self.change_cords(old_rook, 8, 8, True) # self.board[move.start_row][move.start_col+3] = ".." # assign the square on the board as empty # self.board[move.end_row][move.end_col-1] = new_rook # update the board with the new rook # else: # queenside castle move # old_rook = self.board[move.end_row][move.start_col-4] # new_rook = p.Rook(move.start_row, move.end_col + 1, self.board, piece_moved.color) # if piece_moved.color == "black": # self.black_playable_pieces.append(new_rook) # self.black_playable_pieces.remove(old_rook) # else: # self.white_playable_pieces.append(new_rook) # self.white_playable_pieces.remove(old_rook) # self.change_cords(old_rook, 8, 8, True) # self.board[move.end_row][move.start_col-4] = ".." # assign the square on the board as empty # self.board[move.end_row][move.end_col+1] = new_rook # update the board with the new rook self.update_castle_rights(move) self.castling_log.append( CastlingRights(self.current_castle_state.white_kingside, self.current_castle_state.white_queenside, self.current_castle_state.black_kingside, self.current_castle_state.black_queenside)) if not is_test: self.white_to_move = not self.white_to_move self.is_first_move = False
def place_piece(board, i, j, piece): """ Returns True and updates the board 'board' if placing the piece 'piece' on the cell (i, j) was legal. Returns False and doesn't modify the board otherwise. """ colour = piece.colour assert (colour == board.player) # Can't place a piece on top of another if board.piece_on(i, j): return False # Can't place a piece which is not connected to the # hive board.board[i][j].append(Pieces.Queen()) connected = is_connected(board) board.board[i][j].pop() if not connected: return False # Can't place a piece with adjacent ennemy pieces, unless # it is the first move if board.movecount > 1: occupied_nghb = board.occupied_adjacent_cells(i, j) for x, y in occupied_nghb: p = board.piece_on(x, y) if p.colour != colour: return False # Must place the Queen before or at move 4 if board.movecount == 4: if not board.queens[colour]: return False # The piece must be available ! symbol = piece.symbol if not board.remaining_pieces[colour][symbol]: return False # Here, we have checked that this move was indeed legal, # so we put the piece on the board ! # First, we check that whether this is the very first move # of the game, and if it is, we set board's bounds to this # cell. if board.first_move(): board.set_bounds(i, j) board.add_piece(i, j, piece) board.remaining_pieces[piece.colour][piece.symbol] -= 1 if board.player == 1: board.movecount += 1 board.player = 1 - board.player if isinstance(piece, Pieces.Queen): board.queens[colour] = True return True
testCase2 = Logic.move_piece(testCase2, 5, 4, P.Move((5, 1))) testCase3 = B.Board() testCase3 = Logic.move_piece(testCase3, 4, 1, P.Move((4, 3), P.NON_CAPTURE)) testCase3 = Logic.move_piece(testCase3, 0, 6, P.Move((0, 4), P.NON_CAPTURE)) testCase3 = Logic.move_piece(testCase3, 3, 0, P.Move((5, 2))) testCase3 = Logic.move_piece(testCase3, 1, 6, P.Move((1, 4), P.NON_CAPTURE)) testCase3 = Logic.move_piece(testCase3, 5, 0, P.Move((2, 3))) testCase3 = Logic.move_piece(testCase3, 1, 4, P.Move((1, 3), P.NON_CAPTURE)) testCase3 = Logic.move_piece(testCase3, 5, 2, P.Move((5, 6))) testCase4 = B.Board(True) testCase4.board[0][0] = P.King(testCase4.whiteKingId, P.WHITE) testCase4.board[1][0] = P.Rook(100, P.WHITE) testCase4.board[2][0] = P.Rook(101, P.WHITE) testCase4.board[2][1] = P.Queen(102, P.BLACK) testCase4.board[7][1] = P.Pawn(103, P.WHITE) testCase4.board[0][2] = P.Pawn(104, P.WHITE) testCase4.board[1][2] = P.Knight(105, P.BLACK) testCase4.board[2][3] = P.Knight(106, P.BLACK) testCase4.board[4][5] = P.Pawn(107, P.BLACK) testCase4.board[1][6] = P.Pawn(108, P.BLACK) testCase4.board[6][6] = P.Pawn(109, P.BLACK) testCase4.board[7][6] = P.Pawn(110, P.BLACK) testCase4.board[2][7] = P.Bishop(111, P.BLACK) testCase4.board[3][7] = P.Rook(112, P.BLACK) testCase4.board[6][7] = P.King(testCase4.blackKingId, P.BLACK) testCase4.unmoved = [103, 108, 109, 110, 111] testCase4.initializePosVals()
def on_mouse_press(self, x, y, button, modifiers): if self.promotion: if button == mouse.LEFT: if 225 < y < 300: if 131.25 < x < 206.25: self.board[self.promoPawn[0]][ self.promoPawn[1]] = p.Queen( self.promoPawn[1], self.promoPawn[0], not self.move) elif 218.75 < x < 293.75: self.board[self.promoPawn[0]][ self.promoPawn[1]] = p.Rook( self.promoPawn[1], self.promoPawn[0], not self.move) elif 306.25 < x < 381.25: self.board[self.promoPawn[0]][ self.promoPawn[1]] = p.Bishop( self.promoPawn[1], self.promoPawn[0], not self.move) elif 393.75 < x < 468.75: self.board[self.promoPawn[0]][ self.promoPawn[1]] = p.Knight( self.promoPawn[1], self.promoPawn[0], not self.move) self.promoPawn = (-1, -1) self.promotion = False if not self.move: if self.bKing.NoValidMoves( self.board) and not self.bKing.InCheck(self.board): print('Stalemate!') if self.bKing.InCheck(self.board): self.bKing.danger.visible = True if self.bKing.NoValidMoves(self.board): print("Checkmate! White wins.") if self.wKing.danger.visible: if not self.wKing.InCheck(self.board): self.wKing.danger.visible = False else: if self.wKing.NoValidMoves( self.board) and not self.wKing.InCheck(self.board): print('Stalemate!') if self.wKing.InCheck(self.board): self.wKing.danger.visible = True if self.wKing.NoValidMoves(self.board): print("Checkmate! Black wins.") if self.bKing.danger.visible: if not self.bKing.InCheck(self.board): self.bKing.danger.visible = False else: if button == mouse.LEFT: boardX = x // 75 boardY = y // 75 if self.currentPos[0] < 0 and self.currentPos[1] < 0: if self.board[boardY][ boardX] is not None and self.move == self.board[ boardY][boardX].white: self.currentPos = (boardY, boardX) if self.move: ValidMoves = self.board[boardY][ boardX].GetValidMoves(self.board, self.wKing) else: ValidMoves = self.board[boardY][ boardX].GetValidMoves(self.board, self.bKing) if len(ValidMoves) == 0: self.currentPos = (-1, -1) else: for move in ValidMoves: self.validsprites[move[0]][ move[1]].visible = True elif self.board[boardY][ boardX] is not None and self.move == self.board[ boardY][boardX].white: for row in self.validsprites: for sprite in row: sprite.visible = False self.currentPos = (boardY, boardX) if self.move: ValidMoves = self.board[boardY][boardX].GetValidMoves( self.board, self.wKing) else: ValidMoves = self.board[boardY][boardX].GetValidMoves( self.board, self.bKing) if len(ValidMoves) == 0: self.currentPos = (-1, -1) else: for move in ValidMoves: self.validsprites[move[0]][move[1]].visible = True else: if self.validsprites[boardY][boardX].visible: self.board[boardY][boardX] = self.board[ self.currentPos[0]][self.currentPos[1]] self.board[self.currentPos[0]][ self.currentPos[1]].ChangeLocation( boardX, boardY, self.board) if type(self.board[self.currentPos[0]][ self.currentPos[1]]) is p.Pawn and ( boardY == 0 or boardY == 7): self.promotion = True self.promoPawn = (boardY, boardX) self.board[self.currentPos[0]][ self.currentPos[1]] = None self.currentPos = (-1, -1) if self.move: if self.bKing.NoValidMoves( self.board) and not self.bKing.InCheck( self.board): print('Stalemate!') if self.bKing.InCheck(self.board): self.bKing.danger.visible = True if self.bKing.NoValidMoves(self.board): print("Checkmate! White wins.") if self.wKing.danger.visible: if not self.wKing.InCheck(self.board): self.wKing.danger.visible = False else: if self.wKing.NoValidMoves( self.board) and not self.wKing.InCheck( self.board): print('Stalemate!') if self.wKing.InCheck(self.board): self.wKing.danger.visible = True if self.wKing.NoValidMoves(self.board): print("Checkmate! Black wins.") if self.bKing.danger.visible: if not self.bKing.InCheck(self.board): self.bKing.danger.visible = False self.move = not self.move for row in self.validsprites: for sprite in row: sprite.visible = False
def movePiece(self, sourceSquare, targetSquare, targetPieceSelection, sprites, tcount, takeAttempt): # sourceSquare - selected square # targetSquare - square where player is attempting to move # targetPieceSelection - piece or null key for target square # sprites - dictionary containing all pieces # tcount - object containing turns counter, game record, and selected piece to move # takeAttmpt - boolean whether player is attempting to take a piece or not # unique 3-letter key of selected piece to be moved sourcePieceSelection = tcount.pieceSelection # Checking legality of move moveLegality = sprites[sourcePieceSelection].isMoveLegal(self.set,targetSquare,sprites) # If standard legal move if moveLegality == True: # Checking for possible Pawn Upgrade if (targetSquare[1] == '8' and tcount.pieceSelection[0:2] == 'wp') or (targetSquare[1] == '1' and tcount.pieceSelection[0:2] == 'bp'): # Pawn Upgrade # Adding move to history moveCode = sourceSquare+targetSquare tcount.gameRecord.append(moveCode) # Updating board map self.boardMapUpdate(sourceSquare,targetSquare) # Removing pawn from board pawn = tcount.pieceSelection pawnSprite = sprites[pawn] pawnGroup = pawnSprite.tgroup pawnSprite.taken() # Setting up queen code queenCode = pawn[0] + 'q' + pawn[2] self.set[targetSquare[0]][targetSquare[1]] = queenCode Pieces.initialSetup[queenCode] = [targetSquare[0],targetSquare[1],"queen"] # Placing queen on board sprites[queenCode] = Pieces.Queen(pawnSprite.screen,pawnSprite.pos,pawnSprite.images,queenCode,pawnGroup,pawnGroup) pawnGroup.add(sprites[queenCode]) if takeAttempt == True: # Taking black piece sprites[targetPieceSelection].taken() tcount.gameRecord.append(targetPieceSelection) # Deselecting previous selection from board tcount.pieceSelection = 'null' self.squareSelection = 'null' return True else: # Adding move to history moveCode = sourceSquare+targetSquare tcount.gameRecord.append(moveCode) # Updating board map self.boardMapUpdate(sourceSquare,targetSquare) # Moving sprite sprites[tcount.pieceSelection].move(targetSquare) if takeAttempt == True: # Taking black piece sprites[targetPieceSelection].taken() tcount.gameRecord.append(targetPieceSelection) # Deselecting previous selection from board tcount.pieceSelection = 'null' self.squareSelection = 'null' return True else: specialMove = self.checkSpecialMove(sourceSquare, targetSquare, targetPieceSelection, sprites, tcount) if specialMove is True: return True else: return False
def select(self, pos, event): if self.selected_piece != None and self.selected_piece.pos != pos: for x in self.selected_piece.getAvailableMoves( self.tiles, self.pieces, self.pieces_grid, self.checkedTiles[self.selected_piece.isWhite]): if pos == x: # Move selected piece capturedPiece = self.selected_piece.move(pos, self.pieces) if capturedPiece != None: self.capturedPieces[capturedPiece.isWhite].append( capturedPiece.display) self.updateCheck(True) self.updateCheck(False) self.pieces_grid.clear() for y in self.pieces['white']: self.pieces_grid[y.pos] = y if y.name == 'Pawn' and y != self.selected_piece: y.enPassantCapturable = False for y in self.pieces['black']: self.pieces_grid[y.pos] = y if y.name == 'Pawn' and y != self.selected_piece: y.enPassantCapturable = False # self.selected_piece.pos = pos if self.selected_piece.name == 'Pawn' and pos[1] == ( 0, 7)[self.selected_piece.isWhite]: self.pieces[('black', 'white')[ self.selected_piece.isWhite]][self.pieces[( 'black', 'white')[self.selected_piece.isWhite]].index( self.selected_piece)] = Pieces.Queen( self.selected_piece.isWhite, pos) self.pieces_grid[pos] = Pieces.Queen( self.selected_piece.isWhite, pos) self.selected_piece = None self.isWhiteTurn = not self.isWhiteTurn self.gameResult = self.tryEndGame() if self.gameResult != None: print(self.gameResult) self.draw() return for x in self.pieces['white']: if x.pos == pos: if self.selected_piece != x and self.isWhiteTurn: ''' # Deselect piece if it has already been selected self.selected_piece == None else:''' # Set new selected piece # if self.selected_piece != None and self.selected_piece.isWhite == self.isWhiteTurn: self.selected_piece = x else: self.selected_piece = None for x in self.pieces['black']: if x.pos == pos: if self.selected_piece != x and not self.isWhiteTurn: ''' # Deselect piece if it has already been selected self.selected_piece == None else:''' # Set new selected piece # if self.selected_piece != None and self.selected_piece.isWhite == self.isWhiteTurn: self.selected_piece = x else: self.selected_piece = None self.draw()
def gen_queens(board: Board, wk, bk): board.white_pieces.add(Pieces.Queen(board, board.get_square( (board.size // 2 - 1, board.size - 1)), white, wk)) board.black_pieces.add(Pieces.Queen( board, board.get_square((board.size // 2 - 1, 0)), black, bk))
pCPBMoves = [ P.Move((4,2), P.NON_CAPTURE), P.Move((3,2), P.EN_PASSENT), P.Move((5,2)) ] """------------KNIGHT TESTS----------""" knightCenter = deepcopy(board) knightCenter.board[3][3] = P.Knight(0, P.WHITE) knightCenter.unmoved.remove(0) knightCenter2 = deepcopy(knightCenter) knightCenter2.board[2][1] = P.Pawn(1, P.WHITE) knightCenter2.board[5][4] = P.Knight(2, P.WHITE) knightCenter2.board[1][2] = P.Queen(3, P.BLACK) knightCenter2.board[4][1] = P.Bishop(4, P.BLACK) knightCenter2.unmoved.remove(2) knightCenter2.unmoved.remove(3) knightCenter2.unmoved.remove(4) knightCorner = deepcopy(board) knightCorner.board[0][7] = P.Knight(0, P.BLACK) knightCorner.unmoved.remove(0) knCMoves = [ P.Move((2,1)), P.Move((4,1)), P.Move((5,2)), P.Move((5,4)),
import Board import BoardUI import Pieces import Moves b = Board.Board() ui = BoardUI.BoardUI(b) b.board[10][10].append(Pieces.Spider()) b.board[11][10].append(Pieces.Ant(1)) b.board[12][10].append(Pieces.Queen(1)) b.board[10][11].append(Pieces.Beetle(1)) b.board[11][11].append(Pieces.Spider(1)) b.board[12][11].append(Pieces.Beetle(0)) b.board[10][12].append(Pieces.Grasshopper(0)) b.board[11][12].append(Pieces.Grasshopper(1)) b.board[11][13].append(Pieces.Queen(0)) b.white_queen = True b.black_queen = True b.movecount = 6 ui.render() ui.manage_all_events()