Пример #1
0
    def __init__(self, *args, **kwargs):
        super(ActionRoomIntervalForm, self).__init__(*args, **kwargs)

        choices = EVENT_ACTION_SET.choice_repeatedly()
        self.fields['action'] = forms.ChoiceField(choices=choices)

        localize_form_fields(self)
Пример #2
0
def query_event_action_forms(action_type, event_key):
    """
    Query forms of the event action.

    Args:
        action_type: (string) action's type
        event_key: (string) event's key
    """
    # Get action's data.
    action = EVENT_ACTION_SET.get(action_type)
    if not action:
        raise MudderyError(ERR.no_table, "Can not find action: %s" % action_type)

    # Get all forms.
    forms = []
    table_name = action.model_name
    records = general_query_mapper.filter_records(table_name, event_key=event_key)
    if records:
        for record in records:
            forms.append(query_form(table_name, id=record.id))
    else:
        forms.append(query_form(table_name))

    return {
        "forms": forms,
        "repeatedly": action.repeatedly
    }
Пример #3
0
    def __init__(self, *args, **kwargs):
        super(ActionRoomIntervalForm, self).__init__(*args, **kwargs)

        choices = EVENT_ACTION_SET.choice_repeatedly()
        self.fields['action'] = forms.ChoiceField(choices=choices)

        localize_form_fields(self)
Пример #4
0
    def func(self, args, request):
        if not args:
            raise MudderyError(ERR.missing_args, 'Missing arguments.')

        if 'action' not in args:
            raise MudderyError(ERR.missing_args, 'Missing the argument: "action".')

        if 'event' not in args:
            raise MudderyError(ERR.missing_args, 'Missing the argument: "event".')

        if 'values' not in args:
            raise MudderyError(ERR.missing_args, 'Missing the argument: "values".')

        action_type = args["action"]
        event_key = args["event"]
        values = args["values"]

        # Get action's data.
        action = EVENT_ACTION_SET.get(action_type)
        if not action:
            raise MudderyError(ERR.no_table, "Can not find action: %s" % action_type)

        table_name = action.model_name

        # Remove old records.
        data_edit.delete_records(table_name, event_key=event_key)

        # Add new data.
        for value in values:
            data_edit.save_form(value, table_name)

        return success_response("success")
Пример #5
0
    def __init__(self, *args, **kwargs):
        super(EventDataForm, self).__init__(*args, **kwargs)

        choices = EVENT_ACTION_SET.choice_all()
        self.fields['action'] = forms.ChoiceField(choices=choices)

        choices = EVENT_TRIGGER_SET.choice_all()
        self.fields['trigger_type'] = forms.ChoiceField(choices=choices)

        localize_form_fields(self)
Пример #6
0
    def __init__(self, *args, **kwargs):
        super(EventDataForm, self).__init__(*args, **kwargs)

        choices = EVENT_ACTION_SET.choice_all()
        self.fields['action'] = forms.ChoiceField(choices=choices)

        choices = EVENT_TRIGGER_SET.choice_all()
        self.fields['trigger_type'] = forms.ChoiceField(choices=choices)

        localize_form_fields(self)
Пример #7
0
    def __init__(self, *args, **kwargs):
        super(EventDataForm, self).__init__(*args, **kwargs)

        objects = EVENT_ACTION_SET.all()
        choices = [(obj, obj) for obj in objects]
        self.fields['type'] = forms.ChoiceField(choices=choices)

        objects = EVENT_TRIGGER_SET.all()
        choices = [(obj, obj) for obj in objects]
        self.fields['trigger_type'] = forms.ChoiceField(choices=choices)

        localize_form_fields(self)
Пример #8
0
def query_event_action_data(action_type, event_key):
    """
    Query an event action's data.

    Args:
        action_type: (string) action's type
        event_key: (string) event's key
    """
    # Get action's data.
    action = EVENT_ACTION_SET.get(action_type)
    if not action:
        raise MudderyError(ERR.no_table,
                           "Can not find action: %s" % action_type)

    return action.query_event_data_table(event_key)
Пример #9
0
    def at_character_kill(self, killers):
        """
        Called when a character kills others.
        This event is set on the character who is killed, and take effect on the killer!
        """
        if defines.EVENT_TRIGGER_KILL in self.events:
            for event in self.events[defines.EVENT_TRIGGER_KILL]:
                # If has kill event.
                for killer in killers:
                    if self.can_bypass(killer):
                        continue

                    if STATEMENT_HANDLER.match_condition(
                            event["condition"], killer, self.owner):
                        function = EVENT_ACTION_SET.get(event["type"])
                        if function:
                            function(event, killer)
