Beispiel #1
0
def search_for_player(entity, argument):
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    if not argument:
        log.bug("argument non è un parametro valido: %r" % argument)
        return False

    # -------------------------------------------------------------------------

    number, argument = number_argument(argument)

    counter = 1
    for player in database["players"].itervalues():
        if not player.game_request:
            continue
        if player.incognito and player.trust > entity.trust:
            continue
        if is_same(argument, player.name):
            if counter == number:
                return player
            counter += 1

    counter = 1
    for player in database["players"].itervalues():
        if not player.game_request:
            continue
        if player.incognito and player.trust > entity.trust:
            continue
        if is_prefix(argument, player.name):
            if counter == number:
                return player
            counter += 1

    # Cerca ora tra i giocatori offline, giusto per ritornare un qualcosa
    counter = 1
    for player in database["players"].itervalues():
        if player.game_request:
            continue
        if player.incognito and player.trust > entity.trust:
            continue
        if is_same(argument, player.name):
            if counter == number:
                return player
            counter += 1

    counter = 1
    for player in database["players"].itervalues():
        if player.game_request:
            continue
        if player.incognito and player.trust > entity.trust:
            continue
        if is_prefix(argument, player.name):
            if counter == number:
                return player
            counter += 1

    return None
Beispiel #2
0
def search_for_player(entity, argument):
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    if not argument:
        log.bug("argument non è un parametro valido: %r" % argument)
        return False

    # -------------------------------------------------------------------------

    number, argument = number_argument(argument)

    counter = 1
    for player in database["players"].itervalues():
        if not player.game_request:
            continue
        if player.incognito and player.trust > entity.trust:
            continue
        if is_same(argument, player.name):
            if counter == number:
                return player
            counter += 1

    counter = 1
    for player in database["players"].itervalues():
        if not player.game_request:
            continue
        if player.incognito and player.trust > entity.trust:
            continue
        if is_prefix(argument, player.name):
            if counter == number:
                return player
            counter += 1

    # Cerca ora tra i giocatori offline, giusto per ritornare un qualcosa
    counter = 1
    for player in database["players"].itervalues():
        if player.game_request:
            continue
        if player.incognito and player.trust > entity.trust:
            continue
        if is_same(argument, player.name):
            if counter == number:
                return player
            counter += 1

    counter = 1
    for player in database["players"].itervalues():
        if player.game_request:
            continue
        if player.incognito and player.trust > entity.trust:
            continue
        if is_prefix(argument, player.name):
            if counter == number:
                return player
            counter += 1

    return None
Beispiel #3
0
    def find_room(self, argument):
        if not argument:
            log.bug("argument non è un parametro valido: %r" % argument)
            return None

        # ---------------------------------------------------------------------

        number, argument = number_argument(argument)

        counter = 1
        if self.trust >= TRUST.MASTER:
            for room_code in database["rooms"]:
                if is_same(argument, room_code):
                    if counter == number:
                        return database["rooms"][room_code]
                    counter += 1

        counter = 1
        for room in database["rooms"].itervalues():
            if is_same(argument, room.get_name(looker=self)):
                if counter == number:
                    return room
                counter += 1

        # ---------------------------------------------------------------------

        counter = 1
        if self.trust >= TRUST.MASTER:
            for room_code in database["rooms"]:
                if is_prefix(argument, room_code):
                    if counter == number:
                        return database["rooms"][room_code]
                    counter += 1

        counter = 1
        for room in database["rooms"].itervalues():
            if is_prefix(argument, room.get_name(looker=self)):
                if counter == number:
                    return room
                counter += 1

        # ---------------------------------------------------------------------

        counter = 1
        if self.trust >= TRUST.MASTER:
            for room_code in database["rooms"]:
                if is_infix(argument, room_code):
                    if counter == number:
                        return database["rooms"][room_code]
                    counter += 1

        counter = 1
        for room in database["rooms"].itervalues():
            if is_infix(argument, room.get_name(looker=self)):
                if counter == number:
                    return room
                counter += 1

        return None
Beispiel #4
0
    def find_room(self, argument):
        if not argument:
            log.bug("argument non è un parametro valido: %r" % argument)
            return None

        # ---------------------------------------------------------------------

        number, argument = number_argument(argument)

        counter = 1
        if self.trust >= TRUST.MASTER:
            for room_code in database["rooms"]:
                if is_same(argument, room_code):
                    if counter == number:
                        return database["rooms"][room_code]
                    counter += 1

        counter = 1
        for room in database["rooms"].itervalues():
            if is_same(argument, room.get_name(looker=self)):
                if counter == number:
                    return room
                counter += 1

        # ---------------------------------------------------------------------

        counter = 1
        if self.trust >= TRUST.MASTER:
            for room_code in database["rooms"]:
                if is_prefix(argument, room_code):
                    if counter == number:
                        return database["rooms"][room_code]
                    counter += 1

        counter = 1
        for room in database["rooms"].itervalues():
            if is_prefix(argument, room.get_name(looker=self)):
                if counter == number:
                    return room
                counter += 1

        # ---------------------------------------------------------------------

        counter = 1
        if self.trust >= TRUST.MASTER:
            for room_code in database["rooms"]:
                if is_infix(argument, room_code):
                    if counter == number:
                        return database["rooms"][room_code]
                    counter += 1

        counter = 1
        for room in database["rooms"].itervalues():
            if is_infix(argument, room.get_name(looker=self)):
                if counter == number:
                    return room
                counter += 1

        return None
Beispiel #5
0
def find_input(arg, inputs, exact, entity=None):
    """
    Cerca l'argomento passato nella lista di input passata.
    """
    if not arg:
        log.bug("arg non è valido: %s" % arg)
        return None

    if not inputs:
        log.bug("inputs non è valido: %s" % inputs)
        return None

    # exact ha valore di verità

    # -------------------------------------------------------------------------

    # Ricerca dell'input relativo all'argomento passato
    if exact:
        if entity and entity.IS_PLAYER:
            for input in inputs:
                if not input.command:
                    continue
                if input.command.trust > entity.trust and input.command.fun_name not in entity.permissions:
                    continue
                # Viene utilizzata la clean_string invece della is_same per motivi prestazionali
                if clean_string(arg) in input.findable_words:
                    return input
        else:
            for input in inputs:
                if not input.command:
                    continue
                if entity and input.command.trust > entity.trust:
                    continue
                # Viene utilizzata la clean_string invece della is_same per motivi prestazionali
                if clean_string(arg) in input.findable_words:
                    return input

    else:
        if entity and entity.IS_PLAYER:
            for input in inputs:
                if not input.command:
                    continue
                if input.command.trust > entity.trust and input.command.fun_name not in entity.permissions:
                    continue
                if is_prefix(arg, input.findable_words):
                    return input
        else:
            for input in inputs:
                if not input.command:
                    continue
                if entity and input.command.trust > entity.trust:
                    continue
                if is_prefix(arg, input.findable_words):
                    return input

    return None
Beispiel #6
0
def find_input(arg, inputs, exact, entity=None):
    """
    Cerca l'argomento passato nella lista di input passata.
    """
    if not arg:
        log.bug("arg non è valido: %s" % arg)
        return None

    if not inputs:
        log.bug("inputs non è valido: %s" % inputs)
        return None

    # exact ha valore di verità

    # -------------------------------------------------------------------------

    # Ricerca dell'input relativo all'argomento passato
    if exact:
        if entity and entity.IS_PLAYER:
            for input in inputs:
                if not input.command:
                    continue
                if input.command.trust > entity.trust and input.command.fun_name not in entity.permissions:
                    continue
                # Viene utilizzata la clean_string invece della is_same per motivi prestazionali
                if clean_string(arg) in input.findable_words:
                    return input
        else:
            for input in inputs:
                if not input.command:
                    continue
                if entity and input.command.trust > entity.trust:
                    continue
                # Viene utilizzata la clean_string invece della is_same per motivi prestazionali
                if clean_string(arg) in input.findable_words:
                    return input

    else:
        if entity and entity.IS_PLAYER:
            for input in inputs:
                if not input.command:
                    continue
                if input.command.trust > entity.trust and input.command.fun_name not in entity.permissions:
                    continue
                if is_prefix(arg, input.findable_words):
                    return input
        else:
            for input in inputs:
                if not input.command:
                    continue
                if entity and input.command.trust > entity.trust:
                    continue
                if is_prefix(arg, input.findable_words):
                    return input

    return None
Beispiel #7
0
def before_listen_rpg_channel(listener, speaker, target, phrase, ask, exclaim,
                              behavioured):
    # Con una probabilità dell'10%
    if random.randint(1, 10) != 1:
        return

    # Continua solo se sta per parlare l'unicorno rosa
    if speaker.prototype.code != "mfdonald_mob_unicorno-rosa":
        return

    # Spezza la frase detta in più parole (o gruppi di parole tra virgolette)
    words = multiple_arguments(phrase)

    # Controlla se vi sia almeno una parola che inizi nella maniera voluta
    # tra quelle dette (occhio che lo script si attiva anche se l'unicorno dice
    # parole come 'ringhia', per evitare questo bisognerebbe utilizzare la
    # funzione is_same sempre dal modulo utility)
    if not is_prefix(("drin", "ring"), words):
        return

    # Aggiungendo casualmente qualche punto esclamativo a quello che viene detto
    to_say = "Ring!%s Ring!%s" % (random_marks(0, 3), random_marks(0, 3))
    command_say(listener, to_say)

    # Avendo anticipato l'unicorno rosa blocca quello che stava per dire
    return True
def before_listen_rpg_channel(listener, speaker, target, phrase, ask, exclaim, behavioured):
    # Con una probabilità dell'10%
    if random.randint(1, 10) != 1:
        return

    # Continua solo se sta per parlare l'unicorno rosa
    if speaker.prototype.code != "mfdonald_mob_unicorno-rosa":
        return

    # Spezza la frase detta in più parole (o gruppi di parole tra virgolette)
    words = multiple_arguments(phrase)

    # Controlla se vi sia almeno una parola che inizi nella maniera voluta
    # tra quelle dette (occhio che lo script si attiva anche se l'unicorno dice
    # parole come 'ringhia', per evitare questo bisognerebbe utilizzare la
    # funzione is_same sempre dal modulo utility)
    if not is_prefix(("drin", "ring"), words):
        return

    # Aggiungendo casualmente qualche punto esclamativo a quello che viene detto
    to_say = "Ring!%s Ring!%s" % (random_marks(0, 3), random_marks(0, 3))
    command_say(listener, to_say)

    # Avendo anticipato l'unicorno rosa blocca quello che stava per dire
    return True
Beispiel #9
0
    def get_extra(self, argument, exact=False):
        """
        Cerca un'extra particolare tramite l'argomento passato, esegue la ricerca
        in maniera esatta oppure anche in maniera prefissa.
        Questa funzione è da chiamare dai metodi get_extra delle stanze e delle
        entità.
        """
        if not argument:
            log.bug("argument non è un parametro valido: %s" % argument)
            return None

        # -------------------------------------------------------------------------

        for extra in self:
            if is_same(multiple_arguments(extra.keywords), argument):
                return extra

        # Se viene passato un argomento lungo un solo carattere allora non viene
        # eseguita la ricerca prefissa, questo per evitare che i player eseguano
        # un brute force per trovare eventuali extra nascoste (look a, look b,
        # look c, look d...)
        if not exact and len(argument) >= config.min_secret_arg_len:
            for extra in self:
                if is_prefix(argument, multiple_arguments(extra.keywords)):
                    return extra

        return None
Beispiel #10
0
def command_usedrooms(entity, argument):
    if not entity:
        log.bug("entity non un parametro è valido: %r" % entity)
        return False

    # -------------------------------------------------------------------------

    if not argument:
        syntax = get_command_syntax(entity, "command_usedrooms")
        entity.send_output(syntax, break_line=False)
        return False

    number_of_resets = 0
    arg, argument = one_argument(argument)
    try:
        number_of_resets = int(arg)
    except ValueError:
        entity.send_output("Il primo argomento dev'essere un [white]numero[close] che rappresenta la quantità di [blue]reset[close] voluti.")
        return False

    proto_room_resets_counter = {}
    for proto_room_code in database["proto_rooms"]:
        if argument and not is_prefix(argument, proto_room_code):
            continue
        reset_counter = 0
        for room_code in database["rooms"]:
            if is_prefix(proto_room_code, room_code):
                reset_counter += 1
        proto_room_resets_counter[proto_room_code] = reset_counter

    for proto_room_code, reset_counter in proto_room_resets_counter.iteritems():
        if reset_counter == number_of_resets:
            entity.send_output("%s: %s" % (proto_room_code, database["proto_rooms"][proto_room_code].name))

    if len(proto_room_resets_counter) > 0:
        entity.send_output("\n")

    plural = "a" if len(proto_room_resets_counter) == 1 else "e"
    result = "Trovat%s [white]%d[close] stanz%s prototipo resettate [white]%d[close] volte" % (
        plural, len(proto_room_resets_counter), plural, number_of_resets)
    if argument:
        result += " il cui codice è (o inizia per) [white]%s[close]" % argument
    else:
        result += "."

    entity.send_output(result)
    return True
Beispiel #11
0
def get_area_from_argument(argument, only_exact=False):
    if not argument:
        log.bug("argument non è un parametro valido: %r" % argument)
        return None

    # -------------------------------------------------------------------------

    for area in database["areas"].itervalues():
        if is_same(argument, area.code) or is_same(argument, area.name):
            return area

    if only_exact:
        return None

    for area in database["areas"].itervalues():
        if is_prefix(argument, area.code) or is_prefix(argument, area.name):
            return area

    return None
def after_listen_rpg_channel(listener, speaker, target, phrase, ask, exclaim, behavioured):
    words = multiple_arguments(phrase)
    if not is_prefix(("drin", "ring"), words):
        return

    if speaker.prototype.code != "mfdonald_mob_unicorno-rosa":
        return

    # Aggiunge casualmente un prefisso, qualche o finale e punti esclamativi
    # e di domanda finali, risponde all'unicorno rosa
    prefix = ""
    if random.randint(1, 10) == 1:
        prefix = "Ha%s " % ("." * random.randint(2, 4))
    to_say = "a %s %sHall%s?%s" % (speaker.get_numbered_keyword(looker=listener), prefix, "o" * random.randint(1, 3), random_marks(1, 1))
    # Attende qualche secondo.. dopotutto deve raggiungere il telefono!
    # Attenzione ad inserire un numero di secondi troppo alto, altrimenti
    # l'unicorno rosa potrebbe dire più spesso ring ring di quanto l'unicorno
    # azzurro possa rispondere, riempiendo così la ram di callback :P
    # Comunque in questo caso non abbiamo assolutamente questo problema
    defer_random_time(1, 3, command_say, listener, to_say)
Beispiel #13
0
def show_list_found(entity, language, inputs_type, arg):
    """
    Visualizza una lista con tutti gli input che iniziano con l'argomento.
    passato.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    if language != "it" and language != "en":
        log.bug("language non è un parametro valido: %r" % language)
        return False

    if not inputs_type:
        log.bug("inputs_type non è un parametro valido: %r" % inputs_type)
        return False

    # -------------------------------------------------------------------------

    label = _get_label_from_type(inputs_type)
    result = '''<br><table class="mud"></td></tr>[white]%s trovati che iniziano per %s:[close]</td></tr>''' % (
        label, arg)

    inputs = globals()["inputs_%s_%s" % (inputs_type, language)]
    discovered = False
    for input in inputs:
        show, command, first_word = _check_input(input, entity, inputs_type)
        if not show:
            continue
        if not is_prefix(arg, input.findable_words):
            continue
        discovered = True
        result += '''<tr><td class='command'>%-16s</td><td>%s</td></tr>''' % (
            first_word, command.mini_help)

    if not discovered:
        result += '''<tr><td>Nessuno.</td></tr>'''

    entity.send_output('''%s</table>''' % result, False)
    return True
Beispiel #14
0
def search_online_player(argument, only_exact=False):
    """
    A volte è meglio dare precedenza alla ricerca dei giocatori online al posto
    di quelli offline per comodità, poiché spesso gli admin inseriscono
    l'abbreviazione di un player correntemente online.
    """
    for player in database["players"].itervalues():
        if not player.game_request:
            continue
        if is_same(argument, player.name):
            return player

    if only_exact:
        return None

    for player in database["players"].itervalues():
        if not player.game_request:
            continue
        if is_prefix(argument, player.name):
            return player

    return None
Beispiel #15
0
def show_list_found(entity, language, inputs_type, arg):
    """
    Visualizza una lista con tutti gli input che iniziano con l'argomento.
    passato.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    if language != "it" and language != "en":
        log.bug("language non è un parametro valido: %r" % language)
        return False

    if not inputs_type:
        log.bug("inputs_type non è un parametro valido: %r" % inputs_type)
        return False

    # -------------------------------------------------------------------------

    label  = _get_label_from_type(inputs_type)
    result = '''<br><table class="mud"></td></tr>[white]%s trovati che iniziano per %s:[close]</td></tr>''' % (label, arg)

    inputs = globals()["inputs_%s_%s" % (inputs_type, language)]
    discovered = False
    for input in inputs:
        show, command, first_word = _check_input(input, entity, inputs_type)
        if not show:
            continue
        if not is_prefix(arg, input.findable_words):
            continue
        discovered = True
        result += '''<tr><td class='command'>%-16s</td><td>%s</td></tr>''' % (first_word, command.mini_help)

    if not discovered:
        result += '''<tr><td>Nessuno.</td></tr>'''

    entity.send_output('''%s</table>''' % result, False)
    return True
