diff nagslang/screens/area.py @ 100:96bdfadeb461

Cleaner direction key management.
author Jeremy Thurgood <firxen@gmail.com>
date Mon, 02 Sep 2013 12:01:25 +0200
parents c177cdc41477
children 0131e4606e1a
line wrap: on
line diff
--- a/nagslang/screens/area.py	Mon Sep 02 11:54:13 2013 +0200
+++ b/nagslang/screens/area.py	Mon Sep 02 12:01:25 2013 +0200
@@ -12,6 +12,13 @@
 
 
 class ControlKeys(object):
+    direction_keys = {
+        (0, 1): set([pygame.locals.K_UP, pygame.locals.K_w]),
+        (0, -1): set([pygame.locals.K_DOWN, pygame.locals.K_s]),
+        (-1, 0): set([pygame.locals.K_LEFT, pygame.locals.K_a]),
+        (1, 0): set([pygame.locals.K_RIGHT, pygame.locals.K_d]),
+    }
+
     def __init__(self):
         self.keys_down = set()
 
@@ -27,6 +34,14 @@
         elif ev.type == pygame.locals.KEYUP:
             self.key_up(ev.key)
 
+    def get_direction(self):
+        dx, dy = 0, 0
+        for (tx, ty), keys in self.direction_keys.iteritems():
+            if self.keys_down & keys:
+                dx += tx
+                dy += ty
+        return (dx, dy)
+
 
 class AreaScreen(Screen):
 
@@ -95,18 +110,7 @@
         surface.blit(mysurface, (0, 0), render_rect)
 
     def tick_protagonist(self):
-        dx, dy = 0, 0
-        for key, tx, ty in [
-                # Arrows
-                (pygame.locals.K_UP, 0, 1), (pygame.locals.K_DOWN, 0, -1),
-                (pygame.locals.K_LEFT, -1, 0), (pygame.locals.K_RIGHT, 1, 0),
-                # WASD
-                (pygame.locals.K_w, 0, 1), (pygame.locals.K_s, 0, -1),
-                (pygame.locals.K_a, -1, 0), (pygame.locals.K_d, 1, 0),
-        ]:
-            if key in self.keys.keys_down:
-                dx += tx
-                dy += ty
+        dx, dy = self.keys.get_direction()
         self.protagonist.set_direction(dx, dy)
 
     def tick(self, seconds):