Helper for colour conversion
authorStefano Rivera <stefano@rivera.za.net>
Sun, 11 May 2014 16:31:49 +0000 (18:31 +0200)
committerStefano Rivera <stefano@rivera.za.net>
Sun, 11 May 2014 16:31:49 +0000 (18:31 +0200)
naja/scenes/menu.py
naja/tests/test_utils.py [new file with mode: 0644]
naja/utils.py [new file with mode: 0644]
naja/widgets/text.py

index a13abcf568d6c90bd9fdc3cfdab467e5c26b62d9..771cf33318cd8b227b0a534ac9fc06939036291d 100644 (file)
@@ -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 (file)
index 0000000..79feefe
--- /dev/null
@@ -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 (file)
index 0000000..a40b841
--- /dev/null
@@ -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()
index 12df393f1ff855c8a83aa8cd520c181f5ed19984..53030c55b8ad730c4a7725f07dc1bf9c5dcf1f52 100644 (file)
@@ -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)