Example #1
0
    def __init__(self, code=""):
        super(Mob, self).__init__()
        BehaviourUpdaterSuperclass.__init__(self)

        self.code = ""
        self.prototype = None
        if code:
            self.reinit_code(code)
            copy_existing_attributes(self.prototype,
                                     self,
                                     except_these_attrs=["code"])
            self.after_copy_existing_attributes()

        # Eventuale inizializzazione dei punti
        if self.max_life == 0:
            self.max_life = config.starting_points
        if self.max_mana == 0:
            self.max_mana = config.starting_points
        if self.max_vigour == 0:
            self.max_vigour = config.starting_points
        if self.life == 0:
            self.life = self.max_life
        if self.mana == 0:
            self.mana = self.max_mana
        if self.vigour == 0:
            self.vigour = self.max_vigour

        if self.hand == HAND.NONE:
            self.hand = self.hand.randomize()

        # Variabili proprie di una istanza di mob:
        self.area = None
        self.attack = 1
        self.defense = 1
        self.speaking = Element(
            LANGUAGE.COMMON
        )  # Indica con quale linguaggio sta attualmente parlando il mob
        self.style = Element(
            STYLE.NONE)  # Style di combattimento che sta utilizzando
        self.experience = 0  # Esperienza accumulata prima di poter livellare
        self.mount = None  # Indica quale mob o pg sta cavalcando
        self.mounted_by = None  # Indica da quali mob o pg è cavalcato
        self.specials = {
        }  # E' una lista di variabili speciali, possono essere utilizzate come delle flags, vengono aggiunte di solito nei gamescript
        self.reply = None  # Entità a cui si può replicare
        #       self.tracking        = Track()  # Serve quando il mob inizia a tracciare e cacciare una preda fuggita
        self.last_fight_time = None
        self.last_death_time = None

        # Contatori di statistica
        self.defeat_from_mob_counter = 0  # Conteggio delle sconfitte
        self.defeat_from_item_counter = 0  # Conteggio delle sconfitte
        self.defeat_from_player_counter = 0  # Conteggio delle sconfitte
        self.death_from_player_counter = 0  # Conteggio delle sconfitte
        self.mob_defeated_counter = 0  # Conteggio delle vittorie sui mob
        self.item_defeated_counter = 0  # Conteggio degli oggetti distrutti
        self.player_defeated_counter = 0  # Conteggio delle vittorie sui giocatori
        self.player_killed_counter = 0  # Conteggio delle volte che viene ucciso un giocatore

        check_trigger(self, "on_init", self)
Example #2
0
    def __init__(self, size):
        """Construct a square TetrisGrid with the given size."""

        # Initialise grid squares
        grid_squares = []
        for column_index in range(0, size):
            column = []
            for row_index in range(0, size):
                column.append(GridSquare())
            grid_squares.append(column)

        super(TetrisGrid, self).__init__(
            attrs_dict={
                "_size": size,
                "x_bounds": (0, size - 1),
                "y_bounds": (0, size - 1),
                "grid_squares": grid_squares
            })

        # Populate grid with fixed elements
        for row_num in range(*self.y_bounds):
            # Left Wall
            self._get_grid_square(Position(self.x_bounds[0],
                                           row_num)).fill_with(
                                               Element(ElementType.WALL))
            # Right wall
            self._get_grid_square(Position(self.y_bounds[-1],
                                           row_num)).fill_with(
                                               Element(ElementType.WALL))

        # Floor
        for col_num in range(*self.y_bounds):
            self._get_grid_square(Position(col_num,
                                           self.y_bounds[0])).fill_with(
                                               Element(ElementType.WALL))
Example #3
0
    def render_POST(self, request, conn):
        #if conn.new_player and conn.new_player.code in database["players"]:
        #    return "\nImpossibile creare il personaggio %s perché già esistente.\n" % conn.new_player.name

        page = self.check_number_of_players(request, conn)
        if page:
            return page

        # Ricava gli argomenti del form dalla richiesta
        race = ""
        if "race" in request.args:
            race = Element(request.args["race"][0])

        sex = ""
        if "sex" in request.args:
            sex = Element(request.args["sex"][0])

        constellation = ""
        if "constellation" in request.args:
            constellation = Element(request.args["constellation"][0])

        # Controlla la validità degli argomenti inseriti nel form
        err_msg_race = ""
        if not race:
            err_msg_race = "Scegli la razza che vuoi interpretare"
            race = RACE.NONE
        else:
            # (TD) per ora gestisce la sessualità unica delle Frijen in maniera forzata
            if race == RACE.FRIJEN:
                sex = SEX.FEMALE

        err_msg_sex = ""
        if not sex:
            err_msg_sex = "Scegli la sessualità che vuoi interpretare"
            sex = SEX.NONE

        err_msg_constellation = ""
        if not constellation:
            err_msg_constellation = "Scegli la costellazione sotto cui il tuo personaggio è nato"
            constellation = CONSTELLATION.NONE

        # Se tutti gli argomenti del form sono validi crea il personaggio e
        # passa alla pagina di creazione successiva
        if not err_msg_race and not err_msg_sex and not err_msg_constellation:
            new_player = Player()
            new_player.race = race
            new_player.sex = sex
            new_player.constellation = constellation
            conn.new_player = new_player
            request.redirect("create_player2.html")
            request.finish()
            return server.NOT_DONE_YET

        return self.create_page(request, conn, race, sex, constellation,
                                err_msg_race, err_msg_sex,
                                err_msg_constellation)
