[docs]classColour:def__init__(self,value:int):ifnotisinstance(value,int):raiseTypeError(f"value must be an integer, not {type(value)}")ifvalue<0orvalue>0xFFFFFF:raiseValueError(f"value must be between 0 and 16777215, not {value}")self.value:int=valuedef__int__(self)->int:returnself.valuedef__str__(self)->str:returnself.to_hex()def__repr__(self)->str:returnf"<Colour value={self.value}>"def_get_byte(self,byte:int)->int:return(self.value>>(8*byte))&0xFF@propertydefr(self)->int:""" `int`: Returns the red component of the colour """returnself._get_byte(2)@propertydefg(self)->int:""" `int`: Returns the green component of the colour """returnself._get_byte(1)@propertydefb(self)->int:""" `int`: Returns the blue component of the colour """returnself._get_byte(0)
[docs]@classmethoddeffrom_rgb(cls,r:int,g:int,b:int)->Self:""" Creates a Colour object from RGB values Parameters ---------- r: `int` Red value g: `int` Green value b: `int` Blue value Returns ------- `Colour` The colour object """returncls((r<<16)+(g<<8)+b)
[docs]defto_rgb(self)->tuple[int,int,int]:""" `tuple[int, int, int]`: Returns the RGB values of the colour` """return(self.r,self.g,self.b)
[docs]@classmethoddeffrom_hex(cls,hex:str)->Self:""" Creates a Colour object from a hex string Parameters ---------- hex: `str` The hex string to convert Returns ------- `Colour` The colour object Raises ------ `ValueError` Invalid hex colour """find_hex=utils.re_hex.search(hex)ifnotfind_hex:raiseValueError(f"Invalid hex colour {hex!r}")ifhex.startswith("#"):hex=hex[1:]iflen(hex)==3:hex=hex*2returncls(int(hex[1:],16))
[docs]defto_hex(self)->str:""" `str`: Returns the hex value of the colour """returnf"#{self.value:06x}"
[docs]@classmethoddefdefault(cls)->Self:""" `Colour`: Returns the default colour (#000000, Black) """returncls(0)
[docs]@classmethoddefrandom(cls,*,seed:Optional[Any]=None)->Self:""" Creates a random colour Parameters ---------- seed: `Optional[Any]` The seed to use for the random colour to make it deterministic Returns ------- `Colour` The random colour """r=random.Random(seed)ifseedelserandomreturncls(r.randint(0,0xFFFFFF))
[docs]classColor(Colour):""" Alias for Colour """def__init__(self,value:int):super().__init__(value)def__repr__(self)->str:returnf"<Color value={self.value}>"