new Color class replacing bare hex strings, WCAG contrast ratio and relative luminance functions, allow automatic selection of more ideal contrasting colors

This commit is contained in:
Xevion
2021-01-20 23:24:48 -06:00
parent c3bb1f1fee
commit fd7cf3bdec
3 changed files with 125 additions and 14 deletions

View File

@@ -70,14 +70,20 @@ class CommandHandler:
logger.error(f'Could not process client {self.client.nickname}\'s command request.', exc_info=e)
return 'A fatal error occurred while trying to process this command.'
def reroll(self) -> str:
def reroll(self, minimum_contrast: float = 4.65) -> str:
"""
Randomly change the client's color to a different color.
"""
newColor = random.choice(constants.Colors.ALL)
newColorName = constants.Colors.ALL_NAMES[constants.Colors.ALL.index(newColor)]
i = 0
newColor = self.client.color
choices = constants.Colors.has_contrast(float(minimum_contrast))
while i < 50 and newColor == self.client.color:
newColor = random.choice(choices)
self.client.color = newColor
return f'Changed your color to {newColorName} ({newColor})'
contrast = round(constants.Colors.WHITE.contrast_ratio(newColor), 1)
return f'Changed your color to {newColor.name} ({newColor.hex}/{contrast})'
def help(self, command: str) -> Optional[str]:
"""

View File

@@ -42,7 +42,7 @@ class Client:
self.conn.send(helpers.prepare_json(
{
'type': constants.Types.USER_LIST,
'users': [{'nickname': other.nickname, 'color': other.color} for other in self.all_clients]
'users': [{'nickname': other.nickname, 'color': other.color.hex} for other in self.all_clients]
}
))
@@ -69,13 +69,13 @@ class Client:
def send_message(self, message: str) -> None:
"""Sends a string message as the server to this client."""
self.conn.send(helpers.prepare_message(
nickname='Server', message=message, color=constants.Colors.BLACK
nickname='Server', message=message, color=constants.Colors.BLACK.hex
))
def broadcast_message(self, message: str) -> None:
"""Sends a string message to all connected clients as the Server."""
prepared = helpers.prepare_message(
nickname='Server', message=message, color=constants.Colors.BLACK
nickname='Server', message=message, color=constants.Colors.BLACK.hex
)
for client in self.all_clients:
client.send(prepared)
@@ -99,7 +99,7 @@ class Client:
self.broadcast(helpers.prepare_message(
nickname=self.nickname,
message=data['content'],
color=self.color
color=self.color.hex
))
command = data['content'].strip()