Example #4
0
 def __init__(self, season=SEASON.NONE):
     self.season = Element(season)
     self.temperature = 17  # In gradi centigradi
     self.wind_direction = Element(DIR.NONE)  # Direzione del vento
     self.cloud_color = Element(COLOR.NONE)  # Colore delle nuvole
     self.cloud = 25  # Densità delle nuvole del cielo: 0 è limpido, 100 è completamente coperto
     self.humidity = 20  # Umidità nell'aria: 0 deserto secco, 100 foresta pluviale
     self.fog = 10  # Probabilità che vi sia la nebbia, da 0 a 100
     self.rain = 15  # Probabilità che piova, da 0 a 100 (se la temperatura è bassa si tramuta in neve)
     self.hail = 2  # Probabilità che grandini, da 0 a 100
     self.snow = 3  # Probabilità che nevichi
     self.lightning = 5  # Probabilità che tuoni e fulmini, da 0 a 100
Example #5
0
    def test_should_fill_with_element(self):  # noqa: D102
        grid_square = GridSquare()
        element = Element(ElementType.WALL)

        grid_square.fill_with(element)

        self.assertFalse(grid_square.is_empty())
Example #6
0
 def __init__(self):
     self.comment         = ""
     self.fun_name        = ""  # Nome della funzione del comando legato al social
     self.intention       = Element(INTENTION.NONE)  # Tipologia di intenzione
     self.smiles          = ""  # Elenco degli smile supportati dal social
     self.expression      = ""  # Espressione relativa al'utilizzo degli smile
     self.racial_messages = EnumElementDict()
Example #7
0
    def fread_the_line(self, file, line, attr):
        if not file:
            log.bug("file non è un parametro valido: %r" % file)
            return

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

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

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

        if "," in line:
            material, percent = line.split(",", 1)
        else:
            material, percent = line.split(None, 1)

        material = material.strip()
        percent = percent.strip()

        self.material = Element(material)
        self.percent = fread_percent(file, percent, attr)
Example #8
0
    def fread_the_line(self, file, line, attr):
        if not file:
            log.bug("file non è un parametro valido: %r" % file)
            return

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

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

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

        try:
            entitype, percent, buyback_percent = line.split(None, 2)
        except ValueError:
            log.bug(
                "Errore nella lettura di un Sellable nel file <%s> per la linea <%s> e l'attributo <%s>"
                % (file.name, line, attr))
            return

        self.entitype = Element(entitype)
        self.percent = fread_percent(file, percent, attr)
        self.buyback_percent = fread_percent(file, buyback_percent, attr)
Example #9
0
    def test_should_clear(self):  # noqa: D102
        grid_square = GridSquare()
        element = Element(ElementType.WALL)
        grid_square.fill_with(element)

        grid_square.clear()

        self.assertTrue(grid_square.is_empty())
Example #10
0
 def _wait_for_element(self):
     self._element = Element(self._driver, self._locator, self._position)
     WebDriverWait(self._driver, self._timeout).until(
         EC.visibility_of_element_located(
             (By.XPATH, self._element.locator)),
         "{} is not visible after {} seconds".format(
             self._element.name, self._timeout))
     self._position = 0
Example #11
0
    def __init__(self, fun_name=""):
        self.comment = ""
        self.fun_name = fun_name or ""  # Nome della funzione
        self.type = Element(CMDTYPE.INFORMATION)  # Tipologia del comando
        self.trust = Element(TRUST.PLAYER)  # Fiducia minima per digitarlo
        self.position = Element(
            POSITION.REST)  # Posizione minima per utilizzarlo
        self.flags = Flags(CMDFLAG.NONE)  # Flag dei comandi
        self.no_races = Flags(
            RACE.NONE
        )  # Razze che NON possono usarlo (RACE.NONE significa che tutti lo possono utilizzare)
        self.mini_help = ""  # Piccola descrizione dell'utilizzo del comando
        self.timer = 0.0  # Tempo totale di esecuzione del comando (anche se nelle pagine d'amministrazione visualizza il tempo medio)

        # Variabili volatili
        self.module = None  # Riferimento al modulo che contiene la funzione
        self.function = None  # Riferimento alla funzione
        if self.fun_name:
            self.import_module_and_function()
Example #12
0
    def load(self):
        filepath = "persistence/calendar.rpg"
        try:
            file = open(filepath, "r")
        except IOError:
            log.bug("Impossibile aprire il file %s in lettura" % filepath)
            return

        for line in file:
            if not line.strip():
                continue
            if line[0] == "#":
                continue
            break
        else:
            log.bug("Non è stato trovato nessuna riga valida al file %s" %
                    filepath)
            file.close()
            return
        file.close()

        values = line.split()
        if len(values) != 5:
            log.bug(
                "E' stato trovato un numero inatteso di valori al file %s: %d"
                % (filepath, len(values)))
            return

        if is_number(values[0]):
            self.minute = int(values[0])
        else:
            log.bug("minute del file %s non sono un numero valido: %s" %
                    values[0])

        if is_number(values[1]):
            self.hour = int(values[1])
        else:
            log.bug("hour del file %s non sono un numero valido: %s" %
                    values[1])

        if is_number(values[2]):
            self.day = int(values[2])
        else:
            log.bug("day del file %s non sono un numero valido: %s" %
                    values[2])

        self.month = Element(values[3])

        if is_number(values[4]):
            self.year = int(values[4])
        else:
            log.bug("year del file %s non sono un numero valido: %s" %
                    values[4])

        self.get_error_message()
