def create_active_piece(self): if len(self.next_piece.shape) < 1: self.active_piece = Piece(self.get_random_shape(), -1, 0) self.next_piece = Piece(self.get_random_shape(), -1, 0) else: self.active_piece = self.next_piece self.next_piece = Piece(self.get_random_shape(), -1, 0)
def move_piece(self, x1, y1, x2, y2, sym=False): """ Moving piece on a board. If x2=='c' and y2=='a' then castling. :param x1: Int. First board's coordinate of piece player want to move. :param y1: Int. Second board's coordinate of piece player want to move. :param x2: Int. First board's coordinate of square that player want to move on. :param y2: Int. Second board's coordinate of square that player want to move on. :param sym: Boolean. Declaring if this function is called in simulation (default: False). :return: Boolean. True if move has been done, or false if hasn't. """ if x2 + y2 == 'ca': return self.castling(x1, y1, self.turn) elif self._board[x1][y1].move(x2, y2, self.turn): self._board[x2][y2] = self._board[x1][y1] self._board[x1][y1] = Piece(x1, y1, self) if isinstance(self._board[x2][y2], Pawn): if (x2, y2) in self._board[x2][y2].fly: self._board[x2][y2 - 1] = Piece(x2, y2 - 1, self) if isinstance(self._board[x2][y2], Pawn) and (y2 == 0 or y2 == 7) and not sym: self.evolve(x2, y2) return True else: return False
def putPiece(self): # put the Men in their place size = self.size / 8 # size of piece put = True for i in range(3): # this for make AI's Men put = not put for j in range(self.cols): if put: id = self.create_oval(j * size + 4, i * size + 4, j * size + size - 4, i * size + size - 4, fill="black") # 4 is border if not self.is_single_player: self.tag_bind(id, "<ButtonPress-1>", self.onClick) # on click handler self.pieces[i][j] = Piece(i, j, True, id) put = not put put = False for i in range(7, 4, -1): # this for make Player's men put = not put for j in range(self.cols): if put: id = self.create_oval(j * size + 4, i * size + 4, j * size + size - 4, i * size + size - 4, fill="red") self.tag_bind(id, "<ButtonPress-1>", self.onClick) # on click handler self.pieces[i][j] = Piece(i, j, False, id) put = not put
def insert(self, text, index): if not len(text): return # Finding piece that overlaps the given index pieceIndex, pieceOffset = self.getPieceIndexAndOffset(index) current = self.pieces[pieceIndex] # Append text to added buffer added_offset = len(self.buffer) self.buffer += text self.textLength += len(text) # If insertion is at the end and the piece points to the end of the add buffer, # just increase the length if (current.inBuffer and pieceOffset == current.offset + current.length == added_offset): current.length += len(text) return # Spliting into three pieces insertPiece = [] insertPiece.append( Piece(current.inBuffer, current.offset, pieceOffset - current.offset)) insertPiece.append(Piece(True, added_offset, len(text))) insertPiece.append( Piece(current.inBuffer, pieceOffset, current.length - (pieceOffset - current.offset))) insertPiece = list(filter(lambda piece: piece.length > 0, insertPiece)) self.pieces = self.replacePieces(pieceIndex, 1, insertPiece)
def initializePieces(self): #initialize both the object stored in Mattrix for i in initialPosition: for j in initialPosition[i]: self.pieces[j[1]][j[0]] = Piece(self.surf, i, 0, j[0], j[1], self.cellSize) self.pieces[self.Row - j[1]][j[0]] = Piece( self.surf, i, 1, j[0], self.Row - j[1], self.cellSize)
def initialise_pieces(self, size): # corener pieces top_left = Piece("flat", "outside", "outside", "flat") top_right = Piece("flat", "outside", "flat", "outside") bottom_left = Piece("outside", "flat", "outside", "flat") bottom_right = Piece("outside", "flat", "outside", "flat") pieces = [top_left, top_right, bottom_left, bottom_right]
def assignCoordinates(self): for row in range(self.BOARD_ROW_SIZE): for col in range(self.BOARD_COL_SIZE): if self.board[row][col] == 'X': self.corner.addPiece(Piece("corner", col, row)) elif self.board[row][col] == 'O': self.white.addPiece(Piece("white", col, row)) elif self.board[row][col] == '@': self.black.addPiece(Piece("black", col, row))
def __init__(self, length=16): self.board = [[None for _ in range(length + 2)] for _ in range(length + 2)] for i in range(length + 2): self.board[0][i] = Piece(0, ['X'] * 4, Piece.DOWN, [-1, i - 1]) self.board[length + 1][i] = Piece(0, ['X'] * 4, Piece.DOWN, [length, i - 1]) for i in range(length): self.board[1 + i][0] = Piece(0, ['X'] * 4, Piece.DOWN, [i, -1]) self.board[1 + i][length + 1] = Piece(0, ['X'] * 4, Piece.DOWN, [i, length])
def spawnPiece(self): p = None if self.nextPieceToCome == None: p = Piece(random.randint(1, 7), datetime.timestamp(datetime.now())) else: p = self.nextPieceToCome self.nextPieceToCome = Piece(random.randint(1, 7), datetime.timestamp(datetime.now())) p.move((4, 0)) self.pieces.append(p) self.current_piece = p
def __init__(self, testBoard=None): """Creates standard starting position or custom position""" if (testBoard == None): self.blackPieces = self.getStartingBlackPieces() self.whitePieces = self.getStartingWhitePieces() self.blackKing = Piece("black", "king", 0, 4) #direct access to kings for self.whiteKing = Piece("black", "king", 7, 4) #checkmate checks else: self.blackPieces = self.makeCustonBlackPieces(testBoard) self.whitePieces = self.makeCustonWhitePieces(testBoard)
def draw(): running = True while running: for event in pygame.event.get(): if event.type == QUIT: running = False if event.type == MOUSEBUTTONDOWN: try: global boards, prev_data, prev_piece piece_data = screen_to_piece(mouse.get_pos()) # Current pos if not piece_data: print("Selected nothing") if prev_piece: draw_piece(prev_piece) prev_data = None prev_piece = None continue piece_pos, board_pos = piece_data current_board = boards[board_pos[1] + board_pos[0] * 2] current_piece = current_board.get_piece(piece_pos) if not prev_data: if not current_piece: print("Selected nothing") continue prev_data = piece_data prev_piece = current_piece draw_piece(Piece(Vector2(piece_pos), "select", Vector2(board_pos))) # draw the select else: if prev_data == piece_data or board_pos != prev_data[1] or not piece_pos: draw_piece(prev_piece) # draw the select print("2 bad") else: # TODO MAKE DIFFERENT COLOR if board_pos[0] == 0: empty_space = Piece(Vector2(prev_data[0]), "white_board", Vector2(prev_data[1])) else: empty_space = Piece(Vector2(prev_data[0]), "black_board", Vector2(prev_data[1])) draw_piece(empty_space) current_board.move_piece(prev_data[0], piece_pos) current_piece = current_board.get_piece(piece_pos) draw_piece(current_piece) # print("3d pog", current_board) prev_data = None except TypeError as E: raise E print("Cannot draw on black", E) display.flip() quit()
def __init__(self): self.board = Board() self.opponent_piece = Piece() self.piece = Piece() self.sock = Client() self.data = Data() self.sock.connect() self.addThread(self.checkMove) self.addThread(self.checkData) self.board.mainloop()
def test_adminissiblePlacementFor_false3(): board = Board(3) piece1 = Piece() piece1.attacks = MagicMock(return_value=True) board.add(piece1) piece2 = Piece() piece2.attacks = MagicMock(return_value=True) actual = board.admissiblePlacementFor(piece2) expected = False assert actual == expected
def MakeList(self, file, puzzleNum): # get all lines from input file lines = file.readlines() # split all idv input lines into lists for j in range(0, len(lines)): lines[j] = lines[j].split() if (puzzleNum == 1): startList = [None] * int(len(lines) - 1) dictionary = {} elif (puzzleNum == 2): startList = [None] * (len(lines)) startList[0] = float(lines[0][0]) dictionary = {(startList[0]): 1} elif (puzzleNum == 3): startList = [None] * (len(lines)) startList[0] = Piece(lines[0][0], int(lines[0][1]), int(lines[0][2]), int(lines[0][3]), 0) dictionary = {startList[0].getDictKey(): 1} # assign values from lines into starting list for k in range(1, len(lines)): if (puzzleNum == 1): if (k == len(lines) - 1): startList[k - 1] = int(lines[k][0]) dictionary = self.updateDictionary(dictionary, int(lines[k][0])) break startList[k - 1] = int(lines[k][0]) dictionary = self.updateDictionary(dictionary, int(lines[k][0])) elif (puzzleNum == 2): startList[k] = float(lines[k][0]) dictionary = self.updateDictionary(dictionary, float(lines[k][0])) elif (puzzleNum == 3): startList[k] = Piece(lines[k][0], int(lines[k][1]), int(lines[k][2]), int(lines[k][3]), k) dictionary = self.updateDictionary(dictionary, startList[k].getDictKey()) # Return a tuple of all important info if (puzzleNum == 1): return (startList, dictionary, int(lines[0][0])) elif (puzzleNum == 2): return (startList, dictionary, 0) elif (puzzleNum == 3): return (startList, dictionary, 0)
def delete(self, index, length): if length == 0: return if length < 0: self.delete(index + length, -length) return if index < 0: raise IndexError("Text index out of range") # Get overlapping pieces startIndex, startOffset = self.getPieceIndexAndOffset(index) stopIndex, stopOffset = self.getPieceIndexAndOffset(index + length) self.textLength -= length # If single piece, check if delete is at the start or end the piece if startIndex == stopIndex: piece = self.pieces[startIndex] if startOffset == piece.offset: piece.offset += length piece.length -= length return elif stopOffset == piece.offset + piece.length: piece.length -= length return startPiece = self.pieces[startIndex] endPiece = self.pieces[stopIndex] # Spliting into two pieces deletePieces = [] deletePieces.append( Piece(startPiece.inBuffer, startPiece.offset, startOffset - startPiece.offset)) deletePieces.append( Piece( startPiece.inBuffer, startPiece.offset, startOffset - startPiece.offset, )) deletePieces.append( Piece(endPiece.inBuffer, stopOffset, endPiece.length - (stopOffset - endPiece.offset))) deletePieces = list( filter(lambda piece: piece.length > 0, deletePieces)) delete_count = stopIndex - startIndex + 1 self.pieces = self.replacePieces(startIndex, delete_count, deletePieces)
def test(): board = Board() black_pieces = [Piece('black') for _ in range(8)] white_pieces = [Piece('white') for _ in range(8)] board.place(black_pieces.pop(), 2, 0) board.place(white_pieces.pop(), 2, 1) board.place(white_pieces.pop(), 2, 2) board.place(white_pieces.pop(), 2, 3) board.place(black_pieces.pop(), 2, 4) board.print_board() print('running flip_row') tiles = board.flip_rows(2, 0, 'p', 'y') print('flip_row done running') print(board)
def __init__(self,size = 3): ''' :param size: Defines the size of the board ''' self.size = size self.turn = 1 # Player 1 goes first self.player_1_pieces = list() for i in range(size): if i != size-1: self.player_1_pieces.append(Piece(color='black',position=(i,0))) self.player_2_pieces = list() for i in range(size): if i != 0: self.player_2_pieces.append(Piece(color='white',position=(size-1,i)))
def move(self, move): assert self[move.cord0], "%s %s" % (move, self.asFen()) newBoard = self.clone() newBoard.board.applyMove(move.move) cord0, cord1 = move.cords flag = FLAG(move.move) newBoard[cord1] = newBoard[cord0] newBoard[cord0] = None if self.color == WHITE: if flag == QUEEN_CASTLE: newBoard[Cord(D1)] = newBoard[Cord(A1)] newBoard[Cord(A1)] = None elif flag == KING_CASTLE: newBoard[Cord(F1)] = newBoard[Cord(H1)] newBoard[Cord(H1)] = None else: if flag == QUEEN_CASTLE: newBoard[Cord(D8)] = newBoard[Cord(A8)] newBoard[Cord(A8)] = None elif flag == KING_CASTLE: newBoard[Cord(F8)] = newBoard[Cord(H8)] newBoard[Cord(H8)] = None if flag in PROMOTIONS: newBoard[cord1] = Piece(self.color, PROMOTE_PIECE(flag)) elif flag == ENPASSANT: newBoard[Cord(cord1.x, cord0.y)] = None return newBoard
def newShadow(piece): global shadow_piece shadow = Piece(clock, piece=piece) shadow_sprites.add(shadow.getSprites()) shadowMove(shadow, hard_drop_key) shadow_piece = shadow
def read(file): with open(file, 'r') as f: if os.stat(file).st_size == 0: raise FileNotFoundError lines = f.readlines() B = [[None for x in range(16)] for y in range(9)] for line in lines: line = line.strip('\n') l = line.split(';') x = int(int(l[1]) / 100) y = int(int(l[2]) / 100) if l[0] == 'wall': e = Wall(x, y) e.up = to_rgb(l[3]) e.left = to_rgb(l[4]) e.down = to_rgb(l[5]) e.right = to_rgb(l[6]) e.color = to_rgb(l[7]) B[x][y] = e if l[0] == 'piece': e = Piece(x, y) e.up = to_rgb(l[3]) e.left = to_rgb(l[4]) e.down = to_rgb(l[5]) e.right = to_rgb(l[6]) if int(l[7]) == 1: e.upside = True B[x][y] = e if l[0] == 'blank': e = Blank(x, y) B[x][y] = e return B
def is_checkmate(self, colour, board, depth): if colour == 'white': opponent_possible_moves = self.get_all_moves('black') else: opponent_possible_moves = self.get_all_moves('white') player_possible_moves = self.get_all_moves(colour) king_pos = () # Gets all possible moves for each player for i in range(8): for j in range(8): piece = board.board[i][j] if piece is not None: if piece.colour == colour and piece.type == 'king': king_pos = (i, j) king = board.board[king_pos[0]][king_pos[1]] if king_pos in opponent_possible_moves: print('check') for move in king.get_moves(board, (king_pos[0], king_pos[1])): if (king_pos[0] + move[0], king_pos[1] + move[1]) not in opponent_possible_moves: return False if depth == 0: for move in player_possible_moves: test_board = Board(self.board) test_board.board[move[0]][move[1]] = Piece( 'pawn', 'white_pawn.png', colour) if not self.is_checkmate(colour, test_board, 1): return False print('can kill to escape') print(colour, 'checkmate') return True else: return False
def load(self, iFileName): dutyDataExist = os.path.isfile(iFileName) if not dutyDataExist: file = open(iFileName, 'w+') file.close() return file = open(iFileName, 'r') for line in file: if line != '\n': lineSplit = line.split(';') taskId = lineSplit[0] taskPrjCode = lineSplit[1] title = lineSplit[2] currDtyDate = datetime.datetime.now() formatDateTime = '%Y-%m-%d %H:%M:%S' startTime = datetime.datetime.strptime( currDtyDate + ' ' + lineSplit[3], formatDateTime) endTime = datetime.datetime.strptime( currDtyDate + ' ' + lineSplit[4].rstrip('\n'), formatDateTime) newTask = Task(taskPrjCode, title, taskId) newPiece = Piece(newTask, startTime, endTime) self.addPiece(newPiece) file.close()
def __init__(self, x_pos, y_pos, side_length, bgcolor): self.sprite = TileSprite(self) self.sprite.image = pygame.Surface([side_length, side_length]) self.sprite.rect = pygame.Rect(x_pos, y_pos, side_length, side_length) self.sprite.image.fill(0x444444) self.bgcolor = bgcolor pygame.draw.rect(self.sprite.image, self.bgcolor, pygame.Rect(1, 1, side_length - 2, side_length - 2)) self.contents = Piece(None)
def test_add_ok(): board = Board(3) piece = Piece() board.add(piece) assert len(board.pieces) == 1 assert piece in board.pieces
def add(self, x, y): piece = Piece(self.TURN, x, y) if self.inBounds(piece) and self.board[piece.x][piece.y] == 0: self.board[piece.x][piece.y] = piece.player self.checkWin(piece) # check for win after every piece is added self.TURN = -(self.TURN) # switch player turns return True return False # probably better to throw an exception
def populate_board(self): """ Generates a list of pieces and places them on the board. Currently make 4 students and one master for each player. Sets the master locations to the centre of each players' starting row, which are the top and bottom of the board. """ for index, num in enumerate([0, 0, 0, 0, 0, 4, 4, 4, 4, 4]): if num == 0: piece = Piece(1) else: piece = Piece(0) self.pieces.add(piece) piece.location = [num, index % 5] self.board_state[num][index % 5] = piece if index % 5 == 2: piece.master = True
def __init__(self): self.hasPiece = False self.isBlack = True self.label = "a1" self.piece = Piece() self.locX = 0 self.locY = 0 self.loc = [self.locX, self.locY]
def PlacePiece(self, playerID, pieceID, index): if pieceID == "road": if self.ValidRoadLoc(index): self.edges[index].piece = Piece(pieceID, playerID) return True # print("ERROR: INVALID PIECE LOCATION") elif pieceID == "settlement": if self.ValidSettlementLoc(index): self.vertices[index].piece = Piece(pieceID, playerID) return True # print("ERROR: INVALID PIECE LOCATION") elif pieceID == "city": if self.ValidCityLoc(index): self.vertices[index].piece = Piece(pieceID, playerID) return True # print("ERROR: INVALID PIECE LOCATION") return -1
def initialise_board(self): for row in range(self.row_count): for column in range(self.column_count): if column % 2 != 0 and row % 2 == 0 or column % 2 == 0 and row % 2 != 0: # Find black squares self.square_count = self.square_count + 1 self.checkers_board[row][column] = Square( "black", row, column, self.square_count, None, None) # Populate black squares if row < 3: self.checkers_board[row][column].piece = Piece( "black", False) # Populate black pieces if row > (self.row_count - 4): self.checkers_board[row][column].piece = Piece( "white", False) # Populate white pieces else: self.checkers_board[row][column] = Square( "white", row, column, 0, None, None) # Populate white squares
def __init__(self, piece_size, board_size): """ :param piece_size: in pixels :param board_size: in pixels """ self.shape = self._calculeBoardSize(piece_size, board_size) self.histograms = {} self.board = [[Piece(False) for i in range(self.shape[1])] for j in range(self.shape[0])] # [[Piece(False)] * self.shape[1]] * self.shape[0] # Save Pieces objects in it