Beispiel #16
0
def after_listen_rpg_channel(listener, speaker, target, phrase, ask, exclaim,
                             behavioured):
    words = multiple_arguments(phrase)
    if not is_prefix(("drin", "ring"), words):
        return

    if speaker.prototype.code != "mfdonald_mob_unicorno-rosa":
        return

    # Aggiunge casualmente un prefisso, qualche o finale e punti esclamativi
    # e di domanda finali, risponde all'unicorno rosa
    prefix = ""
    if random.randint(1, 10) == 1:
        prefix = "Ha%s " % ("." * random.randint(2, 4))
    to_say = "a %s %sHall%s?%s" % (speaker.get_numbered_keyword(
        looker=listener), prefix, "o" * random.randint(1, 3), random_marks(
            1, 1))
    # Attende qualche secondo.. dopotutto deve raggiungere il telefono!
    # Attenzione ad inserire un numero di secondi troppo alto, altrimenti
    # l'unicorno rosa potrebbe dire più spesso ring ring di quanto l'unicorno
    # azzurro possa rispondere, riempiendo così la ram di callback :P
    # Comunque in questo caso non abbiamo assolutamente questo problema
    defer_random_time(1, 3, command_say, listener, to_say)
Beispiel #17
0
def command_drop(entity, argument="", verbs=VERBS, behavioured=False):
    """
    Permette di abbandonare oggetti per terra oppure posarli in un luogo preciso.
    """
    # È possibile se il comando è stato deferrato
    if not entity:
        return False

    entity = entity.split_entity(1)

    if entity.sended_inputs and is_prefix("abbandon", entity.sended_inputs[-1]):
        verbs = VERBS2

    if not argument:
        entity.send_output("Che cosa vorresti %s." % verbs["infinitive"])
        if entity.IS_PLAYER and OPTION.NEWBIE in entity.account.options:
            syntax = get_command_syntax(entity, "command_drop")
            entity.send_output(syntax, break_line=False)
        return False

    # Ricava l'eventuale quantità d'oggetti da posare
    quantity, argument = quantity_argument(argument)

    # (TD) Controllo del mental state deviato

    # Ricerca dell'oggetto nell'inventario, non viene utilizzata la extended
    target = entity.find_entity(argument, quantity=quantity, location=entity)
    if not target:
        entity.act("Non riesci a trovare nessun [white]%s[close] da poter %s." % (argument, verbs["infinitive"]), TO.ENTITY)
        entity.act("$n sembra cercare qualcosa ma senza risultato.", TO.OTHERS)
        return False

    if quantity == 0:
        quantity = target.quantity
    elif target.quantity < quantity:
        entity.act("Non puoi %s $N perché ne hai solo %d e non %d." % (verbs["infinitive"], target.quantity, quantity), TO.ENTITY, target)
        entity.act("$n sta cercando di ammucchiare un quantitativo voluto di $N per poterlo %s" % verbs["infinitive"], TO.OTHERS, target)
        entity.act("$n sta cercando di ammucchiarti per un quantitativo voluto per poterti %s" % verbs["infinitive"], TO.TARGET, target)
        return False

    if FLAG.NO_DROP in target.flags:
        if entity.trust > TRUST.MASTER:
            entity.send_to_admin("Questa sarebbe in realtà un'entità NO_DROP e non potresti lasciarla")
        else:
            entity.act("Appena cerchi di %s $N te lo ritrovi, con un balzo, in $hand." % verbs["infinitive"], TO.ENTITY, target)
            entity.act("Appena $n cerca di %s $N se lo ritrova, con un balzo, in $hand." % verbs["infinitive"], TO.OTHERS, target)
            entity.act("\nAppena $n cerca di %s gli ritorni in $hand con un balzo." % verbs["you2"], TO.TARGET, target)
            return False

    # Non permette di droppare oggetti nelle stanze con flag di NO_DROP
    if entity.location.IS_ROOM and ROOM.NO_DROP in entity.location.flags:
        if entity.trust > TRUST.MASTER:
            entity.send_to_admin("Questa sarebbe in realtà una stanza NO_DROP in cui non poter lasciar entità")
        else:
            entity.act("Appena %s $N te lo ritrovi in %hand come se una [royalblue]forza misteriosa[close] nel luogo ti impedisse quest'azione!" % verbs["you"], TO.ENTITY, target)
            entity.act("Appena $n lascia andare $N, con l'intenzione di %s, se lo ritrova in $hand come se vi fosse una [royalblue]forza misteriosa[close] nel luogo!" % verbs["noun"], TO.OTHERS, target)
            entity.act("\nAppena $n ti %s ritorni nella sua $hand grazie ad una [royalblue]forza misteriosa[close] del luogo!" % verbs["it"], TO.TARGET, target)
            return False

    # (TD) posare monete

    # (TD) argomento all, ultima cosa da supportare

    # Ricava la locazione in cui posare l'oggetto
    # (TD)
    location = entity.location

    force_return = check_trigger(entity, "before_drop", entity, target, location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(target, "before_dropped", entity, target, location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(location, "before_drop_from_location", entity, target, location, behavioured)
    if force_return:
        return True

    entity.act("%s $N in $l." % color_first_upper(verbs["you"]), TO.ENTITY, target)
    entity.act("$n %s $N in $l." % verbs["it"], TO.OTHERS, target)
    entity.act("$n ti %s in $l." % verbs["it"], TO.TARGET, target)
    if not location.IS_ROOM:
        entity.act("$n ti %s qualcosa." % verbs["it"], TO.TARGET, location)

    if FLAG.INGESTED in target.flags:
        if entity.trust >= TRUST.MASTER:
            entity.send_to_admin("%s %s anche se lo stai digerendo." % (verbs["you"], target.get_name(entity)))
        else:
            log.bug("I giocatori non dovrebbero poter manipolare oggetti ingeriti")
            entity.send_output("[cyan]Errore di digestione nel comando, gli amministratori sono stati avvertiti del problema.[close]")
            return False
        target.stop_digestion()

    target = target.from_location(quantity, use_repop=True)
    target.to_location(location)

    force_return = check_trigger(entity, "after_drop", entity, target, location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(target, "after_dropped", entity, target, location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(location, "after_drop_from_location", entity, target, location, behavioured)
    if force_return:
        return True

    return True
Beispiel #18
0
def _find_entity_handler_for_admin(entity, argument, list_to_search, number, compare_function, avoid_inventory=False, avoid_equipment=True, avoid_doors=False):
    """
    Per velocizzare la find_entity, che con parametro location passato a Null
    può arrivare a rallentamenti notevoli, è stata creata questa copia dalla
    _find_entity_handler con un check aggiuntivo che riguarda solo gli admin.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return None

    if not argument:
        log.bug("argument non è un parametro valido: %r" % argument)  # (TT) questo test potrebbe non servire
        return None

    if not list_to_search and list_to_search != []:
        log.bug("list_to_search non è valido: %r" % list_to_search)
        return None

    if number <= 0:
        log.bug("number non è un parametro valido: %r" % number)
        return None

    if not compare_function:
        log.bug("compare_function non è un parametro valido: %r" % compare_function)
        return None

    # -------------------------------------------------------------------------

    counter = 0
    for target in list_to_search:
        if avoid_inventory and len(target.wear_mode) == 0:
            continue
        if avoid_equipment and len(target.wear_mode) != 0:
            continue
        if avoid_doors and target.door_type and target.is_hinged():
            continue
        if not entity.can_see(target):
            continue

        keywords = target.get_keywords_attr(entity)
        if not keywords:
            log.bug("target %s senza keywords valide: %s" % (target.code, keywords))
            continue

        if compare_function(argument, multiple_arguments(keywords)) or is_same(argument, target.code) or is_prefix(argument + "#", target.code):
            if counter + target.quantity >= number:
                return target
            counter += target.quantity

    return None
Beispiel #19
0
def command_destroy(entity, argument="", verbs=VERBS, behavioured=False):
    # È possibile se il comando è stato deferrato
    if not entity:
        return False

    entity = entity.split_entity(1)

    if entity.sended_inputs and is_prefix("romp", entity.sended_inputs[-1]):
        verbs = VERBS2

    if not argument:
        entity.send_output("Che cosa vorresti %s?" % verbs["infinitive"])
        if entity.IS_PLAYER and OPTION.NEWBIE in entity.account.options:
            syntax = get_command_syntax(entity, "command_destroy")
            entity.send_output(syntax, destroy_line=False)
        return False

    # Solo gli oggetti animati possono utilizzare tale comando
    if entity.IS_ITEM and FLAG.CAN_DAMAGING not in entity.flags:
        entity.act("Non ti è possibile %s nulla di nulla.", TO.ENTITY)
        entity.act("$n sembra vibrare per un attimo... ma forse è stato un abbaglio.", TO.OTHERS)
        return False

    # Ricava l'eventuale quantità d'oggetti da raccogliere
    quantity, argument = quantity_argument(argument)
    arg, argument = one_argument(argument)

    target = entity.find_entity_extensively(arg, entity_tables=["items"], inventory_pos="first")
    if not target:
        target = entity.find_entity_extensively(arg, inventory_pos="first")
        if target:
            attack_translation = translate_input(entity, "attack", "en")
            javascript_code = '''javascript:parent.sendInput('%s %s');''' % (attack_translation, target.get_numbered_keyword(looker=entity))
            destroy_noun = verbs["noun"] % grammar_gender(target)
            attack_noun = ATTACK_VERBS["noun"] % grammar_gender(target)
            html_code = '''<a href="%s">%s</a>''' % (javascript_code, attack_noun)
            entity.act("$N non è un oggetto quindi non puoi %s, ma puoi sempre %s." % (destroy_noun, html_code), TO.ENTITY, target)
            entity.act("$n posa uno sguardo indagatore su $N.", TO.OTHERS, target)
            entity.act("$n posa uno sguardo indagatore su di te.", TO.TARGET, target)
        else:
            entity.act("Non riesci a trovare nessun [white]%s[close] da %s" % (arg, verbs["infinitive"]), TO.ENTITY)
            entity.act("$n cerca qualcosa che però non trova.", TO.OTHERS)
        return False

    # (TD) resistenza al comando se charmati

    # (TD) skill di forza bruta

    if quantity == 0:
        quantity = target.quantity
    elif target.quantity < quantity:
        entity.act("Non puoi %s $N perché ve ne sono solo %d e non %d." % (verbs["infinitive"], target.quantity, quantity), TO.ENTITY, target)
        entity.act("$n sta cercando di ammucchiare un quantitativo voluto di $N per poterlo %s" % verbs["infinitive"], TO.OTHERS, target)
        entity.act("$n sta cercando di ammucchiarti per un quantitativo voluto per %s" % ["you2"], TO.TARGET, target)
        return False

    # In questa maniera crea l'entità finale che verrà manipolata dai trigger
    # in maniera omogenea senza dover attendere la chiamata della from_location
    target = target.split_entity(quantity)

    force_return = check_trigger(entity, "before_destroy", entity, target, behavioured)
    if force_return:
        return True
    force_return = check_trigger(target, "before_broken", entity, target, behavioured)
    if force_return:
        return True

    damage = damage_target(entity, target)
    index, dam_verb_you, dam_verb_it = get_destroy_verbs(damage)

    if target.life <= 0:
        end_destroy(entity, target, verbs, behavioured)
    else:
        messages = {
            "entity" : "%s $N." % dam_verb_you,
            "others" : "$n %s $N." % dam_verb_it,
            "target" : "$n ti %s." % dam_verb_it}
        send_destroy_messages(messages, "start_destroy", entity, target, verbs)
        if index != 0:
            entity.action_in_progress = ActionInProgress(DESTROY_SECONDS, continue_destroy, stop_destroy, entity, target, verbs, behavioured)

    return True
Beispiel #20
0
def command_get(entity, argument="", verbs=VERBS, behavioured=False):
    # È possibile se il comando è stato deferrato
    if not entity:
        return False

    entity = entity.split_entity(1)

    # (TD) Fare altrimenti il passaggio d'argomento verboso per il get e take,
    # creando il command_take?
    if entity.sended_inputs and is_prefix("racco", entity.sended_inputs[-1]):
        verbs = VERBS2

    if not argument:
        entity.send_output("Che cosa vorresti %s?" % verbs["infinitive"])
        if entity.IS_PLAYER and OPTION.NEWBIE in entity.account.options:
            syntax = get_command_syntax(entity, "command_get")
            entity.send_output(syntax, break_line=False)
        return False

    original_argument = argument

    # Ricava l'eventuale quantità d'oggetti da raccogliere
    quantity, argument = quantity_argument(argument)
    arg1, argument = one_argument(argument)

    # (TD) Controllo sul mental state dell'entità

    # Rimuove l'eventuali parole opzionali
    from_descr = ""
    if argument and is_prefix(argument, ("da ", "from ")):
        from_descr = "da"
        dummy_arg2, argument = one_argument(argument)

    if argument:
        location = entity.find_entity_extensively(argument, quantity=quantity)
        # (TD) sperimentale, utilizzarlo in altri comandi se va bene
        # Qui si cerca di risolvere il parsing di un eventuale argomento di
        # questo tipo: prendi camicia a tunica cassa
        if not location:
            arg1, argument = reverse_one_argument(original_argument)
            if is_number(arg1):
                quantity = int(arg1)
                arg1, argument = one_argument(argument)
            location = entity.find_entity_extensively(argument, quantity=quantity)
        if not from_descr:
            from_descr = "su"  # (bb)
    else:
        location = entity.location
        if entity.location.IS_ROOM:
            if not from_descr:
                from_descr = "in"
        else:
            if not from_descr:
                from_descr = "da"

    if not location or (location.is_secret_door() and argument and len(argument) < config.min_secret_arg_len):
        entity.act("Non riesci a trovare nessun [white]%s[close] da cui %s [white]%s[close]." % (argument, verbs["infinitive"], arg1), TO.ENTITY)
        entity.act("$n sta cercando di %s qualcosa dentro qualcos'altro, ma senza molto successo." % verbs["infinitive"], TO.OTHERS)
        return False

    if not location.IS_ROOM and location.container_type and CONTAINER.CLOSED in location.container_type.flags:
        execution_result = False
        if entity.IS_PLAYER and entity.account and OPTION.AUTO_OPEN in entity.account.options:
            execution_result = command_open(entity, location.get_numbered_keyword(looker=entity))
        if not execution_result:
            entity.act("Cerchi di %s %s da $N ma l$O trovi chius$O." % (verbs["infinitive"], arg1), TO.ENTITY, location)
            entity.act("$n cerca di %s %s da $N ma l$O trova chius$O." % (verbs["infinitive"], arg1), TO.OTHERS, location)
            entity.act("$n cerca di %s %s ma ti trova chius$O." % (verbs["you2"], arg1), TO.TARGET, location)
            return False

    if argument:
        avoid_equipment = True
        if location.IS_ITEM:
            avoid_equipment = False
        target = entity.find_entity(arg1, location=location, avoid_equipment=avoid_equipment)
    else:
        target = entity.find_entity_extensively(arg1, inventory_pos="last")

    if ((location.IS_ACTOR and not location.container_type and entity.location != location)
    or (not target and location.IS_ITEM and not location.container_type)
    or (target and location.IS_ITEM and not location.container_type and len(target.wear_mode) <= 0)):
        if entity.trust > TRUST.PLAYER:
            entity.send_to_admin("Anche se non è un contenitore lo puoi manipolare comunque")
        else:
            entity.act("Non riesci a %s %s da $N." % (verbs["infinitive"], arg1), TO.ENTITY, location)
            entity.act("Non riesce a %s nulla da $N." % verbs["infinitive"], TO.OTHERS, location)
            entity.act("Non riesce a %s nulla da te." % verbs["infinitive"], TO.TARGET, location)
            return False

    if not target or (target.is_secret_door() and len(arg1) < config.min_secret_arg_len):
        if location.IS_ROOM:
            entity.act("Non riesci a trovare nessun [white]%s[close] da %s." % (arg1, verbs["infinitive"]), TO.ENTITY)
            entity.act("$n sta cercando qualcosa, ma senza molto successo.", TO.OTHERS)
        else:
            entity.act("Non riesci a trovare nessun [white]%s[close] da %s %s $N." % (arg1, verbs["infinitive"], from_descr), TO.ENTITY, location)
            entity.act("$n sta cercando qualcosa dentro $N, ma senza molto successo.", TO.OTHERS, location)
        return False

    if quantity == 0:
        quantity = target.quantity
    elif target.quantity < quantity:
        entity.act("Non puoi %s $N perché ve ne sono solo %d e non %d." % (verbs["infinitive"], target.quantity, quantity), TO.ENTITY, target)
        entity.act("$n sta cercando di ammucchiare un quantitativo voluto di $N per poterlo %s" % verbs["infinitive"], TO.OTHERS, target)
        entity.act("$n sta cercando di ammucchiarti per un quantitativo voluto per poterti %s" % verbs["infinitive"], TO.TARGET, target)
        return False

    # Di default si raccoglie da terra
    if not location:
        location = entity.location

    force_return = check_trigger(target, "before_try_to_get", entity, target, location, behavioured)
    if force_return:
        return True

    if target == entity:
        entity.act("Cerchi di %s da sol$o... impossibile!" % verbs["you2"], TO.ENTITY)
        entity.act("$n cerca di %s da sol$o... sarà dura che ce la faccia!" % verbs["self"], TO.OTHERS)
        return False

    if target.location == entity:
        entity.act("Cerchi di %s $N ma ti accorgi di averl$O già con te." % verbs["infinitive"], TO.ENTITY, target)
        entity.act("$n cerca di %s $N ma si accorge di averl$O già con sé." % verbs["infinitive"], TO.OTHERS, target)
        return False

    # Controlla che il peso ((TD) e lo spazio) attualmente trasportato dall'entità
    # permetta o meno il get
    # (TD) il bard aveva anche il can_carry_number
    if not entity.can_carry_target(target, quantity=quantity):
        if entity.trust > TRUST.PLAYER:
            entity.send_to_admin("Riesci comunque a %s %s anche se è troppo pesante per te." % (
                verbs["infinitive"], target.get_name(entity)))
        else:
            entity.act("Non puoi %s $N, non riesci a portare con te tutto quel peso." % verbs["infinitive"], TO.ENTITY, target)
            entity.act("$n non può %s $N, non riesce a portare con sé tutto quel peso." % verbs["infinitive"], TO.OTHERS, target)
            entity.act("$n non può %s, non riesce a portare con sé tutto il tuo peso." % verbs["you2"], TO.TARGET, target)
            return False

    # Evita di far rubare a meno che non ci si trovi proprio nell'inventario della vittima
    if location.IS_PLAYER and location != entity.location:
        if entity.trust > TRUST.PLAYER:
            entity.send_to_admin("Raccogli da un giocatore anche se non potresti")
        else:
            entity.act("Cerchi di %s qualcosa da $a, ma ti fermi prima di compiere un [gray]furto[close]." % verbs["infinitive"], TO.ENTITY, target, location)
            entity.act("$n cerca di %s qualcosa da $N, tuttavia si ferma prima di compiere un [gray]furto[close]." % verbs["infinitive"], TO.OTHERS, location)
            entity.act("\n$n cerca di %s qualcosa da $a, ma si ferma prima di compiere un [gray]furto[close]." % verbs["you2"], TO.TARGET, target, location)
            entity.act("\n$n cerca di %s qualcosa, tuttavia si ferma prima di compiere un [gray]furto[close]." % verbs["you2"], TO.TARGET, location, target)
            return False

    # Se non è passato del tempo il cadavere non è lootabile
    if target.corpse_type and target.corpse_type.was_player and target.corpse_type.decomposition_rpg_hours <= len(CORPSE_DESCRS):
        if entity.trust > TRUST.PLAYER:
            entity.send_to_admin("Raccogli da un cadavere di giocatore anche se non potresti")
        else:
            entity.act("Cerchi di %s qualcosa da $a, ma ti fermi prima di compiere un [gray]furto[close]." % verbs["infinitive"], TO.ENTITY, target, location)
            entity.act("$n cerca di %s qualcosa da $N, tuttavia si ferma prima di compiere un [gray]furto[close]." % verbs["infinitive"], TO.OTHERS, location)
            entity.act("\n$n cerca di %s qualcosa da $a, ma si ferma prima di compiere un [gray]furto[close]." % verbs["you2"], TO.TARGET, target, location)
            entity.act("\n$n cerca di %s qualcosa, tuttavia si ferma prima di compiere un [gray]furto[close]." % verbs["you2"], TO.TARGET, location, target)
            return False

    if FLAG.NO_GET in target.flags:
        if entity.trust > TRUST.PLAYER:
            entity.send_to_admin("Raccogli l'oggetto anche se è NO_GET")
        else:
            entity.act("Cerchi di $a $N... ma [darkgray]senza successo[close].", TO.ENTITY, target, verbs["infinitive"])
            entity.act("$n cerca di $a $N... [darkgray]senza successo[close].", TO.OTHERS, target, verbs["infinitive"])
            entity.act("$n cerca di $a... [darkgray]senza successo[close].", TO.TARGET, target, verbs["you2"])
            if not location.IS_ROOM:
                entity.act("$n cerca di $a $N da te... [darkgray]senza successo[close].", TO.TARGET, target, verbs["infinitive"])
            return False

    if location.IS_ROOM and ROOM.NO_GET in location.flags:
        if entity.trust > TRUST.PLAYER:
            entity.send_to_admin("Raccogli l'oggetto anche se la stanza è NO_GET")
        else:
            entity.act("Cerchi di %s $N, tuttavia una [royalblue]forza misteriosa[close] del luogo respinge la tua $hand." % verbs["infinitive"], TO.ENTITY, target)
            entity.act("$n cerca di %s $N, tuttavia una [royalblue]forza misteriosa[close] del luogo sembra respingere la sua $hand." % verbs["infinitive"], TO.OTHERS, target)
            entity.act("\n$n cerca di %s, tuttavia una [royalblue]forza misteriosa[close] del luogo sembra respingere la sua $hand." % verbs["you2"], TO.TARGET, target)
            return False

    if not location.IS_ROOM and location == entity.location and len(target.wear_mode) > 0:
        entity.act("Stai per %s $N svestendo $a, ma poi ti fermi, non è proprio il caso." % verbs["infinitive"], TO.ENTITY, target, location)
        entity.act("$ sembra voler %s $N svestendo $a, ma poi si ferma." % verbs["infinitive"], TO.OTHERS, target, location)
        entity.act("$n sembra voler %s $N da te, ma poi si ferma." % verbs["infinitive"], TO.TARGET, target, location)
        return False

    if FLAG.BURIED in target.flags:
        if entity.trust > TRUST.PLAYER:
            entity.send_to_admin("Raccogli l'oggetto anche se è BURIED rimuovendo tale flag")
        else:
            log.bug("Oggetto buried gettabile da un giocatore senza trust: %s" % target.code)
            return False

    # Ricava l'attributo corretto
    if target.IS_PLAYER:
        if entity.trust > TRUST.PLAYER:
            entity.send_to_admin("Raccogli il giocatore anche se non potresti")
        else:
            entity.act("Cerchi di %s $N, ma ti fermi per [indianred]rispetto[close] nei suoi confronti." % verbs["infinitive"], TO.ENTITY, target)
            entity.act("$n cerca di %s $N, tuttavia si ferma per [indianred]rispetto[close] nei suoi confronti." % verbs["infinitive"], TO.OTHERS, target)
            entity.act("\n$n cerca di %s, tuttavia si ferma per [indianred]rispetto[close] nei tuoi confronti." % verbs["you2"], TO.TARGET, target)
            if not location.IS_ROOM:
                entity.act("$n cerca di %s $a da te, tuttavia si ferma per [indianred]rispetto[close] nei tuoi e suoi confronti." % verbs["infinitive"], TO.TARGET, location, target)
            return False

    # Nel caso l'oggetto era addosso ad un altro oggetto (è meglio tenere
    # queste righe di codice prima del check del trigger before_get visto
    # che a volte negli script vengono modificate le flag di wear)
    if len(target.wear_mode) > 0:
        target.wear_mode.clear()
        target.under_weared = None

    # In questa maniera crea l'entità finale che verrà manipolata dai trigger
    # in maniera omogenea senza dover attendere la chiamata della from_location
    target = target.split_entity(quantity)

    force_return = check_trigger(entity, "before_get", entity, target, location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(target, "before_getted", entity, target, location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(location, "before_get_from_location", entity, target, location, behavioured)
    if force_return:
        return True

    if quantity <= 1:
        entity.act("%s $N da $a." % color_first_upper(verbs["you"]), TO.ENTITY, target, location)
        entity.act("$n %s $N da $a." % verbs["it"], TO.OTHERS, target, location)
        entity.act("$n ti %s da $a." % verbs["it"], TO.TARGET, target, location)
    else:
        entity.act("%s $N, per una quantità di %d, da $a." % (color_first_upper(verbs["you"]), quantity), TO.ENTITY, target, location)
        entity.act("$n %s $N, per una quantità di %d, da $a." % (verbs["it"], quantity), TO.OTHERS, target, location)
        entity.act("$n ti %s, per una quantità di %d, da $a." % (verbs["it"], quantity), TO.TARGET, target, location)
    if not location.IS_ROOM:
        entity.act("$n ti %s qualcosa." % verbs["it"], TO.TARGET, location)

    target = target.from_location(quantity)
    target.to_location(entity)

    # Nel caso sia un seme e fosse stato un admin a gettarlo:
    target.flags -= FLAG.BURIED
    # (TT) forse questo pezzo di codice andrebbe meglio in from_location
    if target.seed_type:
        target.seed_type.stop_growth()
    if target.plant_type:
        target.plant_type.stop_growth()

    # Se il comando get è stato eseguito tramite un behaviour allora l'oggetto
    # raccolto ha una probabilità di essere purificato, queste righe di codice
    # devono trovarsi DOPO la chiamata alla to_location, che esegue una pulizia
    # della deferred relativa alla purificazione
    if behavioured:
        target.start_purification(config.purification_rpg_hours)

    force_return = check_trigger(entity, "after_get", entity, target, location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(target, "after_getted", entity, target, location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(location, "after_get_from_location", entity, target, location, behavioured)
    if force_return:
        return True

    return True
Beispiel #21
0
def get_help(entity, argument):
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    if not argument:
        log.bug("argument non è un parametro valido: %r" % argument)
        return ""

    # -------------------------------------------------------------------------

    # Se argument è formato da più parole erroneamente separate da più spazi
    # allora li converte in un'unico spazio
    if "  " in argument:
        argument = " ".join(argument.split())

    # Cerca prima tra gli help della propria lingua in maniera esatta
    if entity.IS_PLAYER or OPTION.ITALIAN in entity.account.options:
        for help in database["helps"].itervalues():
            if not help.text and help.admin_text and entity.trust == TRUST.PLAYER:
                continue
            if is_same(argument, multiple_arguments(help.italian_keywords)):
                return help
    else:
        for help in database["helps"].itervalues():
            if not help.text and help.admin_text and entity.trust == TRUST.PLAYER:
                continue
            if is_same(argument, multiple_arguments(help.english_keywords)):
                return help

    # Cerca poi tra gli help della propria lingua in maniera prefissa
    if entity.IS_PLAYER or OPTION.ITALIAN in entity.account.options:
        for help in database["helps"].itervalues():
            if not help.text and help.admin_text and entity.trust == TRUST.PLAYER:
                continue
            if is_prefix(argument, multiple_arguments(help.italian_keywords)):
                return help
    else:
        for help in database["helps"].itervalues():
            if not help.text and help.admin_text and entity.trust == TRUST.PLAYER:
                continue
            if is_prefix(argument, multiple_arguments(help.english_keywords)):
                return help

    # Cerca poi tra gli help della lingua secondaria in maniera esatta
    if entity.IS_PLAYER or OPTION.ITALIAN in entity.account.options:
        for help in database["helps"].itervalues():
            if not help.text and help.admin_text and entity.trust == TRUST.PLAYER:
                continue
            if is_same(argument, multiple_arguments(help.english_keywords)):
                return help
    else:
        for help in database["helps"].itervalues():
            if not help.text and help.admin_text and entity.trust == TRUST.PLAYER:
                continue
            if is_same(argument, multiple_arguments(help.italian_keywords)):
                return help

    # Cerca poi tra gli help della lingua secondaria in maniera prefissa
    if entity.IS_PLAYER or OPTION.ITALIAN in entity.account.options:
        for help in database["helps"].itervalues():
            if not help.text and help.admin_text and entity.trust == TRUST.PLAYER:
                continue
            if is_prefix(argument, multiple_arguments(help.english_keywords)):
                return help
    else:
        for help in database["helps"].itervalues():
            if not help.text and help.admin_text and entity.trust == TRUST.PLAYER:
                continue
            if is_prefix(argument, multiple_arguments(help.italian_keywords)):
                return help

    return None
Beispiel #22
0
def command_drop(entity, argument="", verbs=VERBS, behavioured=False):
    """
    Permette di abbandonare oggetti per terra oppure posarli in un luogo preciso.
    """
    # È possibile se il comando è stato deferrato
    if not entity:
        return False

    entity = entity.split_entity(1)

    if entity.sended_inputs and is_prefix("abbandon",
                                          entity.sended_inputs[-1]):
        verbs = VERBS2

    if not argument:
        entity.send_output("Che cosa vorresti %s." % verbs["infinitive"])
        if entity.IS_PLAYER and OPTION.NEWBIE in entity.account.options:
            syntax = get_command_syntax(entity, "command_drop")
            entity.send_output(syntax, break_line=False)
        return False

    # Ricava l'eventuale quantità d'oggetti da posare
    quantity, argument = quantity_argument(argument)

    # (TD) Controllo del mental state deviato

    # Ricerca dell'oggetto nell'inventario, non viene utilizzata la extended
    target = entity.find_entity(argument, quantity=quantity, location=entity)
    if not target:
        entity.act(
            "Non riesci a trovare nessun [white]%s[close] da poter %s." %
            (argument, verbs["infinitive"]), TO.ENTITY)
        entity.act("$n sembra cercare qualcosa ma senza risultato.", TO.OTHERS)
        return False

    if quantity == 0:
        quantity = target.quantity
    elif target.quantity < quantity:
        entity.act(
            "Non puoi %s $N perché ne hai solo %d e non %d." %
            (verbs["infinitive"], target.quantity, quantity), TO.ENTITY,
            target)
        entity.act(
            "$n sta cercando di ammucchiare un quantitativo voluto di $N per poterlo %s"
            % verbs["infinitive"], TO.OTHERS, target)
        entity.act(
            "$n sta cercando di ammucchiarti per un quantitativo voluto per poterti %s"
            % verbs["infinitive"], TO.TARGET, target)
        return False

    if FLAG.NO_DROP in target.flags:
        if entity.trust > TRUST.MASTER:
            entity.send_to_admin(
                "Questa sarebbe in realtà un'entità NO_DROP e non potresti lasciarla"
            )
        else:
            entity.act(
                "Appena cerchi di %s $N te lo ritrovi, con un balzo, in $hand."
                % verbs["infinitive"], TO.ENTITY, target)
            entity.act(
                "Appena $n cerca di %s $N se lo ritrova, con un balzo, in $hand."
                % verbs["infinitive"], TO.OTHERS, target)
            entity.act(
                "\nAppena $n cerca di %s gli ritorni in $hand con un balzo." %
                verbs["you2"], TO.TARGET, target)
            return False

    # Non permette di droppare oggetti nelle stanze con flag di NO_DROP
    if entity.location.IS_ROOM and ROOM.NO_DROP in entity.location.flags:
        if entity.trust > TRUST.MASTER:
            entity.send_to_admin(
                "Questa sarebbe in realtà una stanza NO_DROP in cui non poter lasciar entità"
            )
        else:
            entity.act(
                "Appena %s $N te lo ritrovi in %hand come se una [royalblue]forza misteriosa[close] nel luogo ti impedisse quest'azione!"
                % verbs["you"], TO.ENTITY, target)
            entity.act(
                "Appena $n lascia andare $N, con l'intenzione di %s, se lo ritrova in $hand come se vi fosse una [royalblue]forza misteriosa[close] nel luogo!"
                % verbs["noun"], TO.OTHERS, target)
            entity.act(
                "\nAppena $n ti %s ritorni nella sua $hand grazie ad una [royalblue]forza misteriosa[close] del luogo!"
                % verbs["it"], TO.TARGET, target)
            return False

    # (TD) posare monete

    # (TD) argomento all, ultima cosa da supportare

    # Ricava la locazione in cui posare l'oggetto
    # (TD)
    location = entity.location

    force_return = check_trigger(entity, "before_drop", entity, target,
                                 location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(target, "before_dropped", entity, target,
                                 location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(location, "before_drop_from_location", entity,
                                 target, location, behavioured)
    if force_return:
        return True

    entity.act("%s $N in $l." % color_first_upper(verbs["you"]), TO.ENTITY,
               target)
    entity.act("$n %s $N in $l." % verbs["it"], TO.OTHERS, target)
    entity.act("$n ti %s in $l." % verbs["it"], TO.TARGET, target)
    if not location.IS_ROOM:
        entity.act("$n ti %s qualcosa." % verbs["it"], TO.TARGET, location)

    if FLAG.INGESTED in target.flags:
        if entity.trust >= TRUST.MASTER:
            entity.send_to_admin("%s %s anche se lo stai digerendo." %
                                 (verbs["you"], target.get_name(entity)))
        else:
            log.bug(
                "I giocatori non dovrebbero poter manipolare oggetti ingeriti")
            entity.send_output(
                "[cyan]Errore di digestione nel comando, gli amministratori sono stati avvertiti del problema.[close]"
            )
            return False
        target.stop_digestion()

    target = target.from_location(quantity, use_repop=True)
    target.to_location(location)

    force_return = check_trigger(entity, "after_drop", entity, target,
                                 location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(target, "after_dropped", entity, target,
                                 location, behavioured)
    if force_return:
        return True
    force_return = check_trigger(location, "after_drop_from_location", entity,
                                 target, location, behavioured)
    if force_return:
        return True

    return True
Beispiel #23
0
def interpret(entity, argument, use_check_alias=True, force_position=True, show_input=True, show_prompt=True, behavioured=False):
    """
    Funzione che interpreta gli inputi inviati dalle entità.
    L'argomento use_check_alias a False viene passato dalla find_alias per
    evitare chiamate di alias da altri alias e quindi ricorsioni.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return

    if not argument:
        log.bug("argument non è un parametro valido: %r" % argument)
        return

    # -------------------------------------------------------------------------

    # Si assicura che colui che esegue l'azione sia un'entità unica e
    # non un mucchio fisico
    entity = entity.split_entity(1)

    if FLAG.CONVERSING in entity.flags and len(argument) == 1 and is_number(argument):
        # (TD)
        return

    arg, argument = one_argument(argument, search_separator=False)
    arg = arg.lower()

    input, huh_input, lang = multiple_search_on_inputs(entity, arg, use_check_alias=use_check_alias, argument=argument)
    # Utilizzo bislacco di lang per indicare che è stato trovato un alias
    # e che questo verrà processato tramite un'altra chiamata all'interpret
    if use_check_alias and lang == "alias":
        return

    # Resetta l'inattività di un player se ha inviato un comando
    if entity.IS_PLAYER:
        entity.inactivity = 0

    # Se non ha trovato nulla invia un messaggio apposito
    if not input:
        if show_input:
            entity.send_output(''' <span class="system">%s %s</span>''' % (remove_colors(arg), argument))
        entity.send_output("Huh?")
        # Se l'input non è stato trovato neanche nell'altra lingua allora
        # esegue il log dell'input, potrebbero esservene alcuni di sensati
        # da utilizzare in futuro come sinonimi
        # Scrive anche gli huh input dei mob così da ricavare gamescript o
        # random_do_inputs errati
        if not huh_input:
            log.huh_inputs(entity, arg)
        # Se serve visualizza il prompt
        if show_input:
            entity.send_prompt()
        return False

    # Poiché alcune words nello stesso input a volte hanno prefisso differente
    # tra loro allora cerca quello più simile possibile per farlo visualizzare
    # all'utente
    founded_input = input.findable_words[0]
    for word in input.findable_words:
        if is_prefix(arg, word):
            founded_input = word
            break

    # Se il giocatore è in stato di wait e l'input è un comando interattivo
    # allora evita di inviarlo subito ma lo mette in coda
    if entity.deferred_wait and CMDFLAG.INTERACT in input.command.flags:
        entity.waiting_inputs.append("%s %s" % (founded_input, argument))
        return False
    else:
        # Altrimenti scrive anche l'input a fianco del prompt
        if show_input:
            entity.send_output(''' <span class="system">%s %s</span>''' % (founded_input, argument))

    # Se il pg si è scollegato dalla pagina di gioco non esegue il comando
    if not entity.location:
        return False

    # Vengono salvate le informazioni sull'ultimo input inviato
    if argument:
        last_input = "%s %s" % (arg, argument)
    else:
        last_input = arg
    engine.last_input_sender = entity
    engine.last_input_sended = last_input
    # Si salva l'ultimo input inviato con successo
    if show_input and entity.IS_PLAYER and CMDFLAG.NO_LAST_INPUT not in input.command.flags:
        entity.last_input = last_input

    if CMDFLAG.GDR in input.command.flags:
        entity.sended_inputs.append("%s %s" % (founded_input, argument))

    if argument:
        argument = html_escape(argument)

    # Gestisce i comandi che devono essere digitati per intero
    command = input.command
    if CMDFLAG.TYPE_ALL in command.flags and not is_same(arg, input.findable_words):
        first_words, other_words = one_argument(input.words, search_separator=False)
        entity.send_output("Se vuoi veramente farlo devi scrivere per intero [limegreen]%s[close]." % first_words)
        execution_result = False
    elif not check_position(entity, command.position, force_position):
        # Se la posizione non è corretta invia il relativo messaggio d'errore
        vowel_of_genre = grammar_gender(entity)
        if entity.position == POSITION.DEAD:
            entity.send_output("Un po' difficile fino a che rimani MORT%s.." % vowel_of_genre.upper())
        elif (entity.position == POSITION.MORTAL
        or    entity.position == POSITION.INCAP):
            entity.send_output("Sei troppo ferit%s per farlo." % vowel_of_genre)
        elif entity.position == POSITION.STUN:
            entity.send_output("Sei troppo intontit%s per farlo." % vowel_of_genre)
        elif entity.position == POSITION.SLEEP:
            entity.send_output("Nei tuoi sogni, o cosa?")
        elif entity.position == POSITION.REST:
            entity.send_output("Nah.. Sei troppo rilassat%s ora.." % vowel_of_genre)
        elif entity.position == POSITION.KNEE:
            entity.send_output("Non puoi farlo da inginocchiat%s" % vowel_of_genre)
        elif entity.position == POSITION.SIT:
            entity.send_output("Non puoi farlo da sedut%s." % vowel_of_genre)
        else:
            log.bug("Manca la posizione %r" % entity.position)
        execution_result = False
    else:
        if command.type == CMDTYPE.SOCIAL:
            check_social(entity, command, argument=argument, behavioured=behavioured)

        if CMDFLAG.PRIVATE not in command.flags and (entity.IS_PLAYER or config.print_entity_inputs) and show_input and show_prompt:
            if entity.IS_PLAYER:
                write_on_file = True
            else:
                write_on_file = False
            log.input("'%s%s%s' digitato da %s in %s" % (
                founded_input,
                " " if argument else "",
                argument,
                entity.code,
                entity.location.get_name()), write_on_file=write_on_file)

        # Per comodità di sviluppo ricarica il modulo relativo al comando ogni
        # volta che lo si digita, così da poter testare le modifiche al codice
        # dei comandi senza aver bisogno di riavviare il gioco tutte le volte
        if config.reload_commands:
            reload(command.module)
            command.import_module_and_function()

        # Se si sta eseguendo un'azione che richiede tempo la interrompe
        if entity.action_in_progress and CMDFLAG.INTERACT in command.flags:
            if entity.action_in_progress.defer_later:
                entity.action_in_progress.stop()
            entity.action_in_progress = None

        # Esegue la funzione del comando cronometrandola
        input.counter_use += 1
        starting_time = time.time()
        execution_result = (command.function)(entity, argument)
        if command.fun_name[ : 8] == "command_" and execution_result != True and execution_result != False:
            log.bug("execution_result non è valido per il comando %s: %r" % (command.fun_name, execution_result))
        if command.fun_name[ : 6] == "skill_" and execution_result != "clumsy" and execution_result != "failure" and execution_result != "success" and execution_result != "magistral":
            log.bug("execution_result non è valido per la skill %s: %r" % (command.fun_name, execution_result))
        execution_time = time.time() - starting_time
        # Comandi che superano il tempo definito nella max_execution_time
        # possono portare a bachi creati dalla deferred impostata nel metodo
        # split_entity (nello stesso metodo c'è un commento con più informazioni)
        # Quindi devono essere il più possibile da evitare, allo stesso tempo
        # sarebbe meglio che il max_execution_time sia relativamente basso.
        if execution_time > config.max_execution_time:
            log.time("Il comando %s è stato eseguito in troppo tempo: %f secondi" % (command.fun_name, execution_time))
        command.timer += execution_time

    # Gestisce i comandi da loggare
    if CMDFLAG.LOG in command.flags:
        log.command("%s %s" % (command.fun_name, argument))

    if FLAG.AFK in entity.flags and command.fun_name != "command_afk":
        command_afk(entity)

    # Infine visualizza il prompt
    if show_prompt:
        entity.send_prompt()

    # Se la lista di input ancora da inviare non è vuota allora crea un
    # "falso wait" per forzarne l'invio. In teoria potrei inviarlo da qui, ma
    # il codice di ritorno execution_result andrebbe perduto, ecco perché
    # si fa uso della wait().
    if not entity.deferred_wait and entity.waiting_inputs:
        entity.wait(0.001)

    # Questa parte è da attivare con l'opzione check_references solo nei
    # server di test perché consuma molta cpu essendo eseguita su migliaia
    # di dati ad ogni invio di input, è una modalità di diagnostica
    # che non bada a spese in termini prestazionali
    if config.check_references and not database.reference_error_found:
        database.check_all_references()

    return execution_result
Beispiel #24
0
def get_direction(arg, exact=False):
    """
    Passato un argomento ne ritorna la direzione corrispondente.
    """
    if not arg:
        log.bug("arg non è un parametro valido: %r con exact a %s" % (arg, exact))
        return DIR.NONE

    # -------------------------------------------------------------------------

    # Esegue prima una ricerca esatta
    if   arg == "north"     or arg == "nord":   return DIR.NORTH
    elif arg == "east"      or arg == "est":    return DIR.EAST
    elif arg == "south"     or arg == "sud":    return DIR.SOUTH
    elif arg == "west"      or arg == "ovest":  return DIR.WEST
    elif arg == "up"        or arg == "alto":   return DIR.UP
    elif arg == "down"      or arg == "basso":  return DIR.DOWN
    elif arg == "northeast" or arg == "nordest"   or arg == "ne":                 return DIR.NORTHEAST
    elif arg == "northwest" or arg == "nordovest" or arg == "nw" or arg == "no":  return DIR.NORTHWEST
    elif arg == "southeast" or arg == "sudest"    or arg == "se":                 return DIR.SOUTHEAST
    elif arg == "southwest" or arg == "sudovest"  or arg == "sw" or arg == "so":  return DIR.SOUTHWEST

    # Ora esegue una ricerca relativa al prefisso, se così è stato voluto
    if not exact:
        if   is_prefix(arg, "north"    ) or is_prefix(arg, "nord"     ):  return DIR.NORTH
        elif is_prefix(arg, "east"     ) or is_prefix(arg, "est"      ):  return DIR.EAST
        elif is_prefix(arg, "south"    ) or is_prefix(arg, "sud"      ):  return DIR.SOUTH
        elif is_prefix(arg, "west"     ) or is_prefix(arg, "ovest"    ):  return DIR.WEST
        elif is_prefix(arg, "up"       ) or is_prefix(arg, "alto"     ):  return DIR.UP
        elif is_prefix(arg, "down"     ) or is_prefix(arg, "basso"    ):  return DIR.DOWN
        elif is_prefix(arg, "northeast") or is_prefix(arg, "nordest"  ):  return DIR.NORTHEAST
        elif is_prefix(arg, "northwest") or is_prefix(arg, "nordovest"):  return DIR.NORTHWEST
        elif is_prefix(arg, "southeast") or is_prefix(arg, "sudest"   ):  return DIR.SOUTHEAST
        elif is_prefix(arg, "southwest") or is_prefix(arg, "sudovest" ):  return DIR.SOUTHWEST

    # Se non l'ha trovata ritorna None
    return DIR.NONE
Beispiel #25
0
def command_loop(entity, argument):
    """
    Permette di freezare il loop del gioco. Comodo per disattivare i behaviour
    in fase di test.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    # -------------------------------------------------------------------------

    if not argument:
        output = []
        output.append(get_command_syntax(entity, "command_loop"))
        output.append('''<table class="mud">''')
        for loop in LOOPS:
            loop_name = loop.__class__.__name__.replace("Loop", "").lower()
            output.append(
                '''<tr><td>Attualmente %s%s</td>''' %
                ("l'" if is_vowel(loop_name[0]) else "il ", loop_name))
            output.append('''<td>%sè[close] in pausa</td>''' %
                          ("[red]" if loop.paused else "[white]non "))
            output.append('''<td>e%sè[close] stoppato.</td></tr>''' %
                          (" [white]non " if loop.running else "d [red]"))
        output.append('''</table>''')
        output.append(
            '''Ricordo che i reset non fanno parte dei loop, ma di un sistema di deferred separato.'''
        )
        entity.send_output("".join(output))
        return False

    # -------------------------------------------------------------------------

    arg, argument = one_argument(argument)

    for loop in LOOPS:
        loop_name = loop.__class__.__name__.replace("Loop", "").lower()
        if is_prefix(arg, loop_name):
            break
    else:
        entity.send_output("Non esiste nessun loop chiamato [white]%s[close]" %
                           arg)
        return False

    if not argument:
        entity.send_output(
            "Vuoi eseguire una [green]pausa[close] o un [green]continua[close] %s%s?"
            % ("all'" if is_vowel(loop_name[0]) else "al ", loop_name))
        return False

    article = "L'" if is_vowel(loop_name[0]) else "Il "

    if is_prefix(argument, ("pausa", "pause")):
        if loop.paused:
            entity.send_output("%s%s si trova già in pausa." %
                               (article, loop_name))
        else:
            entity.send_output("%s%s ora è stato messo in pausa" %
                               (article, loop_name))
            loop.paused = True
    elif is_prefix(argument, ("continua", "continue")):
        if loop.paused:
            entity.send_output("%s%s ora ricomincerà a girare." %
                               (article, loop_name))
            loop.paused = False
        else:
            entity.send_output("%s%s sta già girando." % (article, loop_name))
    else:
        entity.send_output(
            "[white]%s[close] non è un argomento valido da passare al comando loop."
            % argument)
        return False

    return True
Beispiel #26
0
def interpret(entity,
              argument,
              use_check_alias=True,
              force_position=True,
              show_input=True,
              show_prompt=True,
              behavioured=False):
    """
    Funzione che interpreta gli inputi inviati dalle entità.
    L'argomento use_check_alias a False viene passato dalla find_alias per
    evitare chiamate di alias da altri alias e quindi ricorsioni.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return

    if not argument:
        log.bug("argument non è un parametro valido: %r" % argument)
        return

    # -------------------------------------------------------------------------

    # Si assicura che colui che esegue l'azione sia un'entità unica e
    # non un mucchio fisico
    entity = entity.split_entity(1)

    if FLAG.CONVERSING in entity.flags and len(argument) == 1 and is_number(
            argument):
        # (TD)
        return

    arg, argument = one_argument(argument, search_separator=False)
    arg = arg.lower()

    input, huh_input, lang = multiple_search_on_inputs(
        entity, arg, use_check_alias=use_check_alias, argument=argument)
    # Utilizzo bislacco di lang per indicare che è stato trovato un alias
    # e che questo verrà processato tramite un'altra chiamata all'interpret
    if use_check_alias and lang == "alias":
        return

    # Resetta l'inattività di un player se ha inviato un comando
    if entity.IS_PLAYER:
        entity.inactivity = 0

    # Se non ha trovato nulla invia un messaggio apposito
    if not input:
        if show_input:
            entity.send_output(''' <span class="system">%s %s</span>''' %
                               (remove_colors(arg), argument))
        entity.send_output("Huh?")
        # Se l'input non è stato trovato neanche nell'altra lingua allora
        # esegue il log dell'input, potrebbero esservene alcuni di sensati
        # da utilizzare in futuro come sinonimi
        # Scrive anche gli huh input dei mob così da ricavare gamescript o
        # random_do_inputs errati
        if not huh_input:
            log.huh_inputs(entity, arg)
        # Se serve visualizza il prompt
        if show_input:
            entity.send_prompt()
        return False

    # Poiché alcune words nello stesso input a volte hanno prefisso differente
    # tra loro allora cerca quello più simile possibile per farlo visualizzare
    # all'utente
    founded_input = input.findable_words[0]
    for word in input.findable_words:
        if is_prefix(arg, word):
            founded_input = word
            break

    # Se il giocatore è in stato di wait e l'input è un comando interattivo
    # allora evita di inviarlo subito ma lo mette in coda
    if entity.deferred_wait and CMDFLAG.INTERACT in input.command.flags:
        entity.waiting_inputs.append("%s %s" % (founded_input, argument))
        return False
    else:
        # Altrimenti scrive anche l'input a fianco del prompt
        if show_input:
            entity.send_output(''' <span class="system">%s %s</span>''' %
                               (founded_input, argument))

    # Se il pg si è scollegato dalla pagina di gioco non esegue il comando
    if not entity.location:
        return False

    # Vengono salvate le informazioni sull'ultimo input inviato
    if argument:
        last_input = "%s %s" % (arg, argument)
    else:
        last_input = arg
    engine.last_input_sender = entity
    engine.last_input_sended = last_input
    # Si salva l'ultimo input inviato con successo
    if show_input and entity.IS_PLAYER and CMDFLAG.NO_LAST_INPUT not in input.command.flags:
        entity.last_input = last_input

    if CMDFLAG.GDR in input.command.flags:
        entity.sended_inputs.append("%s %s" % (founded_input, argument))

    if argument:
        argument = html_escape(argument)

    # Gestisce i comandi che devono essere digitati per intero
    command = input.command
    if CMDFLAG.TYPE_ALL in command.flags and not is_same(
            arg, input.findable_words):
        first_words, other_words = one_argument(input.words,
                                                search_separator=False)
        entity.send_output(
            "Se vuoi veramente farlo devi scrivere per intero [limegreen]%s[close]."
            % first_words)
        execution_result = False
    elif not check_position(entity, command.position, force_position):
        # Se la posizione non è corretta invia il relativo messaggio d'errore
        vowel_of_genre = grammar_gender(entity)
        if entity.position == POSITION.DEAD:
            entity.send_output("Un po' difficile fino a che rimani MORT%s.." %
                               vowel_of_genre.upper())
        elif (entity.position == POSITION.MORTAL
              or entity.position == POSITION.INCAP):
            entity.send_output("Sei troppo ferit%s per farlo." %
                               vowel_of_genre)
        elif entity.position == POSITION.STUN:
            entity.send_output("Sei troppo intontit%s per farlo." %
                               vowel_of_genre)
        elif entity.position == POSITION.SLEEP:
            entity.send_output("Nei tuoi sogni, o cosa?")
        elif entity.position == POSITION.REST:
            entity.send_output("Nah.. Sei troppo rilassat%s ora.." %
                               vowel_of_genre)
        elif entity.position == POSITION.KNEE:
            entity.send_output("Non puoi farlo da inginocchiat%s" %
                               vowel_of_genre)
        elif entity.position == POSITION.SIT:
            entity.send_output("Non puoi farlo da sedut%s." % vowel_of_genre)
        else:
            log.bug("Manca la posizione %r" % entity.position)
        execution_result = False
    else:
        if command.type == CMDTYPE.SOCIAL:
            check_social(entity,
                         command,
                         argument=argument,
                         behavioured=behavioured)

        if CMDFLAG.PRIVATE not in command.flags and (
                entity.IS_PLAYER
                or config.print_entity_inputs) and show_input and show_prompt:
            if entity.IS_PLAYER:
                write_on_file = True
            else:
                write_on_file = False
            log.input("'%s%s%s' digitato da %s in %s" %
                      (founded_input, " " if argument else "", argument,
                       entity.code, entity.location.get_name()),
                      write_on_file=write_on_file)

        # Per comodità di sviluppo ricarica il modulo relativo al comando ogni
        # volta che lo si digita, così da poter testare le modifiche al codice
        # dei comandi senza aver bisogno di riavviare il gioco tutte le volte
        if config.reload_commands:
            reload(command.module)
            command.import_module_and_function()

        # Se si sta eseguendo un'azione che richiede tempo la interrompe
        if entity.action_in_progress and CMDFLAG.INTERACT in command.flags:
            if entity.action_in_progress.defer_later:
                entity.action_in_progress.stop()
            entity.action_in_progress = None

        # Esegue la funzione del comando cronometrandola
        input.counter_use += 1
        starting_time = time.time()
        execution_result = (command.function)(entity, argument)
        if command.fun_name[:
                            8] == "command_" and execution_result != True and execution_result != False:
            log.bug("execution_result non è valido per il comando %s: %r" %
                    (command.fun_name, execution_result))
        if command.fun_name[:
                            6] == "skill_" and execution_result != "clumsy" and execution_result != "failure" and execution_result != "success" and execution_result != "magistral":
            log.bug("execution_result non è valido per la skill %s: %r" %
                    (command.fun_name, execution_result))
        execution_time = time.time() - starting_time
        # Comandi che superano il tempo definito nella max_execution_time
        # possono portare a bachi creati dalla deferred impostata nel metodo
        # split_entity (nello stesso metodo c'è un commento con più informazioni)
        # Quindi devono essere il più possibile da evitare, allo stesso tempo
        # sarebbe meglio che il max_execution_time sia relativamente basso.
        if execution_time > config.max_execution_time:
            log.time(
                "Il comando %s è stato eseguito in troppo tempo: %f secondi" %
                (command.fun_name, execution_time))
        command.timer += execution_time

    # Gestisce i comandi da loggare
    if CMDFLAG.LOG in command.flags:
        log.command("%s %s" % (command.fun_name, argument))

    if FLAG.AFK in entity.flags and command.fun_name != "command_afk":
        command_afk(entity)

    # Infine visualizza il prompt
    if show_prompt:
        entity.send_prompt()

    # Se la lista di input ancora da inviare non è vuota allora crea un
    # "falso wait" per forzarne l'invio. In teoria potrei inviarlo da qui, ma
    # il codice di ritorno execution_result andrebbe perduto, ecco perché
    # si fa uso della wait().
    if not entity.deferred_wait and entity.waiting_inputs:
        entity.wait(0.001)

    # Questa parte è da attivare con l'opzione check_references solo nei
    # server di test perché consuma molta cpu essendo eseguita su migliaia
    # di dati ad ogni invio di input, è una modalità di diagnostica
    # che non bada a spese in termini prestazionali
    if config.check_references and not database.reference_error_found:
        database.check_all_references()

    return execution_result
Beispiel #27
0
def command_restring(entity, argument=""):
    """
    Permette di modificare la short il nome e la descrizione dell'oggetto voluto.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    # -------------------------------------------------------------------------

    if not argument:
        syntax = get_command_syntax(entity, "command_restring")
        entity.send_output(syntax, break_line=False)
        return False

    arg1, argument = one_argument(argument)

    target = entity.find_entity_extensively(arg1, inventory_pos="first")
    if not target:
        entity.send_output("Nessuna entità trovata con argomento [white]%s[close]." % arg1)
        return False

    if not argument:
        output  = "[white]%s[close]:\n" % target.code
        output += '''<table class='mud'>'''
        if not target.IS_PLAYER:
            output += '''<tr><td>KeywordsName:</td><td>%s</td></tr>''' % target.keywords_name
            output += '''<tr><td>KeywordsShort:</td><td>%s</td></tr>''' % target.keywords_short
            output += '''<tr><td>KeywordsShortNight:</td><td>%s</td></tr>''' % target.keywords_short_night
        output += '''<tr><td>Name:</td><td>%s</td></tr>''' % target.name
        if target.short:
            output += '''<tr><td>Short:</td><td>%s</td></tr>''' % target.short
        if target.short_night:
            output += '''<tr><td>ShortNight:</td><td>%s</td></tr>''' % target.short_night
        if target.long:
            output += '''<tr><td>Long:</td><td>%s</td></tr>''' % target.long
        if target.long_night:
            output += '''<tr><td>LongNight:</td><td>%s</td></tr>''' % target.long_night
        output += '''<tr><td>Descr:</td><td>%s</td></tr>''' % target.descr
        if target.descr_night:
            output += '''<tr><td valign="top">DescrNight:</td><td>%s</td></tr>''' % target.descr_night
        if target.descr_hearing:
            output += '''<tr><td valign="top">DescrHearing:</td><td>%s</td></tr>''' % target.descr_hearing
        if target.descr_hearing_night:
            output += '''<tr><td valign="top">DescrHearingNight:</td><td>%s</td></tr>''' % target.descr_hearing_night
        if target.descr_smell:
            output += '''<tr><td valign="top">DescrSmell:</td><td>%s</td></tr>''' % target.descr_smell
        if target.descr_smell_night:
            output += '''<tr><td valign="top">DescrSmellNight:</td><td>%s</td></tr>''' % target.descr_smell_night
        if target.descr_touch:
            output += '''<tr><td valign="top">DescrTouch:</td><td>%s</td></tr>''' % target.descr_touch
        if target.descr_touch_night:
            output += '''<tr><td valign="top">DescrTouchNight:</td><td>%s</td></tr>''' % target.descr_touch_night
        if target.descr_taste:
            output += '''<tr><td valign="top">DescrTaste:</td><td>%s</td></tr>''' % target.descr_taste
        if target.descr_taste_night:
            output += '''<tr><td valign="top">DescrTasteNight:</td><td>%s</td></tr>''' % target.descr_taste_night
        if target.descr_sixth:
            output += '''<tr><td valign="top">DescrSixth:</td><td>%s</td></tr>''' % target.descr_sixth
        if target.descr_sixth_night:
            output += '''<tr><td valign="top">DescrSixthNight:</td><td>%s</td></tr>''' % target.descr_sixth_night
        output += '''</table>'''
        if target.IS_PLAYER and not target.game_request:
            entity.send_output("Il giocatore %s è [darkslategray]offline[close]")
        entity.send_output(output, break_line=False)
        return True

    arg2, argument = one_argument(argument)
    attribute = ""
    if is_prefix(arg2, ("KeywordsName", "keywords_name")):
        attribute = "keywords_name"
        attr_descr = "le parole chiavi del nome"
    elif is_prefix(arg2, ("KeywordsShort", "keywords_short")):
        attribute = "keywords_short"
        attr_descr = "le parole chiavi della short"
    elif is_prefix(arg2, ("KeywordsShortNight", "keywords_short_night")):
        attribute = "keywords_short_night"
        attr_descr = "le parole chiavi della short notturna"
    elif is_prefix(arg2, ("Name", "nome")):
        attribute = "name"
        attr_descr = "il nome"
    elif is_prefix(arg2, ("Short", "corta")):
        attribute = "short"
        attr_descr = "la short"
    elif is_prefix(arg2, ("ShortNight", "short_night")):
        attribute = "short_night"
        attr_descr = "la short notturna"
    elif is_prefix(arg2, ("Long", "lunga")):
        attribute = "long"
        attr_descr = "la long"
    elif is_prefix(arg2, ("LongNight", "long_night")):
        attribute = "long_night"
        attr_descr = "la long notturna"
    elif is_prefix(arg2, ("Descr", "descr", "Descrizione", "description")):
        attribute = "descr"
        attr_descr = "la descrizione"
    elif is_prefix(arg2, ("DescrNight", "descr_night")):
        attribute = "descr_night"
        attr_descr = "la descrizione notturna"
    elif is_prefix(arg2, ("DescrHearing", "descr_hearing")):
        attribute = "descr_hearing"
        attr_descr = "la descrizione uditiva"
    elif is_prefix(arg2, ("DescrHearingNight", "descr_hearing_night")):
        attribute = "descr_hearing_night"
        attr_descr = "la descrizione uditiva notturna"
    elif is_prefix(arg2, ("DescrSmell", "descr_smell")):
        attribute = "descr_smell"
        attr_descr = "la descrizione olfattiva"
    elif is_prefix(arg2, ("DescrSmellNight", "descr_smell_night")):
        attribute = "descr_smell_night"
        attr_descr = "la descrizione olfattiva notturna"
    elif is_prefix(arg2, ("DescrTouch", "descr_touch")):
        attribute = "descr_touch"
        attr_descr = "la descrizione tattile"
    elif is_prefix(arg2, ("DescrTouchNight", "descr_touch_night")):
        attribute = "descr_touch_night"
        attr_descr = "la descrizione tattile notturna"
    elif is_prefix(arg2, ("DescrTaste", "descr_taste")):
        attribute = "descr_taste"
        attr_descr = "la descrizione gustativa"
    elif is_prefix(arg2, ("DescrTasteNight", "descr_taste_night")):
        attribute = "descr_taste_night"
        attr_descr = "la descrizione gustativa notturna"
    elif is_prefix(arg2, ("DescrSixth", "descr_sixth")):
        attribute = "descr_sixth"
        attr_descr = "la descrizione intuitiva"
    elif is_prefix(arg2, ("DescrSixthNight", "descr_sixth_night")):
        attribute = "descr_sixth_night"
        attr_descr = "la descrizione intuitiva notturna"

    if not attribute:
        syntax = "L'etichetta da modificare all'entità '%s' è errata: %s" % (target.code, arg2)
        syntax += get_command_syntax(entity, "command_restring")
        entity.send_output(syntax, break_line=False)
        return False

    if not argument:
        syntax = "Il testo da sostituire nell'etichetta è vuoto."
        syntax += get_command_syntax(entity, "command_restring")
        entity.send_output(syntax, break_line=False)
        return False

    if not check_colors(argument):
        entity.send_output("Errore nella colorazione del testo: %s" % argument)
        return False

    if getattr(target, attribute) == argument:
        entity.send_output("Inutile modificare %s di '%s' con un'altra stringa uguale." % (attr_descr, target.code))
        return False

    # Se si sta rinominando un giocatore allora si tiene traccia del vecchio nome
    if target.IS_PLAYER:
        if attribute == "name":
            argument = color_first_upper(argument)
            err_msg_name = get_error_message_name(argument, True, "players")
            if err_msg_name:
                entity.send_output(err_msg_name)
                return False
            if not is_same(argument, target.name):
                target.old_names += " " + target.name
            # (TD) fare anche i messaggi d'avviso per gli altri attributi? da pensare
            target.send_output("\nTi è stato cambiato il nome da %s a %s" % (target.name, argument))
            target.send_prompt()
        elif attribute in ("keywords_name", "keywords_short", "keywords_short_night"):
            entity.send_output("È impossibile modificare %s nei giocatori." % attr_descr)
            return False

    setattr(target, attribute, argument)
    entity.send_output("Hai modificato il testo dell'etichetta %s di '%s' in %s" % (
        to_capitalized_words(attribute), target.code, argument))
    return True
Beispiel #28
0
def rpg_channel(entity, argument, channel, ask=False, exclaim=False, behavioured=False):
    """
    Gestisce i canali rpg, ha le seguenti caratteristiche:
    - supporto per gli smile
    - supporto per i modi di esprimersi con esclamativo e punto di domanda
    - supporto per gli emote
    - gestione del bersaglio che può essere un'entità, il gruppo o sé stessi
    - (TD) parlata da ubriaco
    - (TD) espansione della potenza della voce in altre stanze
    - (TD) espressioni per le stanze attorno, anche per coloro che riconoscono la voce,
           pensare anche alla suddivisione tra social gestuali e 'rumorosi' per gli smile-espressioni around
    - (TD) modulazione della voce a seconda delle dimensioni di chi parla e della sua voice_potence
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    if not channel:
        log.bug("channel non è un parametro valido: %r" % channel)
        return False

    # -------------------------------------------------------------------------

    if entity.IS_ROOM:
        return False

    objective = OBJECTIVE_ROOM  # obiettivo del messaggio
    # Linguaggio utilizzato per dire il messaggio
    if entity.IS_ITEM:
        language = LANGUAGE.COMMON
    else:
        language = entity.speaking
    smile = ""            # conterrà l'eventuale espressione di uno smile-social
    emote = ""            # conterrà l'eventuale emote inviato con il messaggio tra due asterischi
    expres_entity = ""    # espressione per chi parla
    expres_room   = ""    # espressione per chi sta ascoltando nella stanza
    expres_objective = "" # espressione per chi riceverà il messaggio

    # Ricava i verbi e il colore relativi al canale
    # Se si sta parlando normalmente la propria lingua vengono utilizzati
    # i verbi razziali per descriverne timbro, flessione o pronuncia
    if channel == CHANNEL.SAY:
        verb_you, verb_it = entity.race.say_verb_you, entity.race.say_verb_it
    else:
        verb_you, verb_it = channel.verb_you, channel.verb_it
    color = get_first_color(channel.name)

    # Se non è stato passato nessun messaggio esce
    if not argument or not remove_colors(argument):
        entity.send_output("Cosa vorresti %s?" % channel)
        return False

    if len(argument) > config.max_google_translate:
        entity.send_output("Non puoi %s un messaggio così logorroico." % channel)
        return False

    # Copia l'argomento originale, in alcuni casi serve recuperarlo poi
    original_argument = argument

    # Controlla se si sta parlando a qualcuno, il controllo sulla particella
    # la esegue in minuscolo, dando per sottinteso che quando uno scrive
    # maiuscolo voglia iniziare un discorso
    target = None
    if argument[0 : 2] == "a ":
        arg, argument = one_argument(argument)
        # Se sta parlando a qualcuno cerca di acquisirlo dal nome successivo
        objective_name, argument = one_argument(argument)
        target = entity.find_entity_extensively(objective_name)
        # con me e self esegue un check senza la is_same volutamente, per evitare
        # ricerche con nome di player che iniziano con Me o Self
        if target == entity or objective_name in ("me", "self"):
            objective = OBJECTIVE_SELF
            # Se si parla da soli lo si fa utilizzando la lingua madre
            language = entity.race.natural_language
        elif target:
            objective = OBJECTIVE_TARGET
            # Se si parla con qualcuno della stessa razza lo si fa utilizzando
            # la lingua preferita dalla razza, è un fattore culturale
            if entity.race == target.race:
                language = entity.race.natural_language
        else:
            # Se non ha trovato nessun 'a <nome bersaglio>' riprende
            # l'argument originale
            argument = original_argument
    # Stessa cosa di sopra ma qui controlla se si stia parlando al gruppo
    elif argument[0 : 3] == "al ":
        arg, argument = one_argument(argument)
        objective_name, argument = one_argument(argument)
        if is_prefix(objective_name, "gruppo"):
            if not entity.group:
                entity.send_output("Non fai parte di nessun gruppo.")
                return False
            # Questa variabile verrà utilizza poi nell'invio del messaggio
            group_members = entity.get_members_here(entity.location)
            if not group_members:
                entity.send_output("Non trovi nessun membro del gruppo vicino a te con cui poter parlare.")
                return False
            objective = OBJECTIVE_GROUP
            # Se si parla in un gruppo in cui tutti sono formati dalla stessa
            # razza si preferirà parlare con la lingua della propria razza
            for group_member in group_members:
                if group_member.race != entity.race:
                    break
            else:
                language = entity.race.natural_language
        else:
            # Se il personaggio non vuole parlare al gruppo recupera
            # il valore originale inviato
            argument = original_argument

    # (TD) Gestisce il caso in cui l'entità si trovi immersa in un liquido
    #if entity.is_immersed():
    #    entity.send_output("Tenti di %s qualcosa ma subito l'acqua ti riempie la gola soffocandoti!" % channel)
    #    entity.points.life -= random.randint(entity.level / 6, entity.level / 4) + 1
    #    return False

    if not entity.location:
        log.bug("entity %s non si trova in una locazione valida: %r (original_argument: %s)" % (
            entity.code, entity.location, original_argument))
        return False

    # Gestisce le stanze che obbligano al silenzio
    if entity.location.IS_ROOM:
        if ROOM.SILENCE in entity.location.flags:
            entity.send_output("Il silenzio del luogo ti blocca la gola impedendoti di %s." % channel)
            return False

        # (TT) Se nella stanza c'è molto casino, tante persone etc etc è difficile
        # parlare piano
        if entity.location.mod_noise > 75 and channel <= CHANNEL.SAY:
            entity.send_output("Non puoi %s con tutta questa confusione!" % channel)
            return False

    # Invia l'appropriato messaggio nel caso in cui trovi argument vuoto
    if not argument:
        send_not_argument_message(entity, objective, channel)
        return False

    # Cerca eventuali smiles nella stringa controllando gli ultimi caratteri
    for social in database["socials"].itervalues():
        if not social.smiles:
            continue
        for single_smile in social.smiles.split():
            if single_smile in argument[-config.chars_for_smile : ]:
                break
        else:
            # Se non trova nessun smile esce dal ciclo dei social e continua
            # col prossimo set di smiles trovato
            continue

        cut_smile = argument.rfind(single_smile)
        # Se argument è formato solo dallo smile invia il corrispondente social
        if cut_smile == 0:
            social_name = social.fun_name[len("social_") : ]
            if objective == OBJECTIVE_TARGET:
                input_to_send = "%s %s" % (social_name, target.name)
            elif objective == OBJECTIVE_SELF:
                input_to_send = "%s %s" % (social_name, entity.name)
            else:
                input_to_send = social_name

            send_input(entity, input_to_send, "en", show_input=False, show_prompt=False)
            return True

        # Altrimenti ne ricava l'espressione dello smile-social e toglie lo
        # smile da argument, se il carattere dopo lo smile era un simbolo di
        # punteggiatura lo attacca alla frase togliendo gli spazi
        first_part  = argument[ : cut_smile]
        second_part = argument[cut_smile + len(single_smile) : ]
        if second_part.strip() and second_part.strip()[0] in "!?.,:;":
            first_part = first_part.rstrip()
            second_part = second_part.lstrip()
        argument = first_part.rstrip() + second_part.rstrip()
        smile = " %s" % social.expression
        break

    # Elabora i punti esclamativi e interrogativi per il canale say.
    # Qui viene utilizzata l'opzione chars_for_smile visto che si sta facendo
    # una cosa simile a sopra, ovvero considerare solo l'ultima parte
    # dell'argomento passato.
    exclamations = argument[-config.chars_for_smile : ].count("!")
    questions    = argument[-config.chars_for_smile : ].count("?")
    if exclamations > questions:
        if channel == CHANNEL.SAY:
            verb_you = "Esclami"
            verb_it  = " esclama"
        exclaim = True
    elif exclamations < questions:
        if channel == CHANNEL.SAY:
            verb_you = "Domandi"
            verb_it  = " domanda"
        ask = True
    # Questo elif sottintende che exclamations e questions siano uguali
    elif exclamations != 0 and questions != 0:
        # Con una stessa quantità di ! e di ? l'ultimo che viene trovato
        # ha maggiore peso rispetto all'altro
        exclamation_pos = argument.rfind("!")
        question_pos = argument.rfind("?")
        if exclamation_pos > question_pos:
            if channel == CHANNEL.SAY:
                verb_you = "Esclami"
                verb_it  = " esclama"
            exclaim = True
        else:
            if channel == CHANNEL.SAY:
                verb_you = "Domandi"
                verb_it  = " domanda"
            ask = True

    # Supporto per piccoli emote separati da * ad inizio argument
    if argument[0] == "*":
        cut_emote = argument[1 : ].find("*")
        if cut_emote != -1:
            emote = " %s" % argument[1 : cut_emote+1].strip()
            if smile:
                emote = " e%s" % emote
            argument = argument[cut_emote+2 : ].strip()

    # Unisce i vari pezzi per formare l'output
    expres_entity = verb_you
    expres_room = verb_it
    expres_target = ""
    if objective == OBJECTIVE_TARGET:
        name = target.get_name(entity)
        expres_entity += " a %s" % name
        expres_room   += " a %s" % name
        expres_target += " ti%s" % verb_it
    elif objective == OBJECTIVE_SELF:
        expres_entity += " a te stess%s" % grammar_gender(entity)
        expres_room   += " a sé stess%s" % grammar_gender(entity)
    elif objective == OBJECTIVE_GROUP:
        members = entity.get_members_here(entity.location)
        if len(members) == 1:
            expres_entity += " a %s" % members[0].name
            expres_room   += " a %s" % members[0].name
            expres_target += " ti%s" % verb_it
        else:
            if len(members) > 5:
                many = "folto "
            else:
                many = ""
            expres_entity += " al gruppo"
            expres_room   += " ad un %sgruppo" % many
            expres_target += "%s al gruppo" % verb_it
    # Aggiunge le eventuali espressioni dello smile e dell'emote
    expres_entity += smile + emote
    expres_room   += smile + emote
    expres_target += smile + emote

    if not argument:
        send_not_argument_message(entity, objective, channel)
        return False

    # Prepara il pezzo riguardante la lingua utilizzata
    language = ""
    if not entity.IS_ITEM and entity.speaking != LANGUAGE.COMMON:
        language = " in lingua %s" % entity.speaking

    # Mischia il testo se si è ubriachi
    original_argument = argument = color_first_upper(argument)
    argument = drunk_speech(argument, entity)

    # Parlando si impara la lingua
    if not entity.IS_ITEM:
        learn_language(entity, channel, entity.speaking)

    # Controlla se vi sono parolacce o parole offrpg e logga i relativi argument
    if entity.IS_PLAYER:
        check_for_badwords(entity, argument)

    # Invia il messaggio a tutti coloro che lo possono sentire
    for location in expand_voice_around(entity, channel):
        if not location:
            log.bug("location per il canale %s e per l'entità %s non è valida: %r" % (channel, entity.code, location))
            continue
        for listener in location.iter_contains(use_reversed=True):
            if listener.position <= POSITION.SLEEP:
                continue

            if listener == entity:
                force_return = check_trigger(entity, "before_rpg_channel", listener, entity, target, argument, ask, exclaim, behavioured)
                if force_return:
                    continue
                force_return = check_trigger(entity, "before_" + channel.trigger_suffix, listener, entity, target, argument, ask, exclaim, behavioured)
                if force_return:
                    continue

                # Invia all'entità il suo stesso messaggio
                first_part = (close_color(color) + expres_entity).rstrip()
                message = "%s: '%s'" % (first_part, close_color(argument))
                send_channel_message(entity, message, True)

                force_return = check_trigger(entity, "after_rpg_channel", listener, entity, target, argument, ask, exclaim, behavioured)
                if force_return:
                    continue
                force_return = check_trigger(entity, "after_" + channel.trigger_suffix, listener, entity, target, argument, ask, exclaim, behavioured)
                if force_return:
                    continue
            else:
                # Fa ascoltare solo ad un'entità di un eventuale gruppo fisico
                listener = listener.split_entity(1)

                force_return = check_trigger(listener, "before_listen_rpg_channel", listener, entity, target, argument, ask, exclaim, behavioured)
                if force_return:
                    continue
                force_return = check_trigger(listener, "before_listen_" + channel.trigger_suffix, listener, entity, target, argument, ask, exclaim, behavioured)
                if force_return:
                    continue

                # Prepara alcune cose a seconda della stanza di provenienza del messaggio
                if entity.location == listener.location:
                    entity_name = entity.get_name(listener)
                    entity_name = color_first_upper(entity_name)
                    from_direction = ""
                elif entity.location.IS_ROOM:
                    # (TD) invia qualcuno a meno che non lo si abbia conosciuto
                    # precedentemente con il sistema di presentazione
                    entity_name = "Qualcuno"
                    from_direction = get_from_direction(listener.location.x, listener.location.y, listener.location.z,
                                                        entity.location.x, entity.location.y, entity.location.z)
                elif entity.location.IS_ACTOR:
                    if entity.location != listener:
                        entity_name = "Qualcuno"  # (TD) come sopra
                    from_direction = " dall'inventario di %s" % entity.location.get_name(listener)
                else:
                    entity_name = "Qualcuno"  # (TD) come sopra
                    from_direction = " da dentro %s" % entity.location.get_name(listener)

                # Prepara la prima parte, quella senza il messaggio
                if objective == OBJECTIVE_ROOM:
                    output = "%s%s%s%s" % (entity_name, close_color(color) + expres_room, language, from_direction)
                elif objective == OBJECTIVE_TARGET or OBJECTIVE_SELF:
                    if listener == target:
                        output = "%s%s%s%s" % (entity_name, close_color(color) + expres_target, language, from_direction)
                    else:
                        output = "%s%s%s%s" % (entity_name, close_color(color) + expres_room, language, from_direction)
                elif objective == OBJECTIVE_GROUP:
                    if listener in group_members:
                        output = "%s%s%s%s" % (entity_name, close_color(color) + expres_target, language, from_direction)
                    else:
                        output = "%s%s%s%s" % (entity_name, close_color(color) + expres_room, language, from_direction)

                output = "<br>%s: '%s'" % (close_color(output).rstrip(), close_color(argument))
                send_channel_message(listener, output, False)
                listener.send_prompt()

                force_return = check_trigger(listener, "after_listen_rpg_channel", listener, entity, target, argument, ask, exclaim, behavioured)
                if force_return:
                    continue
                force_return = check_trigger(listener, "after_listen_" + channel.trigger_suffix, listener, entity, target, argument, ask, exclaim, behavioured)
                if force_return:
                    continue

    return True
Beispiel #29
0
def _find_entity_handler_for_admin(entity,
                                   argument,
                                   list_to_search,
                                   number,
                                   compare_function,
                                   avoid_inventory=False,
                                   avoid_equipment=True,
                                   avoid_doors=False):
    """
    Per velocizzare la find_entity, che con parametro location passato a Null
    può arrivare a rallentamenti notevoli, è stata creata questa copia dalla
    _find_entity_handler con un check aggiuntivo che riguarda solo gli admin.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return None

    if not argument:
        log.bug("argument non è un parametro valido: %r" %
                argument)  # (TT) questo test potrebbe non servire
        return None

    if not list_to_search and list_to_search != []:
        log.bug("list_to_search non è valido: %r" % list_to_search)
        return None

    if number <= 0:
        log.bug("number non è un parametro valido: %r" % number)
        return None

    if not compare_function:
        log.bug("compare_function non è un parametro valido: %r" %
                compare_function)
        return None

    # -------------------------------------------------------------------------

    counter = 0
    for target in list_to_search:
        if avoid_inventory and len(target.wear_mode) == 0:
            continue
        if avoid_equipment and len(target.wear_mode) != 0:
            continue
        if avoid_doors and target.door_type and target.is_hinged():
            continue
        if not entity.can_see(target):
            continue

        keywords = target.get_keywords_attr(entity)
        if not keywords:
            log.bug("target %s senza keywords valide: %s" %
                    (target.code, keywords))
            continue

        if compare_function(argument, multiple_arguments(keywords)) or is_same(
                argument, target.code) or is_prefix(argument + "#",
                                                    target.code):
            if counter + target.quantity >= number:
                return target
            counter += target.quantity

    return None
Beispiel #30
0
def command_repaint(entity, argument=""):
    """
    Permette di modificare la short, nome e descrizione di una stanza.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    # -------------------------------------------------------------------------

    if not entity.location.IS_ROOM:
        entity.send_output("Non ti trovi in una stanza ma in %s." %
                           entity.location.code)
        return False

    room = entity.location

    if not argument:
        syntax = get_command_syntax(entity, "command_repaint")
        entity.send_output(syntax)

        output = "[white]%s[close]:\n" % room.code
        output += '''<table class='mud'>'''
        output += '''<tr><td>Name:</td><td>%s</td></tr>''' % room.name
        if room.short:
            output += '''<tr><td>Short:</td><td>%s</td></tr>''' % room.short
        if room.short_night:
            output += '''<tr><td>ShortNight:</td><td>%s</td></tr>''' % room.short_night
        output += '''<tr><td valign="top">Descr:</td><td>%s</td></tr>''' % room.descr
        if room.descr_night:
            output += '''<tr><td valign="top">DescrNight:</td><td>%s</td></tr>''' % room.descr_night
        if room.descr_hearing:
            output += '''<tr><td valign="top">DescrHearing:</td><td>%s</td></tr>''' % room.descr_hearing
        if room.descr_hearing_night:
            output += '''<tr><td valign="top">DescrHearingNight:</td><td>%s</td></tr>''' % room.descr_hearing_night
        if room.descr_smell:
            output += '''<tr><td valign="top">DescrSmell:</td><td>%s</td></tr>''' % room.descr_smell
        if room.descr_smell_night:
            output += '''<tr><td valign="top">DescrSmellNight:</td><td>%s</td></tr>''' % room.descr_smell_night
        if room.descr_touch:
            output += '''<tr><td valign="top">DescrTouch:</td><td>%s</td></tr>''' % room.descr_touch
        if room.descr_touch_night:
            output += '''<tr><td valign="top">DescrTouchNight:</td><td>%s</td></tr>''' % room.descr_touch_night
        if room.descr_taste:
            output += '''<tr><td valign="top">DescrTaste:</td><td>%s</td></tr>''' % room.descr_taste
        if room.descr_taste_night:
            output += '''<tr><td valign="top">DescrTasteNight:</td><td>%s</td></tr>''' % room.descr_taste_night
        if room.descr_sixth:
            output += '''<tr><td valign="top">DescrSixth:</td><td>%s</td></tr>''' % room.descr_sixth
        if room.descr_sixth_night:
            output += '''<tr><td valign="top">DescrSixthNight:</td><td>%s</td></tr>''' % room.descr_sixth_night
        output += '''</table>'''
        entity.send_output(output, break_line=False)
        return False

    arg1, argument = one_argument(argument)
    attribute = ""
    if is_prefix(arg1, ("name", "nome")):
        attribute = "name"
        attr_descr = "il nome"
    elif is_prefix(arg1, ("short", "corta")):
        attribute = "short"
        attr_descr = "la short"
    elif is_prefix(arg1,
                   ("ShortNight", "short_night", "CortaNotte", "corta_notte")):
        attribute = "short_night"
        attr_descr = "la short notturna"
    elif is_prefix(arg1, ("Descr", "descr", "Descrizione", "description")):
        attribute = "descr"
        attr_descr = "la descrizione"
    elif is_prefix(arg1, ("DescrNight", "descr_night")):
        attribute = "descr_night"
        attr_descr = "la descrizione notturna"
    elif is_prefix(arg1, ("DescrHearing", "descr_hearing")):
        attribute = "descr_hearing"
        attr_descr = "la descrizione uditiva"
    elif is_prefix(arg1, ("DescrHearingNight", "descr_hearing_night")):
        attribute = "descr_hearing_night"
        attr_descr = "la descrizione uditiva notturna"
    elif is_prefix(arg1, ("DescrSmell", "descr_smell")):
        attribute = "descr_smell"
        attr_descr = "la descrizione olfattiva"
    elif is_prefix(arg1, ("DescrSmellNight", "descr_smell_night")):
        attribute = "descr_smell_night"
        attr_descr = "la descrizione olfattiva notturna"
    elif is_prefix(arg1, ("DescrTouch", "descr_touch")):
        attribute = "descr_touch"
        attr_descr = "la descrizione tattile"
    elif is_prefix(arg1, ("DescrTouchNight", "descr_touch_night")):
        attribute = "descr_touch_night"
        attr_descr = "la descrizione tattile notturna"
    elif is_prefix(arg1, ("DescrTaste", "descr_taste")):
        attribute = "descr_taste"
        attr_descr = "la descrizione gustativa"
    elif is_prefix(arg1, ("DescrTasteNight", "descr_taste_night")):
        attribute = "descr_taste_night"
        attr_descr = "la descrizione gustativa notturna"
    elif is_prefix(arg1, ("DescrSixth", "descr_sixth")):
        attribute = "descr_sixth"
        attr_descr = "la descrizione intuitiva"
    elif is_prefix(arg1, ("DescrSixthNight", "descr_sixth_night")):
        attribute = "descr_sixth_night"
        attr_descr = "la descrizione intuitiva notturna"

    if not attribute:
        syntax = "L'etichetta da modificare all'entità '%s' è errata: %s" % (
            room.code, arg1)
        syntax += get_command_syntax(entity, "command_repaint")
        entity.send_output(syntax, break_line=False)
        return False

    if not argument:
        syntax = "Il testo da sostituire nell'etichetta è vuoto."
        syntax += get_command_syntax(entity, "command_repaint")
        entity.send_output(syntax, break_line=False)
        return False

    if not check_colors(argument):
        entity.send_output("Errore nella colorazione del testo: %s" % argument)
        return False

    if getattr(room, attribute) == argument:
        entity.send_output(
            "Inutile modificare %s di '%s' con un'altra stringa uguale." %
            (attr_descr, room.code))
        return False

    setattr(room, attribute, argument)
    entity.send_output(
        "Hai modificato il testo dell'etichetta %s di '%s' in %s" %
        (to_capitalized_words(attribute), room.code, argument))
    return True
Beispiel #31
0
def rpg_channel(entity,
                argument,
                channel,
                ask=False,
                exclaim=False,
                behavioured=False):
    """
    Gestisce i canali rpg, ha le seguenti caratteristiche:
    - supporto per gli smile
    - supporto per i modi di esprimersi con esclamativo e punto di domanda
    - supporto per gli emote
    - gestione del bersaglio che può essere un'entità, il gruppo o sé stessi
    - (TD) parlata da ubriaco
    - (TD) espansione della potenza della voce in altre stanze
    - (TD) espressioni per le stanze attorno, anche per coloro che riconoscono la voce,
           pensare anche alla suddivisione tra social gestuali e 'rumorosi' per gli smile-espressioni around
    - (TD) modulazione della voce a seconda delle dimensioni di chi parla e della sua voice_potence
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    if not channel:
        log.bug("channel non è un parametro valido: %r" % channel)
        return False

    # -------------------------------------------------------------------------

    if entity.IS_ROOM:
        return False

    objective = OBJECTIVE_ROOM  # obiettivo del messaggio
    # Linguaggio utilizzato per dire il messaggio
    if entity.IS_ITEM:
        language = LANGUAGE.COMMON
    else:
        language = entity.speaking
    smile = ""  # conterrà l'eventuale espressione di uno smile-social
    emote = ""  # conterrà l'eventuale emote inviato con il messaggio tra due asterischi
    expres_entity = ""  # espressione per chi parla
    expres_room = ""  # espressione per chi sta ascoltando nella stanza
    expres_objective = ""  # espressione per chi riceverà il messaggio

    # Ricava i verbi e il colore relativi al canale
    # Se si sta parlando normalmente la propria lingua vengono utilizzati
    # i verbi razziali per descriverne timbro, flessione o pronuncia
    if channel == CHANNEL.SAY:
        verb_you, verb_it = entity.race.say_verb_you, entity.race.say_verb_it
    else:
        verb_you, verb_it = channel.verb_you, channel.verb_it
    color = get_first_color(channel.name)

    # Se non è stato passato nessun messaggio esce
    if not argument or not remove_colors(argument):
        entity.send_output("Cosa vorresti %s?" % channel)
        return False

    if len(argument) > config.max_google_translate:
        entity.send_output("Non puoi %s un messaggio così logorroico." %
                           channel)
        return False

    # Copia l'argomento originale, in alcuni casi serve recuperarlo poi
    original_argument = argument

    # Controlla se si sta parlando a qualcuno, il controllo sulla particella
    # la esegue in minuscolo, dando per sottinteso che quando uno scrive
    # maiuscolo voglia iniziare un discorso
    target = None
    if argument[0:2] == "a ":
        arg, argument = one_argument(argument)
        # Se sta parlando a qualcuno cerca di acquisirlo dal nome successivo
        objective_name, argument = one_argument(argument)
        target = entity.find_entity_extensively(objective_name)
        # con me e self esegue un check senza la is_same volutamente, per evitare
        # ricerche con nome di player che iniziano con Me o Self
        if target == entity or objective_name in ("me", "self"):
            objective = OBJECTIVE_SELF
            # Se si parla da soli lo si fa utilizzando la lingua madre
            language = entity.race.natural_language
        elif target:
            objective = OBJECTIVE_TARGET
            # Se si parla con qualcuno della stessa razza lo si fa utilizzando
            # la lingua preferita dalla razza, è un fattore culturale
            if entity.race == target.race:
                language = entity.race.natural_language
        else:
            # Se non ha trovato nessun 'a <nome bersaglio>' riprende
            # l'argument originale
            argument = original_argument
    # Stessa cosa di sopra ma qui controlla se si stia parlando al gruppo
    elif argument[0:3] == "al ":
        arg, argument = one_argument(argument)
        objective_name, argument = one_argument(argument)
        if is_prefix(objective_name, "gruppo"):
            if not entity.group:
                entity.send_output("Non fai parte di nessun gruppo.")
                return False
            # Questa variabile verrà utilizza poi nell'invio del messaggio
            group_members = entity.get_members_here(entity.location)
            if not group_members:
                entity.send_output(
                    "Non trovi nessun membro del gruppo vicino a te con cui poter parlare."
                )
                return False
            objective = OBJECTIVE_GROUP
            # Se si parla in un gruppo in cui tutti sono formati dalla stessa
            # razza si preferirà parlare con la lingua della propria razza
            for group_member in group_members:
                if group_member.race != entity.race:
                    break
            else:
                language = entity.race.natural_language
        else:
            # Se il personaggio non vuole parlare al gruppo recupera
            # il valore originale inviato
            argument = original_argument

    # (TD) Gestisce il caso in cui l'entità si trovi immersa in un liquido
    #if entity.is_immersed():
    #    entity.send_output("Tenti di %s qualcosa ma subito l'acqua ti riempie la gola soffocandoti!" % channel)
    #    entity.points.life -= random.randint(entity.level / 6, entity.level / 4) + 1
    #    return False

    if not entity.location:
        log.bug(
            "entity %s non si trova in una locazione valida: %r (original_argument: %s)"
            % (entity.code, entity.location, original_argument))
        return False

    # Gestisce le stanze che obbligano al silenzio
    if entity.location.IS_ROOM:
        if ROOM.SILENCE in entity.location.flags:
            entity.send_output(
                "Il silenzio del luogo ti blocca la gola impedendoti di %s." %
                channel)
            return False

        # (TT) Se nella stanza c'è molto casino, tante persone etc etc è difficile
        # parlare piano
        if entity.location.mod_noise > 75 and channel <= CHANNEL.SAY:
            entity.send_output("Non puoi %s con tutta questa confusione!" %
                               channel)
            return False

    # Invia l'appropriato messaggio nel caso in cui trovi argument vuoto
    if not argument:
        send_not_argument_message(entity, objective, channel)
        return False

    # Cerca eventuali smiles nella stringa controllando gli ultimi caratteri
    for social in database["socials"].itervalues():
        if not social.smiles:
            continue
        for single_smile in social.smiles.split():
            if single_smile in argument[-config.chars_for_smile:]:
                break
        else:
            # Se non trova nessun smile esce dal ciclo dei social e continua
            # col prossimo set di smiles trovato
            continue

        cut_smile = argument.rfind(single_smile)
        # Se argument è formato solo dallo smile invia il corrispondente social
        if cut_smile == 0:
            social_name = social.fun_name[len("social_"):]
            if objective == OBJECTIVE_TARGET:
                input_to_send = "%s %s" % (social_name, target.name)
            elif objective == OBJECTIVE_SELF:
                input_to_send = "%s %s" % (social_name, entity.name)
            else:
                input_to_send = social_name

            send_input(entity,
                       input_to_send,
                       "en",
                       show_input=False,
                       show_prompt=False)
            return True

        # Altrimenti ne ricava l'espressione dello smile-social e toglie lo
        # smile da argument, se il carattere dopo lo smile era un simbolo di
        # punteggiatura lo attacca alla frase togliendo gli spazi
        first_part = argument[:cut_smile]
        second_part = argument[cut_smile + len(single_smile):]
        if second_part.strip() and second_part.strip()[0] in "!?.,:;":
            first_part = first_part.rstrip()
            second_part = second_part.lstrip()
        argument = first_part.rstrip() + second_part.rstrip()
        smile = " %s" % social.expression
        break

    # Elabora i punti esclamativi e interrogativi per il canale say.
    # Qui viene utilizzata l'opzione chars_for_smile visto che si sta facendo
    # una cosa simile a sopra, ovvero considerare solo l'ultima parte
    # dell'argomento passato.
    exclamations = argument[-config.chars_for_smile:].count("!")
    questions = argument[-config.chars_for_smile:].count("?")
    if exclamations > questions:
        if channel == CHANNEL.SAY:
            verb_you = "Esclami"
            verb_it = " esclama"
        exclaim = True
    elif exclamations < questions:
        if channel == CHANNEL.SAY:
            verb_you = "Domandi"
            verb_it = " domanda"
        ask = True
    # Questo elif sottintende che exclamations e questions siano uguali
    elif exclamations != 0 and questions != 0:
        # Con una stessa quantità di ! e di ? l'ultimo che viene trovato
        # ha maggiore peso rispetto all'altro
        exclamation_pos = argument.rfind("!")
        question_pos = argument.rfind("?")
        if exclamation_pos > question_pos:
            if channel == CHANNEL.SAY:
                verb_you = "Esclami"
                verb_it = " esclama"
            exclaim = True
        else:
            if channel == CHANNEL.SAY:
                verb_you = "Domandi"
                verb_it = " domanda"
            ask = True

    # Supporto per piccoli emote separati da * ad inizio argument
    if argument[0] == "*":
        cut_emote = argument[1:].find("*")
        if cut_emote != -1:
            emote = " %s" % argument[1:cut_emote + 1].strip()
            if smile:
                emote = " e%s" % emote
            argument = argument[cut_emote + 2:].strip()

    # Unisce i vari pezzi per formare l'output
    expres_entity = verb_you
    expres_room = verb_it
    expres_target = ""
    if objective == OBJECTIVE_TARGET:
        name = target.get_name(entity)
        expres_entity += " a %s" % name
        expres_room += " a %s" % name
        expres_target += " ti%s" % verb_it
    elif objective == OBJECTIVE_SELF:
        expres_entity += " a te stess%s" % grammar_gender(entity)
        expres_room += " a sé stess%s" % grammar_gender(entity)
    elif objective == OBJECTIVE_GROUP:
        members = entity.get_members_here(entity.location)
        if len(members) == 1:
            expres_entity += " a %s" % members[0].name
            expres_room += " a %s" % members[0].name
            expres_target += " ti%s" % verb_it
        else:
            if len(members) > 5:
                many = "folto "
            else:
                many = ""
            expres_entity += " al gruppo"
            expres_room += " ad un %sgruppo" % many
            expres_target += "%s al gruppo" % verb_it
    # Aggiunge le eventuali espressioni dello smile e dell'emote
    expres_entity += smile + emote
    expres_room += smile + emote
    expres_target += smile + emote

    if not argument:
        send_not_argument_message(entity, objective, channel)
        return False

    # Prepara il pezzo riguardante la lingua utilizzata
    language = ""
    if not entity.IS_ITEM and entity.speaking != LANGUAGE.COMMON:
        language = " in lingua %s" % entity.speaking

    # Mischia il testo se si è ubriachi
    original_argument = argument = color_first_upper(argument)
    argument = drunk_speech(argument, entity)

    # Parlando si impara la lingua
    if not entity.IS_ITEM:
        learn_language(entity, channel, entity.speaking)

    # Controlla se vi sono parolacce o parole offrpg e logga i relativi argument
    if entity.IS_PLAYER:
        check_for_badwords(entity, argument)

    # Invia il messaggio a tutti coloro che lo possono sentire
    for location in expand_voice_around(entity, channel):
        if not location:
            log.bug(
                "location per il canale %s e per l'entità %s non è valida: %r"
                % (channel, entity.code, location))
            continue
        for listener in location.iter_contains(use_reversed=True):
            if listener.position <= POSITION.SLEEP:
                continue

            if listener == entity:
                force_return = check_trigger(entity, "before_rpg_channel",
                                             listener, entity, target,
                                             argument, ask, exclaim,
                                             behavioured)
                if force_return:
                    continue
                force_return = check_trigger(
                    entity, "before_" + channel.trigger_suffix, listener,
                    entity, target, argument, ask, exclaim, behavioured)
                if force_return:
                    continue

                # Invia all'entità il suo stesso messaggio
                first_part = (close_color(color) + expres_entity).rstrip()
                message = "%s: '%s'" % (first_part, close_color(argument))
                send_channel_message(entity, message, True)

                force_return = check_trigger(entity, "after_rpg_channel",
                                             listener, entity, target,
                                             argument, ask, exclaim,
                                             behavioured)
                if force_return:
                    continue
                force_return = check_trigger(entity,
                                             "after_" + channel.trigger_suffix,
                                             listener, entity, target,
                                             argument, ask, exclaim,
                                             behavioured)
                if force_return:
                    continue
            else:
                # Fa ascoltare solo ad un'entità di un eventuale gruppo fisico
                listener = listener.split_entity(1)

                force_return = check_trigger(listener,
                                             "before_listen_rpg_channel",
                                             listener, entity, target,
                                             argument, ask, exclaim,
                                             behavioured)
                if force_return:
                    continue
                force_return = check_trigger(
                    listener, "before_listen_" + channel.trigger_suffix,
                    listener, entity, target, argument, ask, exclaim,
                    behavioured)
                if force_return:
                    continue

                # Prepara alcune cose a seconda della stanza di provenienza del messaggio
                if entity.location == listener.location:
                    entity_name = entity.get_name(listener)
                    entity_name = color_first_upper(entity_name)
                    from_direction = ""
                elif entity.location.IS_ROOM:
                    # (TD) invia qualcuno a meno che non lo si abbia conosciuto
                    # precedentemente con il sistema di presentazione
                    entity_name = "Qualcuno"
                    from_direction = get_from_direction(
                        listener.location.x, listener.location.y,
                        listener.location.z, entity.location.x,
                        entity.location.y, entity.location.z)
                elif entity.location.IS_ACTOR:
                    if entity.location != listener:
                        entity_name = "Qualcuno"  # (TD) come sopra
                    from_direction = " dall'inventario di %s" % entity.location.get_name(
                        listener)
                else:
                    entity_name = "Qualcuno"  # (TD) come sopra
                    from_direction = " da dentro %s" % entity.location.get_name(
                        listener)

                # Prepara la prima parte, quella senza il messaggio
                if objective == OBJECTIVE_ROOM:
                    output = "%s%s%s%s" % (entity_name,
                                           close_color(color) + expres_room,
                                           language, from_direction)
                elif objective == OBJECTIVE_TARGET or OBJECTIVE_SELF:
                    if listener == target:
                        output = "%s%s%s%s" % (
                            entity_name, close_color(color) + expres_target,
                            language, from_direction)
                    else:
                        output = "%s%s%s%s" % (
                            entity_name, close_color(color) + expres_room,
                            language, from_direction)
                elif objective == OBJECTIVE_GROUP:
                    if listener in group_members:
                        output = "%s%s%s%s" % (
                            entity_name, close_color(color) + expres_target,
                            language, from_direction)
                    else:
                        output = "%s%s%s%s" % (
                            entity_name, close_color(color) + expres_room,
                            language, from_direction)

                output = "<br>%s: '%s'" % (close_color(output).rstrip(),
                                           close_color(argument))
                send_channel_message(listener, output, False)
                listener.send_prompt()

                force_return = check_trigger(listener,
                                             "after_listen_rpg_channel",
                                             listener, entity, target,
                                             argument, ask, exclaim,
                                             behavioured)
                if force_return:
                    continue
                force_return = check_trigger(
                    listener, "after_listen_" + channel.trigger_suffix,
                    listener, entity, target, argument, ask, exclaim,
                    behavioured)
                if force_return:
                    continue

    return True
Beispiel #32
0
def command_loop(entity, argument):
    """
    Permette di freezare il loop del gioco. Comodo per disattivare i behaviour
    in fase di test.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    # -------------------------------------------------------------------------

    if not argument:
        output = []
        output.append(get_command_syntax(entity, "command_loop"))
        output.append('''<table class="mud">''')
        for loop in LOOPS:
            loop_name = loop.__class__.__name__.replace("Loop", "").lower()
            output.append('''<tr><td>Attualmente %s%s</td>''' % ("l'" if is_vowel(loop_name[0]) else "il ", loop_name))
            output.append('''<td>%sè[close] in pausa</td>''' % ("[red]" if loop.paused else "[white]non "))
            output.append('''<td>e%sè[close] stoppato.</td></tr>''' % (" [white]non " if loop.running else "d [red]"))
        output.append('''</table>''')
        output.append('''Ricordo che i reset non fanno parte dei loop, ma di un sistema di deferred separato.''')
        entity.send_output("".join(output))
        return False

    # -------------------------------------------------------------------------

    arg, argument = one_argument(argument)

    for loop in LOOPS:
        loop_name = loop.__class__.__name__.replace("Loop", "").lower()
        if is_prefix(arg, loop_name):
            break
    else:
        entity.send_output("Non esiste nessun loop chiamato [white]%s[close]" % arg)
        return False

    if not argument:
        entity.send_output("Vuoi eseguire una [green]pausa[close] o un [green]continua[close] %s%s?" % (
            "all'" if is_vowel(loop_name[0]) else "al ", loop_name))
        return False

    article = "L'" if is_vowel(loop_name[0]) else "Il "

    if is_prefix(argument, ("pausa", "pause")):
        if loop.paused:
            entity.send_output("%s%s si trova già in pausa." % (article, loop_name))
        else:
            entity.send_output("%s%s ora è stato messo in pausa" % (article, loop_name))
            loop.paused = True
    elif is_prefix(argument, ("continua", "continue")):
        if loop.paused:
            entity.send_output("%s%s ora ricomincerà a girare." % (article, loop_name))
            loop.paused = False
        else:
            entity.send_output("%s%s sta già girando." % (article, loop_name))
    else:
        entity.send_output("[white]%s[close] non è un argomento valido da passare al comando loop." % argument)
        return False

    return True
Beispiel #33
0
def command_restring(entity, argument=""):
    """
    Permette di modificare la short il nome e la descrizione dell'oggetto voluto.
    """
    if not entity:
        log.bug("entity non è un parametro valido: %r" % entity)
        return False

    # -------------------------------------------------------------------------

    if not argument:
        syntax = get_command_syntax(entity, "command_restring")
        entity.send_output(syntax, break_line=False)
        return False

    arg1, argument = one_argument(argument)

    target = entity.find_entity_extensively(arg1, inventory_pos="first")
    if not target:
        entity.send_output(
            "Nessuna entità trovata con argomento [white]%s[close]." % arg1)
        return False

    if not argument:
        output = "[white]%s[close]:\n" % target.code
        output += '''<table class='mud'>'''
        if not target.IS_PLAYER:
            output += '''<tr><td>KeywordsName:</td><td>%s</td></tr>''' % target.keywords_name
            output += '''<tr><td>KeywordsShort:</td><td>%s</td></tr>''' % target.keywords_short
            output += '''<tr><td>KeywordsShortNight:</td><td>%s</td></tr>''' % target.keywords_short_night
        output += '''<tr><td>Name:</td><td>%s</td></tr>''' % target.name
        if target.short:
            output += '''<tr><td>Short:</td><td>%s</td></tr>''' % target.short
        if target.short_night:
            output += '''<tr><td>ShortNight:</td><td>%s</td></tr>''' % target.short_night
        if target.long:
            output += '''<tr><td>Long:</td><td>%s</td></tr>''' % target.long
        if target.long_night:
            output += '''<tr><td>LongNight:</td><td>%s</td></tr>''' % target.long_night
        output += '''<tr><td>Descr:</td><td>%s</td></tr>''' % target.descr
        if target.descr_night:
            output += '''<tr><td valign="top">DescrNight:</td><td>%s</td></tr>''' % target.descr_night
        if target.descr_hearing:
            output += '''<tr><td valign="top">DescrHearing:</td><td>%s</td></tr>''' % target.descr_hearing
        if target.descr_hearing_night:
            output += '''<tr><td valign="top">DescrHearingNight:</td><td>%s</td></tr>''' % target.descr_hearing_night
        if target.descr_smell:
            output += '''<tr><td valign="top">DescrSmell:</td><td>%s</td></tr>''' % target.descr_smell
        if target.descr_smell_night:
            output += '''<tr><td valign="top">DescrSmellNight:</td><td>%s</td></tr>''' % target.descr_smell_night
        if target.descr_touch:
            output += '''<tr><td valign="top">DescrTouch:</td><td>%s</td></tr>''' % target.descr_touch
        if target.descr_touch_night:
            output += '''<tr><td valign="top">DescrTouchNight:</td><td>%s</td></tr>''' % target.descr_touch_night
        if target.descr_taste:
            output += '''<tr><td valign="top">DescrTaste:</td><td>%s</td></tr>''' % target.descr_taste
        if target.descr_taste_night:
            output += '''<tr><td valign="top">DescrTasteNight:</td><td>%s</td></tr>''' % target.descr_taste_night
        if target.descr_sixth:
            output += '''<tr><td valign="top">DescrSixth:</td><td>%s</td></tr>''' % target.descr_sixth
        if target.descr_sixth_night:
            output += '''<tr><td valign="top">DescrSixthNight:</td><td>%s</td></tr>''' % target.descr_sixth_night
        output += '''</table>'''
        if target.IS_PLAYER and not target.game_request:
            entity.send_output(
                "Il giocatore %s è [darkslategray]offline[close]")
        entity.send_output(output, break_line=False)
        return True

    arg2, argument = one_argument(argument)
    attribute = ""
    if is_prefix(arg2, ("KeywordsName", "keywords_name")):
        attribute = "keywords_name"
        attr_descr = "le parole chiavi del nome"
    elif is_prefix(arg2, ("KeywordsShort", "keywords_short")):
        attribute = "keywords_short"
        attr_descr = "le parole chiavi della short"
    elif is_prefix(arg2, ("KeywordsShortNight", "keywords_short_night")):
        attribute = "keywords_short_night"
        attr_descr = "le parole chiavi della short notturna"
    elif is_prefix(arg2, ("Name", "nome")):
        attribute = "name"
        attr_descr = "il nome"
    elif is_prefix(arg2, ("Short", "corta")):
        attribute = "short"
        attr_descr = "la short"
    elif is_prefix(arg2, ("ShortNight", "short_night")):
        attribute = "short_night"
        attr_descr = "la short notturna"
    elif is_prefix(arg2, ("Long", "lunga")):
        attribute = "long"
        attr_descr = "la long"
    elif is_prefix(arg2, ("LongNight", "long_night")):
        attribute = "long_night"
        attr_descr = "la long notturna"
    elif is_prefix(arg2, ("Descr", "descr", "Descrizione", "description")):
        attribute = "descr"
        attr_descr = "la descrizione"
    elif is_prefix(arg2, ("DescrNight", "descr_night")):
        attribute = "descr_night"
        attr_descr = "la descrizione notturna"
    elif is_prefix(arg2, ("DescrHearing", "descr_hearing")):
        attribute = "descr_hearing"
        attr_descr = "la descrizione uditiva"
    elif is_prefix(arg2, ("DescrHearingNight", "descr_hearing_night")):
        attribute = "descr_hearing_night"
        attr_descr = "la descrizione uditiva notturna"
    elif is_prefix(arg2, ("DescrSmell", "descr_smell")):
        attribute = "descr_smell"
        attr_descr = "la descrizione olfattiva"
    elif is_prefix(arg2, ("DescrSmellNight", "descr_smell_night")):
        attribute = "descr_smell_night"
        attr_descr = "la descrizione olfattiva notturna"
    elif is_prefix(arg2, ("DescrTouch", "descr_touch")):
        attribute = "descr_touch"
        attr_descr = "la descrizione tattile"
    elif is_prefix(arg2, ("DescrTouchNight", "descr_touch_night")):
        attribute = "descr_touch_night"
        attr_descr = "la descrizione tattile notturna"
    elif is_prefix(arg2, ("DescrTaste", "descr_taste")):
        attribute = "descr_taste"
        attr_descr = "la descrizione gustativa"
    elif is_prefix(arg2, ("DescrTasteNight", "descr_taste_night")):
        attribute = "descr_taste_night"
        attr_descr = "la descrizione gustativa notturna"
    elif is_prefix(arg2, ("DescrSixth", "descr_sixth")):
        attribute = "descr_sixth"
        attr_descr = "la descrizione intuitiva"
    elif is_prefix(arg2, ("DescrSixthNight", "descr_sixth_night")):
        attribute = "descr_sixth_night"
        attr_descr = "la descrizione intuitiva notturna"

    if not attribute:
        syntax = "L'etichetta da modificare all'entità '%s' è errata: %s" % (
            target.code, arg2)
        syntax += get_command_syntax(entity, "command_restring")
        entity.send_output(syntax, break_line=False)
        return False

    if not argument:
        syntax = "Il testo da sostituire nell'etichetta è vuoto."
        syntax += get_command_syntax(entity, "command_restring")
        entity.send_output(syntax, break_line=False)
        return False

    if not check_colors(argument):
        entity.send_output("Errore nella colorazione del testo: %s" % argument)
        return False

    if getattr(target, attribute) == argument:
        entity.send_output(
            "Inutile modificare %s di '%s' con un'altra stringa uguale." %
            (attr_descr, target.code))
        return False

    # Se si sta rinominando un giocatore allora si tiene traccia del vecchio nome
    if target.IS_PLAYER:
        if attribute == "name":
            argument = color_first_upper(argument)
            err_msg_name = get_error_message_name(argument, True, "players")
            if err_msg_name:
                entity.send_output(err_msg_name)
                return False
            if not is_same(argument, target.name):
                target.old_names += " " + target.name
            # (TD) fare anche i messaggi d'avviso per gli altri attributi? da pensare
            target.send_output("\nTi è stato cambiato il nome da %s a %s" %
                               (target.name, argument))
            target.send_prompt()
        elif attribute in ("keywords_name", "keywords_short",
                           "keywords_short_night"):
            entity.send_output("È impossibile modificare %s nei giocatori." %
                               attr_descr)
            return False

    setattr(target, attribute, argument)
    entity.send_output(
        "Hai modificato il testo dell'etichetta %s di '%s' in %s" %
        (to_capitalized_words(attribute), target.code, argument))
    return True