Example #13
0
 def __init__(self):
     self.comment          = ""
     self.code             = ""   # Codice identificativo dell'help
     self.italian_keywords = ""   # Parole di ricerca italiane
     self.english_keywords = ""   # Parole di ricerca inglesi
     self.type             = Element(HELP.NONE)  # Tipologia dell'help
     self.text             = ""   # Testo visualizzato da tutti
     self.admin_text       = ""   # Testo visualizzato solo dagli Admin
     self.see_also         = ""   # Voci degli help simili a questo
     self.counter_use      = 0    # Contatore dell'utilizzo dell'help
     self.syntax_function  = None # Eventuale funzione che fa visualizzare la sintassi del comando
Example #14
0
    def __init__(self, code=""):
        self.comment        = ""
        self.code           = code # Codice identificativo dell'area
        self.name           = ""   # Nome esteso
        self.short          = ""   # Descrizioni breve dell'area
        self.short_night    = ""   # Descrizioni breve notturna dell'area
        self.descr          = ""   # Descrizione dell'area per la pagina web della lista delle aree
        self.creators       = ""   # Lista dei creatori, vale il codice dell'account  (TD) in futuro sarà una lista per poter ricavare il riferimento
        self.level          = 1    # Livello base per tutte le entità dell'area, se viene modificato questo anche tutte le entità aumentano o diminuiscono di livello in proporzione
        self.flags          = Flags(AREA.NONE)
#       self.races          = Flags(RACE.NONE)  # Razze che si possono incontrare principalmente nell'area  (TD)
        self.color          = Element(COLOR.NONE)  # Colore dell'area
        self.music          = ""   # File mid avviato quando uno entra nell'area
        self.music_wild     = ""   # File mid avviato quando uno esce dall'area ed entra nella wild
        self.climates       = {}   # Informazioni climatiche dell'area relativamente alle stagioni
        self.maze           = None # Informazioni relative al labirinto
        self.wumpus         = None # Informazioni relative alle aree wumpus
        self.wild           = None # Struttura relativa alla wilderness
        self.landfill_code  = ""   # Codice della stanza prototipo in cui verranno inseriti gli oggetti "da buttare"
        self.repop_time     = 0    # Minuti reali tra un repop di un'entità ed un'altro
        self.room_resets    = []   # Lista dei reset dell'area

        # Attributi relativi alle liste dei messaggi di echo
        self.echoes_dawn               = []
        self.echoes_dawn_no_sun        = []
        self.echoes_sunrise            = []
        self.echoes_sunrise_no_sun     = []
        self.echoes_noon               = []
        self.echoes_noon_no_sun        = []
        self.echoes_sunset             = []
        self.echoes_sunset_no_sun      = []
        self.echoes_dusk               = []
        self.echoes_dusk_no_moon       = []
        self.echoes_dusk_full_moon     = []
        self.echoes_midnight           = []
        self.echoes_midnight_no_moon   = []
        self.echoes_midnight_full_moon = []

        # Attributi volatili:
        self.max_players    = 0  # Numero massimo di giocatori che sono stati presenti contemporaneamente nell'area nella sessione di gioco
        self.upper_limit    = 0  # Limite di coordinata Z verso l'alto oltre la quale si esce dall'area
        self.lower_limit    = 0  # Limite di coordinata Z verso il basso oltre la quale si esce dall'area
        self.rooms          = {} # Stanze in-game nelle rispettive coordinate
        self.players        = [] # Giocatori in-game che si trovano nelll'area
        self.mobs           = [] # Mob in-game che si trovano nell'area
        self.items          = [] # Oggetti in-game che si trovano nell'area
        self.meteo          = Meteo()  # Informazioni meteo in-game dell'area
        self.gamescripts    = {}   # Gamescript a livello di area

        # Liste relative ai dati modello dell'area, i prototipi
        self.proto_rooms    = {}
        self.proto_mobs     = {}
        self.proto_items    = {}
Example #15
0
 def __init__(self, layout, position):
     """Construct a TetrisPiece using the given Layout located at the given Position."""
     super(TetrisPiece, self).__init__(
         attrs_dict={
             'layout':
             layout,
             'position':
             position,
             'elements': [
                 Element(ElementType.PIECE, position.add(elem_position))
                 for elem_position in layout.positions
             ]
         })
