首页 文章

从组中更改精灵矩形的颜色

提问于
浏览
1

我有一组rects,它们连续显示 . 我希望他们在点击时更改颜色,直到再次单击它们

到目前为止我有这个代码来创建精灵:

class DrawableRect(pygame.sprite.Sprite):
    def __init__(self,color,width,height,value=0):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.value = value
        self.x = 0
        self.y = 0
    def change_value(self,color,value):
        self.image.fill(color)
        self.value=value

def DrawRects(start_x, start_y, rect_spacing, colour_list):
    current_x_pos = start_x
    for rect_num in range(0,8):
        rect = DrawableRect(colour_list[rect_num], boxW, boxH)
        rect.rect.x = current_x_pos
        rect.rect.y = start_y
        current_x_pos = current_x_pos + rect.rect.width + rect_spacing
        rects.add(rect)
    rects.draw(screen)

应用程序的想法是每个矩形代表一个位,当按下它时在0和1之间交替,每个位的组成在某处显示十进制等效 .

我读到群组是无序的,因此索引不起作用,是真的吗?

1 回答

  • 0

    这里's an example I'已根据您的目的进行了修改 . 我在精灵组中有一堆精灵(彩色矩形),当我按下鼠标按钮时,我改变*与鼠标指针碰撞的任何精灵的颜色 .

    这里's the code, you'可能最感兴趣的是 change_color() 方法和 MOUSEBUTTONUP 事件处理代码 .

    import random
    import pygame
    
    screen_width, screen_height = 640, 480
    def get_random_position():
        """return a random (x,y) position in the screen"""
        return (random.randint(0, screen_width - 1),  #randint includes both endpoints.
                random.randint(0, screen_height - 1)) 
    color_list = ["red", "orange", "yellow", "green", "cyan", "blue", "blueviolet"]
    colors = [pygame.color.Color(c) for c in color_list]
    
    class PowerUp(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self)
            width, height = 64, 32
            self.image = pygame.Surface([width, height])
            self.clicked = False  # track whether we've been clicked or not
            # initialise color
            self.color = random.choice(colors)
            self.image.fill(self.color)
            # Fetch the rectangle object that has the dimensions of the image
            self.rect = self.image.get_rect()
            # then move to a random position
            self.update()
    
        def update(self):
            #move to a random position
            self.rect.center = get_random_position()
    
        def random_color(self):
            # randomise color
            self.clicked = not self.clicked
            if self.clicked:
                color = random.choice(colors)
            else:
                color = self.color
            self.image.fill(color)
    
    if __name__ == "__main__":
        pygame.init()
        screen = pygame.display.set_mode((screen_width, screen_height))
        pygame.display.set_caption('Sprite Color Switch Demo')
        clock = pygame.time.Clock() #for limiting FPS
        FPS = 60
        exit_demo = False
    
        pygame.key.set_repeat(300, 200)
    
        #create a sprite group to track the power ups.
        power_ups = pygame.sprite.Group()
        for _ in range(10):
            power_ups.add(PowerUp()) # create a new power up and add it to the group.
    
        # main loop
        while not exit_demo:
            for event in pygame.event.get():            
                if event.type == pygame.QUIT:
                    exit_demo = True
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        exit_demo = True
                    elif event.key == pygame.K_SPACE:
                        power_ups.update()
                elif event.type == pygame.MOUSEBUTTONUP:
                    # check for collision
                    for p in power_ups:
                        if p.rect.collidepoint(event.pos): # maybe use event?
                            p.random_color()
    
            screen.fill(pygame.Color("black")) # use black background
            power_ups.draw(screen)
            pygame.display.update()
            clock.tick(FPS)
        pygame.quit()
        quit()
    

    如果您有任何疑问,请告诉我 . 显然这不会对精灵进行行对齐,我想你已经掌握了这一点 . 我建议你将所有的屏幕绘图操作放在一个地方,这样你的代码就会更清晰 .

    *新颜色是从短名单中随机化的,因此有14%的可能性不会从起始颜色变化 .

相关问题