b368626431994464b7f7650ea60971ac471ecce0
[tabakrolletjie.git] / tabakrolletjie / obstacles.py
1 """ Obstacles for light and space mould. """
2
3 import pymunk
4 import pymunk.pygame_util
5 import pygame.draw
6
7 from .constants import OBSTACLE_CATEGORY
8
9 OBSTACLE_FILTER = pymunk.ShapeFilter(categories=OBSTACLE_CATEGORY)
10
11
12 class ObstacleManager(object):
13     """ Manages a set of obstacles. """
14
15     def __init__(self, space, gamestate):
16         self._space = space
17         self._obstacles = [
18             BaseObstacle.load(cfg) for cfg in gamestate.station["obstacles"]]
19         for obs in self._obstacles:
20             obs.add(self._space)
21
22     def render(self, surface):
23         for obs in self._obstacles:
24             obs.render(surface)
25
26
27 class BaseObstacle(object):
28     def __init__(self):
29         self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
30         self.shapes = []
31
32     def add(self, space):
33         if self.body.space is not None:
34             space.remove(self.body, *self.body.shapes)
35         for shape in self.shapes:
36             shape.filter = OBSTACLE_FILTER
37         space.add(self.body, *self.shapes)
38
39     def render(self, surface):
40         raise NotImplementedError("Obstacles should implement .render().")
41
42     @classmethod
43     def load(cls, config):
44         kw = config.copy()
45         obstacle_type = kw.pop("type")
46         [obstacle_class] = [
47             c for c in cls.__subclasses__()
48             if c.__name__.lower() == obstacle_type]
49         return obstacle_class(**kw)
50
51
52 class Wall(BaseObstacle):
53
54     def __init__(self, vertices):
55         super(Wall, self).__init__()
56         self.shapes.append(pymunk.Poly(self.body, vertices))
57
58     def render(self, surface):
59         for shape in self.shapes:
60             pygame_poly = [
61                 pymunk.pygame_util.to_pygame(v, surface) for v in
62                 shape.get_vertices()]
63             pygame.draw.polygon(surface, (0, 0, 0), pygame_poly)