view nagslang/puzzle.py @ 201:3495a2025bc6

Break puzzlers out of game_object.py
author Stefano Rivera <stefano@rivera.za.net>
date Tue, 03 Sep 2013 23:27:25 +0200
parents
children 831e4f6b3d18
line wrap: on
line source

from nagslang.constants import COLLISION_TYPE_PLAYER


class PuzzleGlue(object):
    """Glue that holds bits of a puzzle together.
    """
    def __init__(self):
        self._components = {}

    def add_component(self, name, puzzler):
        if not isinstance(puzzler, Puzzler):
            puzzler = puzzler.puzzler
        self._components[name] = puzzler
        puzzler.set_glue(self)

    def get_state_of(self, name):
        return self._components[name].get_state()


class Puzzler(object):
    """Behaviour specific to a puzzle component.
    """
    def set_glue(self, glue):
        self.glue = glue

    def set_game_object(self, game_object):
        self.game_object = game_object

    def get_state(self):
        raise NotImplementedError()


class YesPuzzler(Puzzler):
    """Yes sir, I'm always on.
    """
    def get_state(self):
        return True


class NoPuzzler(Puzzler):
    """No sir, I'm always off.
    """
    def get_state(self):
        return False


class CollidePuzzler(Puzzler):
    def __init__(self, *collision_types):
        if not collision_types:
            collision_types = (COLLISION_TYPE_PLAYER,)
        self._collision_types = collision_types

    def get_state(self):
        space = self.game_object.get_space()
        for shape in space.shape_query(self.game_object.get_shape()):
            if shape.collision_type in self._collision_types:
                return True
        return False


class StateProxyPuzzler(Puzzler):
    def __init__(self, state_source):
        self._state_source = state_source

    def get_state(self):
        return self.glue.get_state_of(self._state_source)


class StateLogicalAndPuzzler(Puzzler):
    def __init__(self, *state_sources):
        self._state_sources = state_sources

    def get_state(self):
        for state_source in self._state_sources:
            if not self.glue.get_state_of(state_source):
                return False
        return True