From: Stefano Rivera Date: Sun, 11 May 2014 16:31:49 +0000 (+0200) Subject: Helper for colour conversion X-Git-Tag: 0.1~412^2~1 X-Git-Url: https://git.ctpug.org.za/?a=commitdiff_plain;h=d7291141b604ffc7941074ae1adb9596c5f314ce;p=naja.git Helper for colour conversion --- diff --git a/naja/scenes/menu.py b/naja/scenes/menu.py index a13abcf..771cf33 100644 --- a/naja/scenes/menu.py +++ b/naja/scenes/menu.py @@ -14,7 +14,7 @@ class MenuScene(Scene): def __init__(self): super(MenuScene, self).__init__() self.widgets.append(TextWidget((10, 10), 'Haai', fontsize=32, - colour=(255, 255, 255))) + colour='white')) def handle_event(self, ev): if ev.type == pgl.KEYUP and ev.key in (pgl.K_q, pgl.K_ESCAPE): diff --git a/naja/tests/test_utils.py b/naja/tests/test_utils.py new file mode 100644 index 0000000..79feefe --- /dev/null +++ b/naja/tests/test_utils.py @@ -0,0 +1,19 @@ +from unittest import TestCase + +import pygame + +from naja.utils import convert_colour + + +class TestConvertColour(TestCase): + def setUp(self): + self.red = pygame.Color('red') + + def test_pass_through(self): + self.assertEqual(self.red, convert_colour(self.red)) + + def test_tuple(self): + self.assertEqual(self.red, convert_colour((255, 0, 0))) + + def test_string(self): + self.assertEqual(self.red, convert_colour('red')) diff --git a/naja/utils.py b/naja/utils.py new file mode 100644 index 0000000..a40b841 --- /dev/null +++ b/naja/utils.py @@ -0,0 +1,11 @@ +import pygame + + +def convert_colour(colour): + if isinstance(colour, pygame.Color): + return colour + if isinstance(colour, tuple): + return pygame.Color(*colour) + if isinstance(colour, basestring): + return pygame.Color(colour) + raise ValueError() diff --git a/naja/widgets/text.py b/naja/widgets/text.py index 12df393..53030c5 100644 --- a/naja/widgets/text.py +++ b/naja/widgets/text.py @@ -3,6 +3,7 @@ import pygame from naja.constants import FONT, FONT_SIZE from naja.widgets.base import Widget from naja.resources import resources +from naja.utils import convert_colour class TextWidget(Widget): @@ -13,7 +14,7 @@ class TextWidget(Widget): self.text = text self.fontname = fontname or FONT self.fontsize = (fontsize or FONT_SIZE) / 2 - self.colour = colour or (0, 0, 0) + self.colour = convert_colour(colour or (0, 0, 0)) def prepare(self): self.font = resources.get_font(self.fontname, self.fontsize)