better eyeballs
[tabakrolletjie.git] / tabakrolletjie / obstacles.py
index 61d4376e29da7080a71dbfcf16a38eb0ab29883a..b368626431994464b7f7650ea60971ac471ecce0 100644 (file)
@@ -1,16 +1,63 @@
+""" Obstacles for light and space mould. """
+
 import pymunk
 import pymunk.pygame_util
 import pygame.draw
 
+from .constants import OBSTACLE_CATEGORY
+
+OBSTACLE_FILTER = pymunk.ShapeFilter(categories=OBSTACLE_CATEGORY)
+
+
+class ObstacleManager(object):
+    """ Manages a set of obstacles. """
+
+    def __init__(self, space, gamestate):
+        self._space = space
+        self._obstacles = [
+            BaseObstacle.load(cfg) for cfg in gamestate.station["obstacles"]]
+        for obs in self._obstacles:
+            obs.add(self._space)
+
+    def render(self, surface):
+        for obs in self._obstacles:
+            obs.render(surface)
+
+
+class BaseObstacle(object):
+    def __init__(self):
+        self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
+        self.shapes = []
+
+    def add(self, space):
+        if self.body.space is not None:
+            space.remove(self.body, *self.body.shapes)
+        for shape in self.shapes:
+            shape.filter = OBSTACLE_FILTER
+        space.add(self.body, *self.shapes)
+
+    def render(self, surface):
+        raise NotImplementedError("Obstacles should implement .render().")
+
+    @classmethod
+    def load(cls, config):
+        kw = config.copy()
+        obstacle_type = kw.pop("type")
+        [obstacle_class] = [
+            c for c in cls.__subclasses__()
+            if c.__name__.lower() == obstacle_type]
+        return obstacle_class(**kw)
+
 
-class Wall(object):
+class Wall(BaseObstacle):
 
-    def __init__(self, vertices, space):
-        body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
-        self._shape = pymunk.Poly(body, vertices)
-        space.add(self._shape)
+    def __init__(self, vertices):
+        super(Wall, self).__init__()
+        self.shapes.append(pymunk.Poly(self.body, vertices))
 
     def render(self, surface):
-        pygame_poly = [pymunk.pygame_util.to_pygame(v, surface) for v in
-                       self._shape.get_vertices()]
-        pygame.draw.polygon(surface, (0, 0, 0), pygame_poly)
+        for shape in self.shapes:
+            pygame_poly = [
+                pymunk.pygame_util.to_pygame(v, surface) for v in
+                shape.get_vertices()]
+            pygame.draw.polygon(surface, (0, 0, 0), pygame_poly)