Пример #10
0
    def at_repeat(self):
        """
        Trigger events.
        """
        if not self.obj.location:
            # The character's location is empty (maybe just login).
            return

        if self.obj.location != self.db.room:
            # The character has left the room.
            self.obj.scripts.delete(self)
            return

        # Do actions.
        func = EVENT_ACTION_SET.func(self.db.action)
        if func:
            func(self.db.event_key, self.obj, self.db.room)
Пример #11
0
    def at_character_move_in(self, character):
        """
        Called when a character moves in the event handler's owner, usually a room.
        """
        if not character:
            return

        if self.can_bypass(character):
            return

        if defines.EVENT_TRIGGER_ARRIVE in self.events:
            for event in self.events[defines.EVENT_TRIGGER_ARRIVE]:
                # If has arrive event.
                if STATEMENT_HANDLER.match_condition(event["condition"],
                                                     character, self.owner):
                    # If matches the condition.
                    function = EVENT_ACTION_SET.get(event["type"])
                    if function:
                        function(event, character)
Пример #12
0
    def at_repeat(self):
        """
        Trigger events.
        """
        if not self.obj.location:
            # The character's location is empty (maybe just login).
            return

        if self.obj.location != self.db.room:
            # The character has left the room.
            self.obj.scripts.delete(self)
            return

        # Do actions.
        if self.db.offline:
            self.db.last_trigger_time = time.time()
        func = EVENT_ACTION_SET.func(self.db.action)
        if func:
            func(self.db.event_key, self.obj, self.db.room)
Пример #13
0
def query_event_action_data(action_type, event_key):
    """
    Query an event action's data.

    Args:
        action_type: (string) action's type
        event_key: (string) event's key
    """
    # Get action's data.
    action = EVENT_ACTION_SET.get(action_type)
    if not action:
        raise MudderyError(ERR.no_table, "Can not find action: %s" % action_type)

    record = None
    try:
        record = action.get_event_data_table(event_key)
    except ObjectDoesNotExist:
        pass

    return record
Пример #14
0
def query_event_action_data(action_type, event_key):
    """
    Query an event action's data.

    Args:
        action_type: (string) action's type
        event_key: (string) event's key
    """
    # Get action's data.
    action = EVENT_ACTION_SET.get(action_type)
    if not action:
        raise MudderyError(ERR.no_table, "Can not find action: %s" % action_type)

    record = None
    try:
        record = action.get_event_data_table(event_key)
    except ObjectDoesNotExist:
        pass

    return record
Пример #15
0
    def at_start(self):
        """
        Called every time the script is started.
        """
        # The script will be unpaused when the server restarts. So pause it if the character is no online now.
        if self.db.begin_message:
            if self.obj:
                self.obj.msg(self.db.begin_message)

        # Offline intervals.
        if self.db.offline:
            last_time = self.db.last_trigger_time
            if last_time:
                current_time = time.time()
                times = int((current_time - last_time) / self.interval)
                if times > 0:
                    self.db.last_trigger_time = current_time
                    action = EVENT_ACTION_SET.get(self.db.action)
                    if action and hasattr(action, "offline_func"):
                        action.offline_func(self.db.event_key, self.obj,
                                            self.db.room, times)
Пример #16
0
    def at_character_die(self):
        """
        Called when a character is killed.
        """
        owner = self.owner

        if not owner:
            return

        if self.can_bypass(owner):
            return

        if defines.EVENT_TRIGGER_DIE in self.events:
            for event in self.events[defines.EVENT_TRIGGER_DIE]:
                #If has die event.
                if STATEMENT_HANDLER.match_condition(event["condition"], owner,
                                                     None):
                    # If matches the condition, run event on the owner.
                    function = EVENT_ACTION_SET.get(event["type"])
                    if function:
                        function(event, owner)
Пример #17
0
    def trigger(self, event_type, character, obj):
        """
        Trigger an event.

        Args:
            event_type: (string) event's type.
            character: (object) the character who trigger this event.
            obj: (object) the event object.

        Return:
            triggered: (boolean) if an event is triggered.
        """
        if not character:
            return False

        if self.can_bypass(character):
            return False

        if event_type not in self.events:
            return False

        # Get all event's of this type.
        event_list = self.events[event_type]

        candidates = [
            e for e in event_list
            if not character.is_event_closed(e["key"]) and
            STATEMENT_HANDLER.match_condition(e["condition"], character, obj)
        ]

        rand = random.random()
        for event in candidates:
            if rand < event["odds"]:
                func = EVENT_ACTION_SET.func(event["action"])
                if func:
                    func(event["key"], character, obj)
                return True
            rand -= event["odds"]
Пример #18
0
    def trigger(self, event_type, character, target):
        """
        Trigger an event.

        Return:
            triggered: (boolean) if an event is triggered.
        """
        if not character:
            return False

        if self.can_bypass(character):
            return False

        if event_type not in self.events:
            return False

        for event in self.events[event_type]:
            # Check condition.
            if STATEMENT_HANDLER.match_condition(event["condition"], character,
                                                 target):
                function = EVENT_ACTION_SET.get(event["type"])
                if function:
                    function(event, character)
