Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Why are my class attributes not accessible from outside the class?

I am doing a chess program, but the part which is turning the x and y coordinates of the pieces on the board into x and y coordinates on the screen isn't working, as it tells me that the piece has no rect.x attribute or x attribute. The same thing happens when I try with just y.

class piece(pygame.sprite.Sprite):
    x = 0
    y = 0
    possible_moves = []
    colour = "w"

    def __init__(self, x, y, name):
        super().__init__()
        self.x = x
        self.y = y
        self.image = load_image(name)
        self.colour = name[1]
        self.rect = self.image.get_rect
        pygame.draw.rect(self.image, WHITE, [10, 10, square_size, square_size])

def set_up_pieces(piece_list):
    for p in piece_list:
        p.rect.x = p.x * square_size + board_top_left_x
        p.rect.y = (7 - p.y) * square_size + board_top_left_y
    return piece_list

This gives me an error in the second function, but I don't see why, as the x and y variables are clearly defined in the class. p is in a class inheriting from piece, but I don't think that that makes a difference as I've tried redeclaring the variables within the subclass.

class PBlock(pygame.sprite.Sprite): 
    colour = "" 
    width = 0 
    height = 0 

    def __init__(self, colour, width, height): 
        super().__init__() 
        self.image = pygame.Surface([width, height]) 
        self.image.fill(WHITE) 
        self.image.set_colorkey(WHITE) 
        pygame.draw.rect(self.image, colour, [0, 0, width, height]) 
        self.rect = self.image.get_rect() 
        self.colour = colour 
        self.width = width 
        self.height = height

for i in range(BlockNbr): 
    block = Block(BLUE, blocksize, blocksize) 
    block.rect.x = random.randrange(screen_width) 
    block.rect.y = random.randrange(screen_height) 
    block_list.add(block) 
    all_sprites_list.add(block) 

This second block of code works, and so I'm not sure why the first one doesn't.

Comments