Example #16
0
    def __init__(self, name=""):
        self.comment = ""
        self.created_time = datetime.datetime.now(
        )  # Data di creazione del'account
        self.name = name  # Nome di login
        self.password = ""  # Password
        self.email = ""  # Indirizzo e-mail (opzionale)
        self.options = Flags(OPTION.NONE)
        self.show_logs = Flags(LOG.NONE)
        self.aliases = {}  # Dizionario relativo agli alias
        self.macros = {}  # Dizionario relativo alle macro
        # (TD) provare a convertire questi datetime in None e caricarli tramite schema
        self.last_bug_sended_at = None
        self.last_comment_sended_at = None
        self.last_typo_sended_at = None
        self.last_idea_sended_at = None
        self.sended_bugs = 0  # Bug totali inviati
        self.sended_comments = 0  # Typo totali inviati
        self.sended_ideas = 0  # Idee totali inviati
        self.sended_typos = 0  # Typo totali inviati
        self.user_agents = [
        ]  # Informazioni relative ai client browser utilizzati dal giocatore per entrare nel Mud
        self.resolution_width = 0  # Risoluzione in pixel del monitor del client in larghezza
        self.resolution_height = 0  # Risoluzione in pixel del monitor del client in altezza

        # Al primo account creato in assoluto dà poteri di Implementor, dando
        # per scontato che il primo giocatore che utilizza questo Mud sia il
        # futuro amministratore, ai successivi account dona la trust di player
        if not database["accounts"]:
            self.trust = Element(TRUST.IMPLEMENTOR)
        else:
            self.trust = Element(TRUST.PLAYER)

        # Attributi volatili
        self.players = {}  # Dizionario dei giocatori creati dall'account
        self.player = None  # Personaggio che si sta creando o utilizzando
Example #17
0
    def __init__(self, columns=0, rows=0, code_prefix=""):
        self.columns = columns  # Numero di colonne totali del labirinto
        self.rows = rows  # Numero di righe totali del labirinto
        self.code_prefix = code_prefix  # Prefisso del codice delle room utilizzate per il reset
        self.remake_hour = -1  # In quale ora il maze viene ricreato
        self.remake_weekday = Element(WEEKDAY.NONE)
        self.remake_message = ""  # Messaggio di act a tutte le entità nel labirinto durante il relativo remake
        self.passages = [
        ]  # Elenco dei passaggi: entrate, uscite o altre nicchie, collegate al labirinto attorno al suo bordo
        self.dead_ends = [
        ]  # Elenco dei vicoli ciechi casualmente da inserire al posto di quelli standard

        # Variabili volatili
        self.cells = []
        self.track_counter = 0  # Numero di room tracciate dall'algoritmo di creazione del maze
Example #18
0
    def __init__(self, code=""):
        super(ProtoMob, self).__init__()

        self.code = code or ""
        self.height = 0
        self.constellation = Element(
            CONSTELLATION.NONE)  # Costellazione sotto cui è nato il mob
        self.virtue = Element(
            VIRTUE.NONE)  # Virtù che il mob segue principalmente
        self.hand = Element(
            HAND.NONE)  # Indica quale mano utilizza preferibilmente
        self.hometown = ""  # Area che il mob o il pg considera come propria casa
        self.group_name = ""  # Nome del gruppo in cui fa parte, fanno parte tutti i mob che lo hanno uguale
        self.voice_emote = ""  # Stringa che ne descrive la voce nel canale rpg_channel()
        self.voice_potence = 50  # Potenza della voce, 0 o meno significa aver perso la voce, per razze umanoidi i valori sono da 40 a 80, per razze 'minori' o 'maggiori' i valori possono variare e superare anche il 100
        self.parts = {
        }  # Forma, materiale, vita, flags delle parti sono già di default a seconda delle razza, però si possono cambiare anche a livello di file di area
        self.morph = None  # Tipo di morph sotto cui il personaggio è affetto
        self.skill_messages = {
        }  # Dizionario dei messaggi personalizzati riguardanti le skill

        # Attributi
        self.strength = 0
        self.endurance = 0
        self.agility = 0
        self.speed = 0
        self.intelligence = 0
        self.willpower = 0
        self.personality = 0
        self.luck = 0

        # Condizioni
        self.thirst = 0
        self.hunger = 0
        self.sleep = 0
        self.drunkness = 0
        self.adrenaline = 0
        self.mind = 0  # Tale quale a quello dello smaug
        self.emotion = 0  # Tale quale a quello dello smaug
        self.bloodthirst = 0

        self.eye_color = Element(COLOR.NONE)
        self.hair_color = Element(COLOR.NONE)
        self.hair_length = 0
        self.hair_type = Element(HAIRTYPE.NONE)
        self.skin_color = Element(COLOR.NONE)
Example #19
0
 def __init__(self):
     self.comment = ""  # Commento per gli area builder relativo all'entità leggibile
     self.title = ""  # Titolo del libro
     self.author = ""  # Autore o gli autori di questo libro
     self.summary = ""  # Riassunto del libro che il giocatore carpisce esaminandolo
     self.language = Element(LANGUAGE.COMMON)  # (TD) Lingua di questo libro
     self.flags = Flags(
         READABLE.NONE)  # Flag relative alle entità leggibili
     self.visual_width = ""  # Larghezza in pixel del libro sullo schermo
     self.visual_height = ""  # Larghezza in pixel del libro sullo schermo
     self.padding = ""  # Larghezza in pixel del padding della cornice del libro
     self.border_top = ""  # Bordo css decorante il libro in alto
     self.border_right = ""  # Bordo css decorante il libro a destra
     self.border_bottom = ""  # Bordo css decorante il libro in basso
     self.border_left = ""  # Bordo css decorante il libro a sinistra
     self.border_inside = ""  # Bordo css decorante il libro tra le due pagine
     self.number_decoration_left = ""  # Decorazione della pagina sinistra per i numeri di pagina
     self.number_decoration_right = ""  # Decorazione della pagina sinistra per i numeri di pagina
     self.pages = []  # Lista delle pagine e relativo contenuto