Пример #19
0
    def at_action(self, character, obj):
        """
        Called when a character act to an object.
        """
        if not character:
            return True

        if self.can_bypass(character):
            return True

        triggered = False
        if defines.EVENT_TRIGGER_ACTION in self.events:
            for event in self.events[defines.EVENT_TRIGGER_ACTION]:
                # If has traverse event.
                if STATEMENT_HANDLER.match_condition(event["condition"],
                                                     character, self.owner):
                    # If matches the condition.
                    triggered = True
                    function = EVENT_ACTION_SET.get(event["type"])
                    if function:
                        function(event, character)

        return not triggered
Пример #20
0
    def at_character_traverse(self, character):
        """
        Called before a character traverses an exit.
        If returns true, the character can pass the exit, else the character can not pass the exit.
        """
        if not character:
            return True

        if self.can_bypass(character):
            return True

        triggered = False
        if defines.EVENT_TRIGGER_TRAVERSE in self.events:
            for event in self.events[defines.EVENT_TRIGGER_TRAVERSE]:
                # If has traverse event.
                if STATEMENT_HANDLER.match_condition(event["condition"],
                                                     character, self.owner):
                    # If matches the condition.
                    triggered = True
                    function = EVENT_ACTION_SET.get(event["type"])
                    if function:
                        function(event, character)

        return not triggered
Пример #21
0
    def func(self, args, request):
        if not args:
            raise MudderyError(ERR.missing_args, 'Missing arguments.')

        if 'action' not in args:
            raise MudderyError(ERR.missing_args,
                               'Missing the argument: "action".')

        if 'event' not in args:
            raise MudderyError(ERR.missing_args,
                               'Missing the argument: "event".')

        if 'values' not in args:
            raise MudderyError(ERR.missing_args,
                               'Missing the argument: "values".')

        action_type = args["action"]
        event_key = args["event"]
        values = args["values"]

        # Get action's data.
        action = EVENT_ACTION_SET.get(action_type)
        if not action:
            raise MudderyError(ERR.no_table,
                               "Can not find action: %s" % action_type)

        table_name = action.model_name

        # Remove old records.
        data_edit.delete_records(table_name, event_key=event_key)

        # Add new data.
        for value in values:
            data_edit.save_form(value, table_name)

        return success_response("success")
Пример #22
0
    def trigger(self, event_type, character, obj):
        """
        Trigger an event.

        Args:
            event_type: (string) event's type.
            character: (object) the character who trigger this event.
            obj: (object) the event object.

        Return:
            triggered: (boolean) if an event is triggered.
        """
        if not character:
            return False

        if self.can_bypass(character):
            return False

        if event_type not in self.events:
            return False

        # Get all event's of this type.
        event_list = self.events[event_type]

        candidates = [e for e in event_list
                         if not character.is_event_closed(e["key"]) and
                             STATEMENT_HANDLER.match_condition(e["condition"], character, obj)]

        rand = random.random()
        for event in candidates:
            if rand < event["odds"]:
                func = EVENT_ACTION_SET.func(event["action"])
                if func:
                    func(event["key"], character, obj)
                return True
            rand -= event["odds"]
Пример #23
0
 class Meta:
     model = EVENT_ACTION_SET.get("ACTION_GET_OBJECTS").model()
     fields = '__all__'
Пример #24
0
 class Meta:
     model = EVENT_ACTION_SET.get("ACTION_ROOM_INTERVAL").model()
     fields = '__all__'
Пример #25
0
 class Meta:
     model = EVENT_ACTION_SET.get("ACTION_MESSAGE").model()
     fields = '__all__'
