Merge branch 'master' of ctpug.org.za:tabakrolletjie
[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 BaseObstacle(object):
13     def __init__(self):
14         self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
15         self.shapes = []
16
17     def add(self, space):
18         if self.body.space is not None:
19             space.remove(self.body, *self.body.shapes)
20         for shape in self.shapes:
21             shape.filter = OBSTACLE_FILTER
22         space.add(self.body, *self.shapes)
23
24     def render(self, surface):
25         raise NotImplementedError("Obstacles should implement .render().")
26
27     @classmethod
28     def load(cls, config):
29         kw = config.copy()
30         obstacle_type = kw.pop("type")
31         [obstacle_class] = [
32             c for c in cls.__subclasses__()
33             if c.__name__.lower() == obstacle_type]
34         return obstacle_class(**kw)
35
36
37 class Wall(BaseObstacle):
38
39     def __init__(self, vertices):
40         super(Wall, self).__init__()
41         self.shapes.append(pymunk.Poly(self.body, vertices))
42
43     def render(self, surface):
44         for shape in self.shapes:
45             pygame_poly = [
46                 pymunk.pygame_util.to_pygame(v, surface) for v in
47                 shape.get_vertices()]
48             pygame.draw.polygon(surface, (0, 0, 0), pygame_poly)