Example #20
0
    def render_POST(self, request, conn):
        if not conn.new_player:
            return '''Per qualche errore sul server il personaggio non è stato creato, oppure è stato già creato, controlla la pagina con <a href="players.html">i tuoi personaggi</a>.'''

        # Ricava gli argomenti del form dalla richiesta
        age = 0
        if "age" in request.args:
            age = request.args["age"][0]

        height = 0
        if "height" in request.args:
            height = request.args["height"][0]

        weight = 0
        if conn.new_player.race.weight_low > 1000:
            if "weight" in request.args:
                weight = request.args["weight"][0]
        else:
            weight = random.randint(conn.new_player.race.weight_low,
                                    conn.new_player.race.weight_high)

        hair_color = None
        hair_type = None
        hair_length = 0
        if conn.new_player.race.have_hair:
            if "hair_color" in request.args:
                hair_color = Element(request.args["hair_color"][0])

            if "hair_type" in request.args:
                hair_type = Element(request.args["hair_type"][0])

            if "hair_length" in request.args:
                hair_length = request.args["hair_length"][0]

        eye_color = ""
        if "eye_color" in request.args:
            eye_color = Element(request.args["eye_color"][0])

        skin_color = ""
        if "skin_color" in request.args:
            skin_color = Element(request.args["skin_color"][0])

        hand = ""
        if "hand" in request.args:
            hand = Element(request.args["hand"][0])

        name = ""
        if "name" in request.args:
            name = request.args["name"][0]

        # Controlla la validità degli argomenti inseriti nel form
        err_msg_age = ""
        try:
            age = int(age)
        except ValueError:
            err_msg_age = "L'età deve essere un numero che indica gli anni vissuti dal tuo personaggio"
        else:
            if age < conn.new_player.race.age_adolescence or age > conn.new_player.race.age_old:
                err_msg_age = "I limiti dell'età, relativamente alla razza da te scelta, sono tra %d e %d." % (
                    conn.new_player.race.age_adolescence,
                    conn.new_player.race.age_old)

        err_msg_height = ""
        try:
            height = int(height)
        except ValueError:
            err_msg_height = "L'altezza deve essere un numero in centimetri"
        else:
            if height < conn.new_player.race.height_low or height > conn.new_player.race.height_high:
                err_msg_height = "I limiti dell'altezza, relativamente alla razza da te scelta, sono tra %d e %d" % (
                    conn.new_player.race.height_low,
                    conn.new_player.race.height_high)

        err_msg_weight = ""
        if conn.new_player.race.weight_low > 1000:
            try:
                weight = int(weight)
            except ValueError:
                err_msg_weight = "Il peso deve essere un numero in chili"
            else:
                if weight < conn.new_player.race.weight_low / 1000 or weight > conn.new_player.race.weight_high / 1000:
                    err_msg_weight = "I limiti del peso, relativamente alla razza da te scelta, sono tra %d e %d" % (
                        conn.new_player.race.weight_low / 1000,
                        conn.new_player.race.weight_high / 1000)

        err_msg_haircolor = ""
        err_msg_hairtype = ""
        err_msg_hairlength = ""
        if conn.new_player.race.have_hair:
            if not hair_color:
                err_msg_haircolor = "Scegli il colore di capelli che vuoi dare al tuo personaggio."
                hair_color = COLOR.NONE

            if not hair_type:
                err_msg_hairtype = "Scegli il tipo di tagli di capelli che vuoi per il tuo personaggio."
                hair_type = HAIRTYPE.NONE

            try:
                hair_length = int(hair_length)
            except ValueError:
                err_msg_hairlength = "La lunghezza dei capelli deve essere un numero in centimentri."
            else:
                if hair_length < 0 or hair_length >= conn.new_player.race.height_low:
                    err_msg_hairlength = "La lunghezza dei capelli deve essere un numero tra lo 0 e %d" % (
                        conn.new_player.race.height_low / 2)

        err_msg_eyecolor = ""
        if not eye_color:
            err_msg_eyecolor = "Scegli il colore degli occhi che vuoi dare al tuo personaggio"
            eye_color = COLOR.NONE

        err_msg_skin_color = ""
        if not skin_color:
            err_msg_skin_color = "Scegli il colore della pelle che vuoi dare al tuo personaggio"
            skin_color = COLOR.NONE

        err_msg_hand = ""
        if not hand:
            err_msg_hand = "Scegli qual'è la %s principale del tuo futuro personaggio" % conn.new_player.race.hand
            hand = HAND.NONE

        err_msg_name = ""
        if name:
            name = color_first_upper(name)
            err_msg_name = get_error_message_name(name, False, "players")
        else:
            err_msg_name = "Inserisci il nome del personaggio che vuoi interpretare."

        # Se non ci sono stati errori allora inserisce i dati scelti dal
        # giocatore nell'oggetto personaggio che sta creando e continua
        # la creazione
        if (not err_msg_age and not err_msg_height and not err_msg_weight
                and not err_msg_haircolor and not err_msg_hairtype
                and not err_msg_hairlength and not err_msg_eyecolor
                and not err_msg_skin_color and not err_msg_hand
                and not err_msg_name):
            conn.new_player.age = age
            conn.new_player.birth_month = conn.new_player.constellation.month
            conn.new_player.birth_day = random.randint(1, config.days_in_month)
            conn.new_player.height = height
            if conn.new_player.race.weight_low > 1000:
                conn.new_player.weight = weight * 1000
            else:
                conn.new_player.weight = weight
            conn.new_player.hair_color = hair_color
            conn.new_player.hair_type = hair_type
            conn.new_player.hair_length = hair_length
            conn.new_player.eye_color = eye_color
            conn.new_player.skin_color = skin_color
            conn.new_player.hand = hand
            conn.new_player.name = name
            conn.new_player.code = remove_colors(name)

            # Se vi era un giocatore connesso al gioco allora lo sconnette
            # per poi connettersi con quello nuovo
            if conn.player and conn.player.game_request:
                conn.player.send_output(
                    "\n\nConnessione chiusa per la creazione di un nuovo personaggio."
                )
                conn.player.game_request.finish()

            # Se ha terminato di distribuire tutti i punti allora procede alla
            # creazione e all'inserimento in gioco del nuovo personaggio
            conn.account.player = conn.new_player
            conn.account.players[conn.new_player.code] = conn.new_player
            conn.player = conn.new_player
            conn.player.account = conn.account
            database["players"][conn.new_player.code] = conn.new_player
            conn.new_player = None

            # Se c'è solo il nuovo personaggio nel database allora gli dona
            # il massimo dei permessi
            if len(database["players"]) == 1:
                conn.player.trust = TRUST.IMPLEMENTOR

            # Internet Explorer non riesce a gestire qualche cosa e non si connette
            # direttamente in gioco
            if conn.get_browser().startswith("IE"):
                request.redirect("chaplayersml")
            else:
                request.redirect("game_interface.html?pg_code=%s" %
                                 conn.player.code)
            request.finish()
            return server.NOT_DONE_YET

        return self.create_page(request, conn, age, height, weight, hair_color,
                                hair_type, hair_length, eye_color, skin_color,
                                hand, name, err_msg_age, err_msg_height,
                                err_msg_weight, err_msg_haircolor,
                                err_msg_hairtype, err_msg_hairlength,
                                err_msg_eyecolor, err_msg_skin_color,
                                err_msg_hand, err_msg_name)
