X-Git-Url: https://git.ctpug.org.za/?a=blobdiff_plain;f=tabakrolletjie%2Fobstacles.py;h=81dd9cec8d937c64a649f8067391ad095f9c92ff;hb=aeed77cd9edcf4a13c391a919a033862ff31cbdf;hp=61d4376e29da7080a71dbfcf16a38eb0ab29883a;hpb=17c77c62d4679e2002ec49a01e8a3bc39829451b;p=tabakrolletjie.git diff --git a/tabakrolletjie/obstacles.py b/tabakrolletjie/obstacles.py index 61d4376..81dd9ce 100644 --- a/tabakrolletjie/obstacles.py +++ b/tabakrolletjie/obstacles.py @@ -1,16 +1,80 @@ +""" Obstacles for light and space mould. """ + +import pygame.locals as pgl + import pymunk import pymunk.pygame_util import pygame.draw +import pygame.surface + +from .constants import (SCREEN_SIZE, OBSTACLE_CATEGORY) +from .loader import loader + +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): -class Wall(object): + def __init__(self, vertices): + super(Wall, self).__init__() + self.shapes.append(pymunk.Poly(self.body, vertices)) + self._image = None - 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 get_image(self): + if self._image is None: + self._image = pygame.surface.Surface(SCREEN_SIZE).convert_alpha() + self._image.fill((0,0,0,0)) + + for shape in self.shapes: + pygame_poly = [ + pymunk.pygame_util.to_pygame(v, self._image) for v in + shape.get_vertices()] + pygame.draw.polygon(self._image, (255, 255, 255), pygame_poly) + + wall_texture = loader.load_image("textures", "stone.png").convert_alpha() + self._image.blit(wall_texture, (0, 0), None, pgl.BLEND_RGBA_MULT) + + return self._image 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) + surface.blit(self.get_image(), (0, 0), None, 0)