如何在不再次写入整行的情况下修改我的参数?

问题描述

嗨,我正在尝试一些方法覆盖,但我不知道该怎么做。我有一个叫做 RectCreator 的类

class RectCreator:

    def __init__(self,location_x,location_y,width,height,):
        self.location_x = location_x
        self.location_y = location_y
        self.width = width
        self.height = height
  
    def creating_rect(self,display,color):
        creating_rect = pygame.Rect(self.location_x,self.location_y,self.width,self.height)
        drawing_rect = pygame.draw.rect(display,color,creating_rect,border_radius=20)
        return creating_rect,drawing_rect

这个类在一个文件中。我在 main.py 中导入了文件,我正在使用这样的类:

button_1 = RectCreator(350,350,100,100)
btn_1 = button_1.creating_rect(display_surface,blue)

在这就是我想要做的。我不知道如何更改 btn_1 的颜色而不像这样再次写入所有行:

btn_1 = button_1.creating_rect(display_surface,green) ---------------> I DONT WANT TO WRITE THAT

我尝试向类中添加一个颜色方法,并将该方法放入使用颜色的方法中。

def color(self,color):
    return color

def creating_rect(self,display):
    creating_rect = pygame.Rect(self.location_x,self.height)
    drawing_rect = pygame.draw.rect(display,self.color(),border_radius=20)
    return creating_rect,drawing_rect

那是我的解决方案,但是 self.color() 要求我提供一个参数。我想做的就是:

btn_1 = button_1.creating_rect(display_surface,blue)
**output : a blue Box that display on my apP**

btn_1.change_color(green)
**output : Now that blue Box turned to green Box**

解决方法

一旦你在屏幕上绘制了一些东西(比如一个矩形),它就会留在那里并且不会消失,直到你在同一位置绘制新的东西。例如。如果您将位置 5,12 的屏幕像素设置为绿色,则您无法在不再次与屏幕表面交互的情况下神奇地更改该位置的颜色。

因此,如果您绘制了一个蓝色矩形并且现在想要一个绿色矩形,则必须再次调用 pygame.draw.rect。改变随机变量是不够的。

你可以做的是向你的类添加一个颜色属性,并使用它来改变矩形的颜色无论如何你必须绘制每一帧(可能存在例外):

class RectCreator:

    def __init__(self,location_x,location_y,width,height,color='blue'):
        self.rect = pygame.Rect((location_x,height))
        self.color = color
  
    def draw(self,display):
        pygame.draw.rect(display,self.color,self.rect,border_radius=20)

然后,创建一个实例并在主循环中继续调用 draw。然后您可以简单地通过设置 color 属性

来更改颜色
import random
...
btn_1 = RectCreator(350,350,100,100)
...
while True:

    for e in pygame.event.get():
        if e.type == pygame.KEYDOWN:
            btn_1.color = random.choice(('blue','green','red','yellow'))

    btn_1.draw(display_surface)
    ...
    pygame.display.flip()