Example #21
0
 def __init__(self):
     self.entitype = Element(
         ENTITYPE.NONE
     )  # Tipologia di entità che possono essere venduta al negoziante
     self.percent = 50  # Percentuale sul costo per le entità vendute al negoziante
     self.buyback_percent = 100  # Percentuale sul costo per le entità comprate dal negoziante e precedentemente vendutegli
Example #22
0
def create_random_mob(mob=None,
                      name="",
                      level=0,
                      race=RACE.NONE,
                      sex=SEX.NONE,
                      way=WAY.NONE):
    """
    Crea un nuovo mob con caratteristiche casuali.
    """
    if not name and name != "":
        log.bug("name non è un parametro valido: %r" % name)
        return None

    if level < 0 or level > config.max_level:
        log.bug("level non è un parametro valido: %d" % level)
        return None

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

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

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

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

    # Crea a caso un nome se non è stato passato
    if not name:
        name = create_random_name(race, sex)

    proto_mob_code = random.choice(database["proto_mobs"].keys())
    if not mob:
        mob = Mob(proto_mob_code)
    mob = create_random_entity(mob, name, level, race, sex)

    # (TD) tramite il way è possibile creare un set di skill adatte

    # Crea casualmente gli attributi di entità che non sono stati ancora
    # inizializzati dalla create_random_entity()
    mob.weight = random.randint(mob.race.weight_low, mob.race.weight_high)
    mob.height = random.randint(mob.race.height_low, mob.race.height_high)
    mob.age = random.randint(mob.race.age_adolescence, mob.race.age_old)

    # (TD) Sceglie una descrizione casuale a seconda della razza del sesso e dell'età
    mob.descr = ""
    mob.descr_night = ""

    # Punti
    mob.max_life = random.randint(90, 110)
    mob.max_mana = random.randint(90, 110)
    mob.max_vigour = random.randint(90, 110)
    mob.life = mob.max_life - random.randint(0, mob.max_life / 4)
    mob.mana = mob.max_mana - random.randint(0, mob.max_mana / 4)
    mob.vigour = mob.max_vigour - random.randint(0, mob.max_vigour / 4)

    # Attributi
    mob.strength = random.randint(5, 95)
    mob.endurance = random.randint(5, 95)
    mob.agility = random.randint(5, 95)
    mob.speed = random.randint(5, 95)
    mob.intelligence = random.randint(5, 95)
    mob.willpower = random.randint(5, 95)
    mob.personality = random.randint(5, 95)
    mob.luck = random.randint(5, 95)

    # Condizioni
    mob.thirst = random.randint(0, 25)
    mob.hunger = random.randint(0, 25)
    mob.drunkness = random.randint(0, 25)
    mob.bloodthirst = random.randint(0, 25)
    mob.adrenaline = random.randint(0, 25)
    mob.mind = random.randint(0, 25)
    mob.emotion = random.randint(0, 25)

    # Imposta le altre variabili  # (TD) da migliorare
    mob.attack = random.randint(1, mob.level)
    mob.defense = random.randint(1, mob.level)

    mob.position.randomize(from_element=POSITION.REST,
                           to_element=POSITION.STAND)
    mob.skills = create_random_skills(mob)
    mob.constellation.randomize()
    mob.voice_potence = random.randint(45, 55) + mob.level / 4

    if random.randint(0, 200) == 0:
        mob.flags += Element(FLAG.AMBIDEXTROUS)
    else:
        if random.randint(0, 3) == 0:
            mob.hand = Element(HAND.RIGHT)
        else:
            mob.hand = Element(HAND.LEFT)

    return mob
