X-Git-Url: https://git.ctpug.org.za/?a=blobdiff_plain;f=tabakrolletjie%2Fobstacles.py;h=b368626431994464b7f7650ea60971ac471ecce0;hb=403f74bb5689f3231a1e23b500a09aee35259b57;hp=e69de29bb2d1d6434b8b29ae775ad8c2e48c5391;hpb=f3600c28cd6e96abe7c0916860b0cc56b444545f;p=tabakrolletjie.git diff --git a/tabakrolletjie/obstacles.py b/tabakrolletjie/obstacles.py index e69de29..b368626 100644 --- a/tabakrolletjie/obstacles.py +++ b/tabakrolletjie/obstacles.py @@ -0,0 +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(BaseObstacle): + + def __init__(self, vertices): + super(Wall, self).__init__() + self.shapes.append(pymunk.Poly(self.body, vertices)) + + def render(self, surface): + 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)