Пример #26
0
class DialogueHandler(object):
    """
    The DialogueHandler maintains a pool of dialogues.
    """
    speaker_escape = re.compile(r'%[%|p|n]')

    @staticmethod
    def escape_fun(word):
        """
        Change escapes to target words.
        """
        escape_word = word.group()
        char = escape_word[1]
        if char == "%":
            return char
        else:
            return "%(" + char + ")s"

    def __init__(self):
        """
        Initialize the handler.
        """
        self.can_close_dialogue = GAME_SETTINGS.get("can_close_dialogue")
        self.single_sentence_mode = GAME_SETTINGS.get(
            "single_dialogue_sentence")
        self.dialogue_storage = {}

    def load_cache(self, dialogue):
        """
        To reduce database accesses, add a cache.
        """
        if not dialogue:
            return

        if dialogue in self.dialogue_storage:
            # already cached
            return

        # Add cache of the whole dialogue.
        self.dialogue_storage[dialogue] = {}

        # Get db model
        try:
            dialogue_record = DIALOGUES.get(dialogue)
        except Exception, e:
            return

        sentences = DIALOGUE_SENTENCES.filter(dialogue)
        if not sentences:
            return

        nexts = DIALOGUE_RELATIONS.filter(dialogue)

        dependencies = DIALOGUE_QUESTION.filter(dialogue)

        # Add db fields to data object.
        data = {}

        data["condition"] = dialogue_record.condition

        data["dependencies"] = []
        for dependency in dependencies:
            data["dependencies"].append({
                "quest": dependency.dependency,
                "type": dependency.type
            })

        data["sentences"] = []
        for sentence in sentences:
            speaker_model = self.speaker_escape.sub(self.escape_fun,
                                                    sentence.speaker)

            # get events and quests
            event_trigger = EventTrigger(None, sentence.key)
            events = event_trigger.get_events()
            provide_quest = []
            finish_quest = []
            if defines.EVENT_TRIGGER_SENTENCE in events:
                for event_info in events[defines.EVENT_TRIGGER_SENTENCE]:
                    if event_info["action"] == "ACTION_ACCEPT_QUEST":
                        action = EVENT_ACTION_SET.get(event_info["action"])
                        provide_quest.extend(
                            action.get_quests(event_info["key"]))
                    elif event_info["action"] == "ACTION_TURN_IN_QUEST":
                        action = EVENT_ACTION_SET.get(event_info["action"])
                        finish_quest.extend(
                            action.get_quests(event_info["key"]))

            data["sentences"].append({
                "key": sentence.key,
                "dialogue": dialogue,
                "ordinal": sentence.ordinal,
                "speaker_model": speaker_model,
                "icon": sentence.icon,
                "content": sentence.content,
                "event": event_trigger,
                "provide_quest": provide_quest,
                "finish_quest": finish_quest,
                "can_close": self.can_close_dialogue
            })

        # sort sentences by ordinal
        data["sentences"].sort(key=lambda x: x["ordinal"])
        count = 0
        for sentence in data["sentences"]:
            sentence["sentence"] = count
            sentence["is_last"] = False
            count += 1

        data["sentences"][-1]["is_last"] = True

        data["nexts"] = [next_one.next_dlg for next_one in nexts]

        # Add to cache.
        self.dialogue_storage[dialogue] = data
Пример #27
0
    def load_cache(self, dialogue):
        """
        To reduce database accesses, add a cache.
        """
        if not dialogue:
            return

        if dialogue in self.dialogue_storage:
            # already cached
            return

        # Add cache of the whole dialogue.
        self.dialogue_storage[dialogue] = {}

        # Get db model
        try:
            dialogue_record = DIALOGUES.get(dialogue)
        except Exception as e:
            return

        sentences = DIALOGUE_SENTENCES.filter(dialogue)
        if not sentences:
            return

        nexts = DIALOGUE_RELATIONS.filter(dialogue)

        dependencies = DIALOGUE_QUESTION.filter(dialogue)

        # Add db fields to data object.
        data = {}

        data["condition"] = dialogue_record.condition

        data["dependencies"] = []
        for dependency in dependencies:
            data["dependencies"].append({
                "quest": dependency.dependency,
                "type": dependency.type
            })

        data["sentences"] = []
        for sentence in sentences:
            speaker_model = self.speaker_escape.sub(self.escape_fun,
                                                    sentence.speaker)

            # get events and quests
            event_trigger = EventTrigger(None, sentence.key)
            events = event_trigger.get_events()
            provide_quest = []
            finish_quest = []
            if defines.EVENT_TRIGGER_SENTENCE in events:
                for event_info in events[defines.EVENT_TRIGGER_SENTENCE]:
                    if event_info["action"] == "ACTION_ACCEPT_QUEST":
                        action = EVENT_ACTION_SET.get(event_info["action"])
                        provide_quest.extend(
                            action.get_quests(event_info["key"]))
                    elif event_info["action"] == "ACTION_TURN_IN_QUEST":
                        action = EVENT_ACTION_SET.get(event_info["action"])
                        finish_quest.extend(
                            action.get_quests(event_info["key"]))

            data["sentences"].append({
                "key": sentence.key,
                "dialogue": dialogue,
                "ordinal": sentence.ordinal,
                "speaker_model": speaker_model,
                "icon": sentence.icon,
                "content": sentence.content,
                "event": event_trigger,
                "provide_quest": provide_quest,
                "finish_quest": finish_quest,
                "can_close": self.can_close_dialogue
            })

        # sort sentences by ordinal
        data["sentences"].sort(key=lambda x: x["ordinal"])
        count = 0
        for sentence in data["sentences"]:
            sentence["sentence"] = count
            sentence["is_last"] = False
            count += 1

        data["sentences"][-1]["is_last"] = True

        data["nexts"] = [next_one.next_dlg for next_one in nexts]

        # Add to cache.
        self.dialogue_storage[dialogue] = data