Example #23
0
 def __init__(self):
     self.material = Element(MATERIAL.NONE)
     self.percent = 0
Example #24
0
 def __init__(self):
     self.minute = 0  # Minuto rpg
     self.hour = 0  # Ora rpg
     self.day = 1  # Giorno rpg
     self.month = Element(MONTH.NONE)  # Mese rpg
     self.year = 0  # Anno rpg
Example #25
0
 def __init__(self):
     self.comment = ""
     self.category = Element(WEAPON.NONE)  # Tipo di arma
     self.flags = Flags(WEAPONFLAG.NONE)  # Flag di arma
     self.damage = ""  # Danno dell'arma, se vuoto viene ricavato automaticamente tramite una tabella
Example #26
0
    def parse_miml_check(self, check, looker=None):
        if not check:
            log.bug("check non è un parametro valido: %r" % check)
            return False

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

        check_parts = check.split()

        if check_parts[0][0:4] == "self":
            check_entity = self
        elif check_parts[0][0:8] == "location":
            if self.IS_ROOM:
                check_entity = self
            else:
                check_entity = self.location
        elif check_parts[0][0:17] == "previous_location":
            if self.IS_ROOM:
                check_entity = self
            else:
                check_entity = self.previous_location
        elif check_parts[0][0:6] == "looker":
            if not looker:
                log.bug(
                    "looker non valido (%r) anche se il check lo necessita: %s"
                    % (looker, check))
                return False
            check_entity = looker
        elif check_parts[0][0:6] == "season":
            if check_parts[1] == "is":
                if calendar.season == Element(check_parts[2]):
                    return True
                else:
                    return False
            elif check_parts[1] == "is not":
                if calendar.season != Element(check_parts[2]):
                    return True
                else:
                    return False
            else:
                log.bug(
                    "Operatore di check sconosciuto: %s per l'elemento con codice %s"
                    % (check_parts[1], check_parts[2]))
                return False
        else:
            log.bug("entità da utilizzare per i check è sconosciuta: %s" %
                    check_parts[0])
            return False

        # (TD) no, dovrò splittare con or o and ed utilizzare le builtin any o all
        #for element_code in check_parts[2].split("|"):
        #    pass

        # Miml relativo alla razza dell'entità controllata
        if check_parts[2][0:5] == "RACE.":
            if check_entity.IS_ROOM:
                return False

            if check_parts[1] == "is":
                if check_entity.race == Element(check_parts[2]):
                    return True
                else:
                    return False
            elif check_parts[1] == "is not":
                if check_entity.race != Element(check_parts[2]):
                    return True
                else:
                    return False
            else:
                log.bug(
                    "Operatore di check sconosciuto: %s per l'elemento con codice %s"
                    % (check_parts[1], check_parts[2]))
                return False
        # Miml relativo alla sessualità dell'entità controllata
        elif check_parts[2][0:4] == "SEX.":
            if check_entity.IS_ROOM:
                return False

            if check_parts[1] == "is":
                if check_entity.sex == Element(check_parts[2]):
                    return True
                else:
                    return False
            elif check_parts[1] == "is not":
                if check_entity.sex != Element(check_parts[2]):
                    return True
                else:
                    return False
            else:
                log.bug(
                    "Operatore di check sconosciuto: %s per l'elemento con codice %s"
                    % (check_parts[1], check_parts[2]))
                return False
        # Miml relativo ai contenitori
        elif check_parts[2][0:10] == "CONTAINER.":
            if check_entity.IS_ROOM or not check_entity.container_type:
                return False

            if check_parts[1] == "is":
                if Element(
                        check_parts[2]) in check_entity.container_type.flags:
                    return True
                else:
                    return False
            elif check_parts[1] == "is not":
                if Element(check_parts[2]
                           ) not in check_entity.container_type.flags:
                    return True
                else:
                    return False
            else:
                log.bug(
                    "Operatore di check sconosciuto: %s per l'elemento con codice %s"
                    % (check_parts[1], check_parts[2]))
                return False
        # Miml relativo al settore di una stanza
        elif check_parts[2][0:7] == "SECTOR.":
            if not check_entity.IS_ROOM:
                return False

            if check_parts[1] == "is":
                if check_entity.sector == Element(check_parts[2]):
                    return True
                else:
                    return False
            elif check_parts[1] == "is not":
                if check_entity.sector != Element(check_parts[2]):
                    return True
                else:
                    return False
            else:
                log.bug(
                    "Operatore di check sconosciuto: %s per l'elemento con codice %s"
                    % (check_parts[1], check_parts[2]))
                return False
        # Miml relativo alle flags di una stanza
        elif check_parts[2][0:5] == "ROOM.":
            if not check_entity.IS_ROOM:
                return False

            if check_parts[1] == "is":
                if Element(check_parts[2]) in check_entity.flags:
                    return True
                else:
                    return False
            elif check_parts[1] == "is not":
                if Element(check_parts[2]) not in check_entity.flags:
                    return True
                else:
                    return False
            else:
                log.bug(
                    "Operatore di check sconosciuto: %s per l'elemento con codice %s"
                    % (check_parts[1], check_parts[2]))
                return False
        # Miml relativo all'inventario portato
        elif check_parts[0][-14:] == ".inventory_qty":
            check_qty = 0
            if is_number(check_parts[2]):
                check_qty = int(check_parts[2])
            else:
                log.bug(
                    "la parte destra dell'opeartore del check miml %s non è un numbero valido"
                    % (check))

            qty = 0
            for content in check_entity.iter_contains():
                if len(content.wear_mode
                       ) == 0 and FLAG.INGESTED not in content.flags:
                    qty += 1

            if check_parts[1] == "==" and qty == check_qty:
                return True
            elif check_parts[1] == "!=" and qty != check_qty:
                return True
            elif check_parts[1] == ">" and qty > check_qty:
                return True
            elif check_parts[1] == ">=" and qty >= check_qty:
                return True
            elif check_parts[1] == "<" and qty < check_qty:
                return True
            elif check_parts[1] == "<=" and qty <= check_qty:
                return True
            else:
                return False
        # Miml relativo all'equipaggiamento portato
        elif check_parts[0][-14:] == ".equipment_qty":
            check_qty = 0
            if is_number(check_parts[2]):
                check_qty = int(check_parts[2])
            else:
                log.bug(
                    "la parte destra dell'opeartore del check miml %s non è un numbero valido"
                    % check)

            qty = 0
            for content in check_entity.iter_contains():
                if len(content.wear_mode
                       ) != 0 and FLAG.INGESTED not in content.flags:
                    qty += 1

            if check_parts[1] == "==" and qty == check_qty:
                return True
            elif check_parts[1] == "!=" and qty != check_qty:
                return True
            elif check_parts[1] == ">" and qty > check_qty:
                return True
            elif check_parts[1] == ">=" and qty >= check_qty:
                return True
            elif check_parts[1] == "<" and qty < check_qty:
                return True
            elif check_parts[1] == "<=" and qty <= check_qty:
                return True
            else:
                return False
        # Miml relativo alle exits, wall e direzioni
        elif get_direction_miml(check_parts[0]) != DIR.NONE:
            if not check_entity.IS_ROOM:
                return False

            direction = get_direction_miml(check_parts[0])
            if direction in check_entity.exits:
                if check_parts[1] == "is":
                    if check_parts[2] == "Exit":
                        return True
                    elif check_parts[2] == "Wall":
                        # Il check qui ci vuole comunque perché una direzione può
                        # avere sia uscita che muro, idem per il ramo 'is not'
                        if direction in check_entity.walls:
                            return True
                        else:
                            return False
                    elif check_parts[2] == "Door":
                        if check_entity.exits[
                                direction].door and check_entity.exits[
                                    direction].door.door_type:
                            return True
                        else:
                            return False
                    elif check_parts[2][:5] == "EXIT.":
                        if Element(check_parts[2]
                                   ) in check_entity.exits[direction].flags:
                            return True
                        else:
                            return False
                    elif check_parts[2][:5] == "DOOR.":
                        if check_entity.exits[
                                direction].door and check_entity.exits[
                                    direction].door.door_type and Element(
                                        check_parts[2]) in check_entity.exits[
                                            direction].door.door_type.flags:
                            return True
                        else:
                            return False
                elif check_parts[1] == "is not":
                    if check_parts[2] == "Exit":
                        return False
                    elif check_parts[2] == "Wall":
                        if direction in check_entity.walls:
                            return False
                        else:
                            return True
                    elif check_parts[2] == "Door":
                        if check_entity.exits[
                                direction].door and check_entity.exits[
                                    direction].door.door_type:
                            return False
                        else:
                            return True
                    elif check_parts[2][:5] == "EXIT.":
                        if Element(check_parts[2]
                                   ) in check_entity.exits[direction].flags:
                            return False
                        else:
                            return True
                    elif check_parts[2][:5] == "DOOR.":
                        if check_entity.exits[
                                direction].door and check_entity.exits[
                                    direction].door.door_type and Element(
                                        check_parts[2]) in check_entity.exits[
                                            direction].door.door_type.flags:
                            return False
                        else:
                            return True
                else:
                    log.bug(
                        "Operatore di check sconosciuto: %s per il check %s" %
                        (check_parts[1], check))
                    return False

            if direction in check_entity.walls:
                if check_parts[1] == "is":
                    if check_parts[2] == "Wall":
                        if direction in check_entity.walls:
                            return True
                        else:
                            return False
                elif check_parts[1] == "is not":
                    if check_parts[2] == "Wall":
                        if direction in check_entity.walls:
                            return False
                        else:
                            return True

            return False

        # Tutti gli altri casi vengono gestiti come errore di sintassi
        log.bug("check del miml dalla sintassi errata: %s" % check)
        return False