[英]Change color of Pygame Surface
I've made a Rectangle class:我制作了一个矩形 class:
class Rectangle(pygame.sprite.Sprite):
def __init__(self, len, x, y, color):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((len, len), flags=pygame.SRCALPHA)
# self.image.set_colorkey(Constants.WHITE)
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.center = (x + len / 2, y + len / 2)
self.is_blocked = False
self.x_pos = x
self.y_pos = y
self.x = math.floor((x - Constants.PADTOPBOTTOM) / Constants.CELL_SIZE)
self.y = math.floor((y - Constants.PADLEFTRIGHT) / Constants.CELL_SIZE)
def update(self):
if self.is_blocked:
print("is update working?") # it is working.
self.image.fill(Constants.GREEN)
And when update() is called I want to change the color of the rectangle to green but it doesn't work.当调用 update() 时,我想将矩形的颜色更改为绿色,但它不起作用。 I'm new to pygame and I don't know what to do.
我是 pygame 的新手,我不知道该怎么做。
Your problem is that you keep creating new sprites every frame, so when you change the color of one Rectangle
to green, it will be covered by a white one.您的问题是您每帧都不断创建新的精灵,因此当您将一个
Rectangle
的颜色更改为绿色时,它将被白色覆盖。
You do this by calling the fill
function (which creates new Rectangle
instances) inside the drawGrid
function.为此,您可以在
drawGrid
function 中调用fill
function(创建新的Rectangle
实例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.