def before_try_to_get(entity, target, location, behavioured):
    if (random.randint(0, 1) == 0):
        entity.act("Infili una $hand tra i fili ma qualcosa ti punge e la ritiri subito di scatto.", TO.ENTITY, target)
        entity.act("Non appena $n infila una $hand tra i fili la ritira di scatto.", TO.OTHERS, target)
        return True

    oggetto = Item(random.choice(PROTO_CIANFUSAGLIE_CODES))
    oggetto.inject(location)

    entity.act("Infili la $hand tra $N per prendere qualcosa.", TO.ENTITY, target)
    entity.act("Ti senti un po' deprezzat$O ogni volta $n t'indaga!", TO.TARGET, target)
    entity.act("$n infila la $hand tra $N per prendere qualcosa.", TO.OTHERS, target)

    numbered_keyword = oggetto.get_numbered_keyword(looker=entity)
    execution_result = command_get(entity, numbered_keyword)

    # Il peso dei fili viene diminuito man mano che se ne preleva.
    # Prima di farlo verifica che sia uscita una keyword quando ne resta
    # troppo poco viene eliminato
    if execution_result:
        if target.weight < oggetto.weight:
           target.act("Ed ora non ne trovi neanche uno, o così sembra.", TO.OTHERS, target)
           target.act("Ed ora non ne è rimasto neanche uno, o così sembra.", TO.ENTITY, target)
           target.extract(1)
        else:
           target.weight = target.weight - oggetto.weight

    return execution_result
def after_touch(entity, target, descr, detail, behavioured):
    if not entity.IS_PLAYER:
        return False

    if target.weight < 200:
        entity.act("$n pigia al pompetta di $N ma a vuoto.", TO.OTHERS, target)
        entity.act("Pigi la pompetta di $N ma a vuoto.", TO.ENTITY, target)
        return False
    else:
        target.weight = target.weight - PROFUMO_PROTO.weight

    for mode in PROFUMO_PROTO.wear_type.modes:
        for part in mode:
            already_weared_part, already_weared_possession = check_if_part_is_already_weared(entity, part)
            if already_weared_part:
                entity.act("[plum]$N si dissolve immediatamente nell'aria.[close]", TO.ENTITY, PROFUMO_PROTO)
                entity.act("[plum]$N si dissolve immediatamente nell'aria.[close]", TO.OTHERS, PROFUMO_PROTO)
                return

            profumo = Item(PROTO_PROFUMO_CODE)
            profumo.inject(entity)

            profumo.wear_mode += part
            part_descriptions = get_part_descriptions(mode, "wear")

            send_wear_messages(entity, profumo, "Indossi", "indossa", part_descriptions)
            break

    defer(10, profumo_cleaning, profumo, entity)
def blooming(pianta, room, age, fortuna):

    if pianta.code not in database["items"]:
        return

    fiore = Item("karpuram_item_mirtillo-rosso-04-fiore")
    if not fiore:
        log.bug("impossibile creare fiore: %r" % fiore)
        return

    location=pianta.location

    pianta.act("Nelle scorse ore $N ha aperto i fiori", TO.OTHERS, pianta)
    pianta.act("Nelle scorse ore $N ha aperto i fiori", TO.ENTITY, pianta)
    pianta.extract(1)

    fiore.inject(location)

    fiore.act("$N rifulge di tutto il suo splendore.", TO.OTHERS, fiore)
    fiore.act("$N rifulge di tutto il suo splendore.", TO.ENTITY, fiore)
    fortuna = fortuna -1
    if random.randint(1, fortuna) == 1:
        reactor.callLater(random.randint( FLOWER_WAIT_MIN , FLOWER_WAIT_MAX ), desiccation, fiore, room, age )
        return
    reactor.callLater(random.randint( FLOWER_WAIT_MIN , FLOWER_WAIT_MAX ),fructification , fiore, room, age, fortuna)
Ejemplo n.º 4
0
def before_try_to_get(entity, target, location, behavioured):
    manciata_torba = Item("karpuram_item_torba-manciata")
    laminetta_oro = Item("karpuram_item_laminetta-oro")

    if random.randint(1, 10) == 1:
        laminetta_oro.inject(location)
        entity.act(
            "Metti la $hand in $N ed un luccicore ti distrae dal tuo proponimento!",
            TO.ENTITY, target)
        entity.act(
            "tu che sei $N ti senti un po' deprezzato ogni volta $n ti indaga!",
            TO.TARGET, target)
        entity.act("$n affonda una mano in $N e si ferma sorpres$o.",
                   TO.OTHERS, target)
        execution_result = command_get(
            entity, laminetta_oro.get_numbered_keyword(looker=entity))
    else:
        manciata_torba.inject(location)
        execution_result = command_get(
            entity, manciata_torba.get_numbered_keyword(looker=entity))

    # Se execution_result a True significa che è stato raccolta con successo
    # una manciata di torba e quindi ferma l'esecuzione del resto del comando get;
    # altrimenti è False e tornando False viene continuato il get del mucchio
    # di torba, che in futuro fallirà per motivi di peso
    return execution_result
Ejemplo n.º 5
0
 def __init__(self, amount):
     Item.__init__(
         self,
         str(amount) + " Gold",
         "imgs/dungeon_crawl/item/gold/gold_pile_10.png",
         "Gold could be used to buy some items or other services", 0)
     self.amount = amount
def marciume(seed, room):

    if seed.code not in database["items"]:
        return
    frutto_marcio = Item("karpuram_item_mirtillo-rosso-00-frutto-marcio")
    if not frutto_marcio:
        log.bug("impossibile creare frutto_marcio: %r" % frutto_marcio)
        return

    if room != seed.location:
        # log da rimuovere 
        log.bug("room di drop diversa da room attuale")
        return

    location=seed.location

    seed.act("$N appare tutto molliccio...", TO.OTHERS, seed)
    seed.act("$N appare tutto molliccio...", TO.ENTITY, seed)

    seed.extract()

    frutto_marcio.inject(location)

    frutto_marcio.act("... è $N buono solo come concime.", TO.OTHERS, frutto_marcio)
    frutto_marcio.act("... è $N buono solo come concime.", TO.ENTITY, frutto_marcio)
def renew(fruttificato, room, age, fortuna):

    if fruttificato.code not in database["items"]:
        return

    pianta = Item("karpuram_item_mirtillo-rosso-03-pianta")
    if not pianta:
        log.bug("impossibile creare pianta: %r" % pianta)
        return

    age = age +1
    location=fruttificato.location

    fruttificato.act("quel che un tempo doveva esser $N, ora ...", TO.OTHERS, fruttificato)
    fruttificato.act("quel che un tempo doveva esser $N, ora ...", TO.ENTITY, fruttificato)
    fruttificato.extract(1)

    pianta.inject(location)

    pianta.act("... è $N che fruttificherà più avanti", TO.OTHERS, pianta)
    pianta.act("... è $N che fruttificherà più avanti", TO.ENTITY, pianta)
    
    fortuna = fortuna -1
    if random.randint(1, fortuna) == 1:
        reactor.callLater(random.randint(10,20), desiccation, pianta, room, age )
        return
    reactor.callLater(random.randint(10,20), blooming, pianta, room, age, fortuna)
def carica_regalo(player, location, rompicapo):
    price = Item(random.choice(PRICE_PROTO_CODES))
    price.inject(location)
    player.act("\n[yellow]Hai appena concluso il rompicapo che dal nulla compare un premio![close]\n", TO.ENTITY, rompicapo)
    player.act("\n[yellow]$n fa uno scatto sorpreso all'apparire del premio per $N.[close]\n", TO.OTHERS, rompicapo)
    player.act("Gothcha!.", TO.TARGET, rompicapo)
    print "novizi2_item_rompicapo-colorato - YOU WIN"
def before_try_to_get(entity, target, location, behavioured):
    # Crea e inserisce il pizzico di polverina nella locazione da cui prenderlo
    pizzico = Item("carrozzone-zingaro_item_polverina-pizzico")
    pizzico.inject(location)

    entity.act("Infili le dita dentro $N.", TO.ENTITY, target)
    entity.act("$n allunga due dita dentro $N.", TO.OTHERS, target)
    entity.act("Ti senti un po' deprezzata ogni volta che $n ti indaga!",
               TO.TARGET, target)

    # Bisogna utilizzare la get_numbered_keyword perché non si sa se entity in quel
    # momento stia guardando la short diurna, notturna o il nome
    first_keyword = pizzico.get_numbered_keyword(looker=entity)
    if location.IS_ROOM:
        argument = first_keyword
    else:
        argument = "%s %s " % (first_keyword,
                               location.get_numbered_keyword(looker=entity))
    execution_result = command_get(entity, argument)

    # Questo è meglio farlo solo se il get è andato a buon fine, cioè quando
    # execution_result ha valore di verità positiva
    if execution_result:
        if target.weight < pizzico.weight:
            target.act("Quello era l'ultimo, ora sei vuot$o.", TO.ENTITY)
            target.act("Una volta c'era $n, ma ora è vuot$o.", TO.OTHERS)
            target.extract(1)
        else:
            target.weight = target.weight - pizzico.weight

    return execution_result
Ejemplo n.º 10
0
 def __init__(self, settings):
     self.boardWidth = getSetting(settings, "boardWidth", 10)
     self.boardHeight = getSetting(settings, "boardHeight", 10)
     self.cellSize = getSetting(settings, "cellSize", 10)
     self.snake = Snake(settings, self.boardWidth / 2, self.boardHeight / 2)
     self.isDead = False
     self.item = Item(settings)
     self.reinitItem()
Ejemplo n.º 11
0
    def handle_new_player(self, ident):
        self.players[ident] = Player(ident)
        # self.players[ident].profession = 'survivor'
        self.players[ident].position = self.find_spawn_point_for_new_player()
        self.worldmap.put_object_at_position(self.players[ident], self.players[ident].position)
        self.localmaps[ident] = self.worldmap.get_chunks_near_position(self.players[ident].position)
        # give the player their starting items by referencing the ProfessionManager.
        # print('profession items ')
        '''
        ident : survivor
        _comment : A basic as it comes. I'll use this for the default profession.
        name : Survivor
        description : Some would say that there's nothing particularly notable about you. But you survived. That's more than most can say right now.
        skills : ["{'survival': 1}"]
        points : 0
        items : {'equipped': [{'TORSO': 'backpack'}], 'in_containers': [{'backpack': 'cell_phone'}]}
        flags : []
        CBMs : []
        '''
        #print(self.players[ident].profession)
        for key, value in self.ProfessionManager.PROFESSIONS[str(self.players[ident].profession)].items():
            print(key, ':', value)
        
            # print(value.items())
            # TODO: load the items into the player equipment slots as well as future things like CBMs and flags
            if(key == 'equipped_items'):
                for equip_location, item_ident in value.items():
                    print(equip_location, item_ident)
                    for bodypart in self.players[ident].body_parts:
                        if(bodypart.ident.split('_')[0] == equip_location):
                            if(bodypart.slot0 is None):
                                if('container_type' in self.ItemManager.ITEM_TYPES[item_ident]):
                                    bodypart.slot0 = Container(item_ident, self.ItemManager.ITEM_TYPES[item_ident]) # need to pass the reference to load the item with data.
                                else:
                                    bodypart.slot0 = Item(item_ident, self.ItemManager.ITEM_TYPES[item_ident]) # need to pass the reference to load the item with data.
                                break
                            elif(bodypart.slot1 is None):
                                if('container_type' in self.ItemManager.ITEM_TYPES[item_ident]):
                                    bodypart.slot1 = Container(item_ident, self.ItemManager.ITEM_TYPES[item_ident]) # need to pass the reference to load the item with data.
                                else:
                                    bodypart.slot1 = Item(item_ident, self.ItemManager.ITEM_TYPES[item_ident]) # need to pass the reference to load the item with data.
                                break
                    else:
                        print('player needed an item but no free slots found')
            elif(key == 'items_in_containers'): # load the items_in_containers into their containers we just created.
                print('LOADING ITEMS INTO CONTAINERS')
                for location_ident, item_ident in value.items():
                    print(location_ident, item_ident)
                    # first find the location_ident so we can load a new item into it.
                    for bodypart in self.players[ident].body_parts:
                        if(bodypart.slot0 is not None):
                            if(isinstance(bodypart.slot0, Container) and bodypart.slot0.ident == location_ident): # uses the first one it finds, maybe check if it's full?
                                bodypart.slot0.add_item(Item(item_ident, self.ItemManager.ITEM_TYPES[item_ident]))
                            if(isinstance(bodypart.slot1, Container) and bodypart.slot1.ident == location_ident): # uses the first one it finds, maybe check if it's full?
                                bodypart.slot1.add_item(Item(item_ident, self.ItemManager.ITEM_TYPES[item_ident]))

        print('New player joined.', self.players[ident].name)
Ejemplo n.º 12
0
def test_item_functions():
    name = "A shiny bauble"
    desc = "A tiny golden bauble, not good for much but very shiny"
    value = 5
    item = Item(name=name, desc=desc, value=value)

    assert item.identify() == name
    assert item.describe() == desc
    assert item.appraise() == value
Ejemplo n.º 13
0
def test_basket_assignment_example():
    baked_beans = Item(name='Baked Beans', price=0.99, discount_bogof=2)
    biscuits = Item(name='Biscuits', price=1.20)

    basket = Basket(items=[baked_beans] * 4 + [biscuits])

    assert basket.get_subtotal() == 5.16
    assert basket.get_discount() == 0.99
    assert basket.get_total() == 4.17
Ejemplo n.º 14
0
def before_try_to_get(entity, target, location, behavioured):
    frutta_semi_db = ["flora_item_mirtillo-rosso-01-frutto",
                      "flora_item_leccio-01-ghianda-viva",
                      "flora_item_leccio-02-ghianda-morta",
                      "flora_item_mirtillo-nero-01-frutto",
                      "flora_item_mirtillo-rosso-00-frutto-marcio",
                      "flora_item_mirtillo-rosso-00-frutto-sterile",
                      "flora_item_farnia-01-ghianda-viva",
                      "flora_item_farnia-02-ghianda-morta"]

    num_rand = random.randint(1, 100)
    if num_rand < 8:
        frutto_seme_code = frutta_semi_db[0]
    elif num_rand < 18:
        frutto_seme_code = frutta_semi_db[1]
    elif num_rand < 22:
        frutto_seme_code = frutta_semi_db[2]
    elif num_rand < 32:
        frutto_seme_code = frutta_semi_db[3]
    elif num_rand < 35:
        frutto_seme_code = frutta_semi_db[4]
    elif num_rand < 40:
        frutto_seme_code = frutta_semi_db[5]
    elif num_rand < 76:
        frutto_seme_code = frutta_semi_db[6]
    else:
        frutto_seme_code = frutta_semi_db[7]

    # Crea e inserisce il seme scelto nella locazione da cui prenderlo poi
    seed_founded = Item(frutto_seme_code)
    seed_founded.inject(location)

    # Attenzione che il get invierà i propri messaggi oltre a questi qui
    entity.act("Infili la $hand verso $N.", TO.ENTITY, target)
    entity.act("$n allunga una mano verso $N.", TO.OTHERS, target)
    entity.act("Ti senti un po' deprezzato ogni volta che $n ti indaga!", TO.TARGET, target)

    # Bisogna utilizzare la get_numbered_keyword perché non si sa se entity
    # in quel momento possa visualizzare la short diurna, notturna o il nome
    argument = seed_founded.get_numbered_keyword(looker=entity)
    if not location.IS_ROOM:
        argument += " %s " % location.get_numbered_keyword(looker=entity)
    execution_result = command_get(entity, argument)

    # La diminuzione del peso deve essere eseguita quando effettivamente sia
    # stato eseguito il comando di get, ovvero execution_result ha valore
    # di verità positiva
    if execution_result:
        if target.weight < seed_founded.weight:
            target.act("Dei $n che c'erano ora non resta nulla.", TO.ENTITY)
            target.act("Di te ormai ora non resta nulla.", TO.OTHERS)
            target.extract(1)
        else:
            target.weight = target.weight - seed_founded.weight

    return True
Ejemplo n.º 15
0
def carica_regalo(player, location, rompicapo):
    price = Item(random.choice(PRICE_PROTO_CODES))
    price.inject(location)
    player.act(
        "\n[yellow]Hai appena concluso il rompicapo che dal nulla compare un premio![close]\n",
        TO.ENTITY, rompicapo)
    player.act(
        "\n[yellow]$n fa uno scatto sorpreso all'apparire del premio per $N.[close]\n",
        TO.OTHERS, rompicapo)
    player.act("Gothcha!.", TO.TARGET, rompicapo)
    print "novizi2_item_rompicapo-colorato - YOU WIN"
Ejemplo n.º 16
0
 def test_initialize(self):
     item = Item([0, 'format'], 'id', 'prev-id')
     self.assertEqual(item.id, 'id')
     self.assertEqual(item.prev_id, 'prev-id')
     self.assertEqual(item.formats, [0, 'format'])
     format = TestFormatSubClass()
     format2 = TestFormatSubClass2()
     item = Item([format, format2])
     self.assertEqual(item.formats, [format, format2])
     item = Item(format)
     self.assertEqual(item.formats, [format])
Ejemplo n.º 17
0
def test_basket_bonus_discount():
    shampoo_small = Item(name='Shampoo Small', price=2.00, discount_bonus=True)
    shampoo_medium = Item(name='Shampoo Medium',
                          price=2.50,
                          discount_bonus=True)
    shampoo_large = Item(name='Shampoo Large', price=3.50, discount_bonus=True)
    basket = Basket(items=[shampoo_large] * 3 + [shampoo_medium] +
                    [shampoo_small] * 2)

    assert basket.get_subtotal() == 17.00
    assert basket.get_discount() == 5.5
    assert basket.get_total() == 11.5
Ejemplo n.º 18
0
def before_try_to_get(entity, target, location, behavioured):

    funghi_db = {
        1: "villaggio-zingaro_item_fungo-01",
        2: "villaggio-zingaro_item_fungo-02",
        3: "villaggio-zingaro_item_fungo-03"
    }

    num_rand = random.randint(1, 100)
    if num_rand < 14:
        fungo_label = funghi_db[3]
    elif num_rand < 32:
        fungo_label = funghi_db[2]
    elif num_rand < 49:
        fungo_label = funghi_db[1]
    # in tutti gli altri casi esce dallo script con il return True
    # che esce dal flusso del get senza raccattare nulla
    else:
        entity.act(
            "Fai come per afferrarne uno ma questo ti sguscia tra le mani e si ritrae sotto terra.",
            TO.ENTITY, target)
        entity.act(
            "$n fa come per afferrare un fungo ma questo $gli sguscia tra le mani e si ritrae sotto terra.",
            TO.OTHERS, target)
        return True

    fungo = Item(fungo_label)
    fungo.inject(location)

    entity.act("Allunghi la $hand verso $N per raccoglierne uno.", TO.ENTITY,
               target)
    entity.act("$n allunga una $hand verso $N per raccoglierne uno.",
               TO.OTHERS, target)
    entity.act("Ti senti un po' deprezzat$O ogni volta $n ti indaga!",
               TO.TARGET, target)

    numbered_keyword = fungo.get_numbered_keyword(looker=entity)
    execution_result = command_get(entity, numbered_keyword)

    # Il peso del cerchio viene diminuito man mano che se ne preleva
    # prima di farlo verifica che sia uscita una keyword quando ne
    # resta troppo poco viene eliminato
    if execution_result:
        if target.weight < fungo.weight:
            target.act("Ed ora non ne trovi neanche uno, o così sembra.",
                       TO.ENTITY, target)
            target.act("Ed ora non ne è rimasto neanche uno, o così sembra.",
                       TO.OTHERS, target)
            target.extract(1)
        else:
            target.weight = target.weight - fungo.weight

    return execution_result
def gen_trash(room):
    casual_rotten = Item(random.choice(PROTO_VEGGY_CODES))

    #if casual_rotten.max_global_quantity != 0 and casual_rotten.current_global_quantity >= casual_rotten.max_global_quantity:
    if casual_rotten.has_reached_max_global_quantity():
        #log.bug("limit exceded")
        return

    casual_rotten.flags += FLAG.BURIED

    #log.bug("veggys injection")
    casual_rotten.inject(room)
Ejemplo n.º 20
0
class Board():
    def __init__(self, settings):
        self.boardWidth = getSetting(settings, "boardWidth", 10)
        self.boardHeight = getSetting(settings, "boardHeight", 10)
        self.cellSize = getSetting(settings, "cellSize", 10)
        self.snake = Snake(settings, self.boardWidth / 2, self.boardHeight / 2)
        self.isDead = False
        self.item = Item(settings)
        self.reinitItem()

    def draw(self, screen):
        self.move()
        screen.fill(style.BoardFillColor)
        for row in range(0, self.boardWidth):
            for column in range(0, self.boardHeight):
                x = row * self.cellSize
                y = column * self.cellSize
                color = style.BoardFloorColor
                if self.isDead:
                    color = style.BoardDeadColor
                pygame.draw.rect(screen, color,
                                 (x, y, self.cellSize, self.cellSize), 1)
        self.item.draw(screen)
        self.snake.draw(screen)

    def move(self):
        if self.snake.direction == Direction.Up:
            self.tryMove(self.snake.x, self.snake.y - 1)
        elif self.snake.direction == Direction.Right:
            self.tryMove(self.snake.x + 1, self.snake.y)
        elif self.snake.direction == Direction.Down:
            self.tryMove(self.snake.x, self.snake.y + 1)
        elif self.snake.direction == Direction.Left:
            self.tryMove(self.snake.x - 1, self.snake.y)

    def tryMove(self, x, y):
        self.isDead = ((x < 0) or (x >= self.boardWidth) or (y < 0)
                       or (y >= self.boardHeight)
                       or self.snake.isContains(x, y))
        if self.isDead:
            return

        isItemEaten = (x == self.item.x) and (y == self.item.y)
        if isItemEaten:
            self.item.eatenUpCount = self.item.eatenUpCount + 1
            self.reinitItem()

        self.snake.moveHead(x, y, isItemEaten)

    def reinitItem(self):
        self.item.x = random.randint(0, self.boardWidth - 1)
        self.item.y = random.randint(0, self.boardHeight - 1)
def turn_to_dust(player, cadavere, location):
    if not player.IS_PLAYER:
        return False

    polvere = Item(PROTO_DUST_CODE)
    polvere.inject(location)
    player.act("$N comincia a sgretolarsi fino a farsi polvere.", TO.ENTITY, cadavere)
    player.act("$N toccato da $n si decompone a vista d'occhio.", TO.OTHERS, cadavere)
    player.act("Ti sgretoli al tocco di $n!", TO.TARGET, cadavere)
    cadavere.extract(1)
    caterpillar_creation()

    return True
Ejemplo n.º 22
0
def on_sunrise(lupo):
    if not lupo:
        log.bug("lupo non è un parametro valido: %r" % lupo)
        return

    dosso = Item(PROTO_DOSSO_CODE)
    dosso.inject(lupo.location)

    dosso.act("Ti origini da $N e sei $n.", TO.ENTITY, lupo)
    dosso.act("Tra atroci ululati $N si trasforma in $n!", TO.OTHERS, lupo)
    dosso.act("$n si origina da te!", TO.TARGET, lupo)

    lupo.stop_repop()
    lupo.extract(1)
def marciume(seed, room):

    if seed.code not in database["items"]:
        return
    frutto_marcio = Item("karpuram_item_mirtillo-rosso-00-frutto-marcio")
    if not frutto_marcio:
        log.bug("impossibile creare frutto_marcio: %r" % frutto_marcio)
        return

    if room != seed.location:
        # log da rimuovere
        log.bug("room di drop diversa da room attuale")
        return

    location = seed.location

    seed.act("$N appare tutto molliccio...", TO.OTHERS, seed)
    seed.act("$N appare tutto molliccio...", TO.ENTITY, seed)

    seed.extract()

    frutto_marcio.inject(location)

    frutto_marcio.act("... è $N buono solo come concime.", TO.OTHERS,
                      frutto_marcio)
    frutto_marcio.act("... è $N buono solo come concime.", TO.ENTITY,
                      frutto_marcio)
Ejemplo n.º 24
0
 def test_send_to_zmq(self):
     pc = PubControl()
     pc._zmq_pub_controller = ZmqPubControllerTestClass()
     pc._send_to_zmq('chan', Item(TestFormatSubClass()))
     fmt = TestFormatSubClass()
     pc._send_to_zmq('chan', Item(fmt))
     self.assertEqual(pc._zmq_pub_controller.publish_channel,
                      'chan'.encode('utf-8'))
     is_encoded = False
     try:
         if not isinstance(pc._zmq_pub_controller.publish_channel, unicode):
             is_encoded = True
     except NameError:
         if not isinstance(pc._zmq_pub_controller.publish_channel, str):
             is_encoded = True
def after_move(entity, from_room, direction, to_room, running, behavioured):
    if not entity.IS_PLAYER:
        return

    for content in to_room.iter_contains():
        if content.IS_PLAYER:
            continue
        if content.prototype.code == oggetti["chiave"]:
            return

    chiave = Item(oggetti["chiave"])
    chiave.inject(to_room)

    defer(3, ambience_act_1, to_room)
    defer(5, ambience_act_2, to_room, chiave)
def after_move(entity, from_room, direction, to_room, running, behavioured):
    if not entity.IS_PLAYER:
        return 

    for content in to_room.iter_contains():
        if content.IS_PLAYER:
             continue
        if content.prototype.code == oggetti["chiave"]:
             return

    chiave = Item(oggetti["chiave"])
    chiave.inject(to_room)

    defer(3, ambience_act_1, to_room)
    defer(5, ambience_act_2, to_room, chiave)
def turn_to_dust(player, cadavere, location):
    if not player.IS_PLAYER:
        return False

    polvere = Item(PROTO_DUST_CODE)
    polvere.inject(location)
    player.act("$N comincia a sgretolarsi fino a farsi polvere.", TO.ENTITY,
               cadavere)
    player.act("$N toccato da $n si decompone a vista d'occhio.", TO.OTHERS,
               cadavere)
    player.act("Ti sgretoli al tocco di $n!", TO.TARGET, cadavere)
    cadavere.extract(1)
    caterpillar_creation()

    return True
Ejemplo n.º 28
0
def gem_gen(unused_room):
    sum_relative_weight = 0
    for gem_code in GEMS_WEIGHT_DICT:
        print "--> relative weight sum <--", sum_relative_weight
        sum_relative_weight += GEMS_WEIGHT_DICT[gem_code]
    print "--> final reative weight sum <--", sum_relative_weight

    area = database["areas"]["miniere-kezaf"]
    rooms = area.rooms.values()
    log.bug("start miniere kezaf", log_stack=False)

    rooms_to_fill = len(rooms) - 2
    print "rooms_to_fill ", rooms_to_fill
    for room in random.sample(rooms, rooms_to_fill):
        for content in room.iter_contains():
            if FLAG.BURIED in content.flags:
                log.bug("gem extraction: %s" % content.code, log_stack=False)
                content.extract(1)
        if random.randint(0, 1):
            casual_gem_code = random.chioce(PROTO_GEMS_CODES)
            if casual_gem_code.has_reached_max_global_quantity():
                log.bug("extract causa excedeed of: %s" % casual_gem_code,
                        log_stack=False)
            else:
                casual_gem = Item(casual_gem_code)
                casual_gem.flags += FLAG.BURIED
                log.bug("insertion of: %s" % casual_gem.code, log_stack=False)
                casual_gem.inject(room)

#            if not casual_gem:
#                log.bug("not casual gem: %s" % casual_gem, log_stack=False)
#                return
#            casual_gem.flags += FLAG.BURIED
#
#            if casual_gem.has_reached_max_global_quantity():
#                log.bug("extract causa excedeed of: %s" % casual_gem.code, log_stack=False)
#                casual_gem.extract(1)
#            else:
#                log.bug("insertion of: %s" % casual_gem.code, log_stack=False)
#                casual_gem.inject(room)

#            if casual_gem.max_global_quantity == 0 or casual_gem.current_global_quantity < casual_gem.max_global_quantity:
#                log.bug("insertion of: %s" % casual_gem.code, log_stack=False)
#                casual_gem.inject(room)
#            else:
#                log.bug("extract causa excedeed of: %s" % casual_gem.code, log_stack=False)
#                casual_gem.extract(1)
    return True
Ejemplo n.º 29
0
    def cached_fitness(self, genes: "Genes") -> "Tuple[Result, Any]":
        '''Same as _fitnes_function but uses cached values if it can.

        For the given set of genes it checks if cache_data contains
        that record already. If it does not it creates a new tuple
        with _fitness_function and saves it to cache_data.

        Args:
            genes: An array of booleans (genes) whose cache_data record
                is to be returned

        Returns:
            A tuple[Result, Any] that was obtained from cache_data or
            calculated.
        '''
        #print("Trying:", np.where(genes))
        number = Item.to_number(genes)
        result = self.cache_data.get(number, None)
        self.cache_counter[number] += 1
        if result is None:
            result = self._fitness_function(genes)
            self.cache_data[number] = result
        else:
            #print("Hitted", self.cache_counter)
            pass
        return result
Ejemplo n.º 30
0
def main():
    items = []
    random.seed(5345)
    number_of_items = int(input("Please enter number of items: "))
    for i in range(number_of_items):
        item = Item(random.randint(1, 10), random.randint(0, 75))
        items.append(item)
    print(items)
    weight = 0
    for i in range(number_of_items):
        weight += items[i].weight
    print(weight)
    max_weight = round(weight / 2)
    population_size = int(input("Please enter population size: "))
    population = generate_population(population_size, max_weight, items)
    number_of_generations = int(input("Please enter number of generations: "))
    population = run_algorithm(population, number_of_generations)
    print_population(population)
    choice = input("Do you want to export results to textfile? (y/N) ")
    if choice == "y":
        parameters = {
            "Number of items": number_of_items,
            "Population size": population_size,
            "Number of generations": number_of_generations
        }
        filename = input("Please enter filename: ")
        if not path.isdir("exported_results"):
            mkdir("exported_results")
        export_results(population, parameters, filename)
Ejemplo n.º 31
0
    def purge_item_with_information_gain(self, item: "Item") -> "EvalItem":
        '''Removes the worst gene from an item.

        Checks which gene adds the least to the score and removes it
        from the item.

        Args:
            item: An Item object to which we want to remove the worst
                gene.

        Returns:
            An EvalItem Object that is the same as the input object but
            with the worst gene removed.
        '''
        base_result, model = self.fitness_function(item.genes)
        on_genes = np.where(item.genes)[0]
        changes = [(1.0, -1) for _ in on_genes]

        for change_ind, gene_ind in enumerate(on_genes):
            sh_result = self.evaluator(model, item.genes, [change_ind])
            changes[change_ind] = (base_result.score - sh_result.score, gene_ind)
        changes.sort()  # Sort them so that first cause the smallest change
        # print(base_result)
        # print("CHANGES:", changes)
        # And therefore seem a good fit for removal
        # Maybe some random selection?
        genes2 = item.genes.copy()
        # Unset the gene with the smallest change
        genes2[changes[0][1]] = False

        rt_item = Item(genes2, item.generation + 1, None, None).\
            evaluate(self.fitness_function)
        return rt_item
Ejemplo n.º 32
0
 def bash(
     self, object, position
 ):  # catch-all for bash/smash (can probably use this for vehicle collisions aswell) object is object that is doing the bashing
     # since we bash in a direction we need to check what's in the tile and go from there.
     # both furniture and terrain can be bashed but we should assume that the player wants to bash the furniture first then terrain we will go in that order.
     tile = self.get_tile_by_position(position)
     terrain = tile["terrain"]
     # strength = creature strength.
     if tile["furniture"] is not None:
         furniture_type = self.FurnitureManager.FURNITURE_TYPES[
             tile["furniture"].ident]
         for item in furniture_type["bash"]["items"]:
             self.put_object_at_position(
                 Item(
                     self.ItemManager.ITEM_TYPES[str(
                         item["item"])]["ident"],
                     self.ItemManager.ITEM_TYPES[str(item["item"])],
                 ),
                 position,
             )  # need to pass the reference to load the item with data.
         tile["furniture"] = None
         # get the 'bash' dict for this object from furniture.json
         # get 'str_min'
         # if player can break it then delete the furniture and add the bash items from it to the tile.
         return
     if terrain is not None:
         # get the 'bash' dict for this object from terrain.json if any
         # if dict is not None:
         # get 'str_min'
         # if player can break it then delete the terrain and add the bash terrain from it to the tile.
         return
     return
Ejemplo n.º 33
0
def gem_gen(unused_room):
    sum_relative_weight = 0
    for gem_code in GEMS_WEIGHT_DICT:
        print "--> relative weight sum <--", sum_relative_weight
        sum_relative_weight += GEMS_WEIGHT_DICT[gem_code]
    print "--> final reative weight sum <--", sum_relative_weight

    area = database["areas"]["miniere-kezaf"]
    rooms = area.rooms.values()
    log.bug("start miniere kezaf", log_stack=False)

    rooms_to_fill = len(rooms) - 2
    print "rooms_to_fill ", rooms_to_fill
    for room in random.sample(rooms, rooms_to_fill):
        for content in room.iter_contains():
            if FLAG.BURIED in content.flags:
                log.bug("gem extraction: %s" % content.code, log_stack=False) 
                content.extract(1)
        if random.randint(0,1):
            casual_gem_code = random.chioce(PROTO_GEMS_CODES)
            if casual_gem_code.has_reached_max_global_quantity():
                log.bug("extract causa excedeed of: %s" % casual_gem_code, log_stack=False) 
            else:
                casual_gem = Item(casual_gem_code)
                casual_gem.flags += FLAG.BURIED
                log.bug("insertion of: %s" % casual_gem.code, log_stack=False) 
                casual_gem.inject(room)

#            if not casual_gem:
#                log.bug("not casual gem: %s" % casual_gem, log_stack=False)
#                return
#            casual_gem.flags += FLAG.BURIED
#        
#            if casual_gem.has_reached_max_global_quantity():
#                log.bug("extract causa excedeed of: %s" % casual_gem.code, log_stack=False) 
#                casual_gem.extract(1)
#            else:
#                log.bug("insertion of: %s" % casual_gem.code, log_stack=False) 
#                casual_gem.inject(room)

#            if casual_gem.max_global_quantity == 0 or casual_gem.current_global_quantity < casual_gem.max_global_quantity: 
#                log.bug("insertion of: %s" % casual_gem.code, log_stack=False) 
#                casual_gem.inject(room)
#            else:
#                log.bug("extract causa excedeed of: %s" % casual_gem.code, log_stack=False) 
#                casual_gem.extract(1)
    return True
 def test_init_item(self):
     name = 'life_potion'
     sprite = 'imgs/dungeon_crawl/item/potion/magenta_new.png'
     description = 'This is a test description'
     item = Item(name, sprite, description)
     self.assertEqual(name, item.name)
     self.assertEqual(description, item.desc)
     self.assertEqual('Life Potion', str(item))
def generate_item(apprendista, player, choosed_material, room):
    # Normale che possa accadere visto che la funzione viene deferrata
    if not apprendista or not player or not room:
        return

    to_say = "Uhm... un golem di %s... Cominciamo un po'..." % choosed_material
    command_say(apprendista, to_say)

    proto_item_code = ITEM_PROTO_CODE[choosed_material]
    item = Item(proto_item_code)
    item.flags += FLAG.NO_GET
    item.inject(room)

    # (bb) perché funzioni al meglio il sistema di persistent act qui bisogna
    # che esista anche il messaggio a TO.ENTITY, da aggiungere quindi
    apprendista.act(PHRASES[choosed_material], TO.OTHERS, item)
    defer_random_time(12, 20, generate_golem, apprendista, player, choosed_material, room, item)
Ejemplo n.º 36
0
 def load(self):
     ws = load_workbook(self.path)['Engineering']
     values =  ws.values
     headers = tuple(self.__column_name_to_item_field(header) for header in next(values))
     dicts = [dict(zip(headers, row)) for row in values]
     for attrs in dicts:
         del attrs[None]
     return [Item(**attrs) for attrs in dicts if attrs['name']]
def on_sunrise(lupo):
    if not lupo:
        log.bug("lupo non è un parametro valido: %r" % lupo)
        return

    dosso = Item(PROTO_DOSSO_CODE)
    dosso.inject(lupo.location)

    dosso.act("Ti origini da $N e sei $n.", TO.ENTITY, lupo)
    dosso.act("Tra atroci ululati $N si trasforma in $n!", TO.OTHERS, lupo)
    dosso.act("$n si origina da te!", TO.TARGET, lupo)

    lupo.stop_repop()
    lupo.extract(1)
def medaglione_corruption(medaglione, player):
    # Normale perché la funzione è deferrata
    if not medaglione or not player:
        return

    old_medallion = Item("villaggio-zingaro_item_medaglione-rotto")
    old_medallion.inject(medaglione.location)

    medaglione.act("$n si consuma lentamente...",
                   TO.ENTITY,
                   send_to_location=player.location)
    medaglione.act("$n si consuma lentamente...",
                   TO.OTHERS,
                   send_to_location=player.location)
    medaglione.extract(1)

    defer(120, medaglione_remove, old_medallion, player)
    return False
Ejemplo n.º 39
0
 def test_export(self):
     format = TestFormatSubClass()
     out = Item(format, 'id', 'prev-id').export()
     self.assertEqual(out['name'], {'body': 'bodyvalue'})
     self.assertEqual(out['id'], 'id')
     self.assertEqual(out['prev-id'], 'prev-id')
     out = Item(format).export()
     self.assertFalse('id' in out)
     self.assertFalse('prev-id' in out)
     out = Item(format, 'id', 'prev-id').export(True)
     self.assertEqual(out['formats']['name'], {'body': 'bodyvalue'})
     self.assertEqual(out['id'], 'id')
     self.assertEqual(out['prev-id'], 'prev-id')
     self.verify_unicode(out['id'], 'id')
     self.verify_unicode(out['prev-id'], 'prev-id')
     out = Item(format, 'id', 'prev-id').export(False, True)
     self.verify_utf8(out['id'.encode('utf-8')], 'id')
     self.verify_utf8(out['prev-id'.encode('utf-8')], 'prev-id')
def reset_fermaglio():
    """
    Cerca le copie di fermagli e le rimuove, ma se son in inventario dei
    player li sostituisce con la fuffa.
    """
    for fermaglio in reversed(database["items"].values()):
        if fermaglio.prototype.code != FERMAGLIO_PROTO_CODE:
            continue
        if not fermaglio.location:
            fermaglio.extract(1)
        player_container = fermaglio.get_player_carrier()
        if player_container:
            location = fermaglio.location
            fermaglio.extract(1)
            dummy_fermaglio = Item(FAKE_FERMAGLIO_PROTO_CODE)
            dummy_fermaglio.inject(location)
        else:
            fermaglio.extract(1)
def generate_item(apprendista, player, choosed_material, room):
    # Normale che possa accadere visto che la funzione viene deferrata
    if not apprendista or not player or not room:
        return

    to_say = "Uhm... un golem di %s... Cominciamo un po'..." % choosed_material
    command_say(apprendista, to_say)

    proto_item_code = ITEM_PROTO_CODE[choosed_material]
    item = Item(proto_item_code)
    item.flags += FLAG.NO_GET
    item.inject(room)

    # (bb) perché funzioni al meglio il sistema di persistent act qui bisogna
    # che esista anche il messaggio a TO.ENTITY, da aggiungere quindi
    apprendista.act(PHRASES[choosed_material], TO.OTHERS, item)
    defer_random_time(12, 20, generate_golem, apprendista, player,
                      choosed_material, room, item)
def before_try_to_get(entity, target, location, behavioured):
    matasse_db = {
        1: "carrozzone-zingaro_item_canovaccio-01-macchiato",
        2: "carrozzone-zingaro_item_canovaccio-01-pulito",
        3: "carrozzone-zingaro_item_canovaccio-01-usurato",
        4: "carrozzone-zingaro_item_canovaccio-02-macchiato",
        5: "carrozzone-zingaro_item_canovaccio-02-pulito",
        6: "carrozzone-zingaro_item_canovaccio-02-usurato"
    }

    num_rand = random.randint(1, 100)
    if num_rand < 17:
        matassa_label = matasse_db[1]
    elif num_rand < 34:
        matassa_label = matasse_db[2]
    elif num_rand < 50:
        matassa_label = matasse_db[3]
    elif num_rand < 67:
        matassa_label = matasse_db[4]
    elif num_rand < 84:
        matassa_label = matasse_db[5]
    else:
        matassa_label = matasse_db[6]

    matassa = Item(matassa_label)
    matassa.inject(location)

    entity.act("Affondi la $hand verso $N incurante.", TO.ENTITY, target)
    entity.act("Ti senti un po' deprezzato ogni volta $n ti indaga!",
               TO.TARGET, target)
    entity.act("Incurante $n allunga una $hand verso $N.", TO.OTHERS, target)

    execution_result = command_get(entity, "canovaccio")

    # Il peso del filo viene diminuito man mano che se ne preleva quando
    # ne resta troppo poco viene eliminato
    if target.weight < matassa.weight:
        target.act("E questo era il tuo ultimo pezzo di stoffa...", TO.ENTITY)
        target.act("E questo era l'ultimo pezzo di stoffa...", TO.OTHERS)
        target.extract(1)
    else:
        target.weight = target.weight - matassa.weight

    return execution_result
def before_try_to_get(entity, target, location, behavioured):

    funghi_db = {1: "villaggio-zingaro_item_fungo-01",
                 2: "villaggio-zingaro_item_fungo-02",
                 3: "villaggio-zingaro_item_fungo-03"}

    num_rand = random.randint(1, 100)
    if num_rand < 14: 
        fungo_label = funghi_db[3]
    elif num_rand < 32:
        fungo_label = funghi_db[2]
    elif num_rand < 49:
        fungo_label = funghi_db[1]
    # in tutti gli altri casi esce dallo script con il return True
    # che esce dal flusso del get senza raccattare nulla
    else :
        entity.act("Fai come per afferrarne uno ma questo ti sguscia tra le mani e si ritrae sotto terra.", TO.ENTITY, target)    
        entity.act("$n fa come per afferrare un fungo ma questo $gli sguscia tra le mani e si ritrae sotto terra.", TO.OTHERS, target)    
        return True

    fungo = Item(fungo_label)
    fungo.inject(location)

    entity.act("Allunghi la $hand verso $N per raccoglierne uno.", TO.ENTITY, target)
    entity.act("$n allunga una $hand verso $N per raccoglierne uno.", TO.OTHERS, target)
    entity.act("Ti senti un po' deprezzat$O ogni volta $n ti indaga!", TO.TARGET, target)

    numbered_keyword = fungo.get_numbered_keyword(looker=entity)
    execution_result = command_get(entity, numbered_keyword)

    # Il peso del cerchio viene diminuito man mano che se ne preleva 
    # prima di farlo verifica che sia uscita una keyword quando ne
    # resta troppo poco viene eliminato
    if execution_result:
        if target.weight < fungo.weight:
           target.act("Ed ora non ne trovi neanche uno, o così sembra.", TO.ENTITY, target)
           target.act("Ed ora non ne è rimasto neanche uno, o così sembra.", TO.OTHERS, target)
           target.extract(1)
        else:
           target.weight = target.weight - fungo.weight

    return execution_result
def before_try_to_get(entity, target, location, behavioured):
     matasse_db = {1: "carrozzone-zingaro_item_canovaccio-01-macchiato",
                   2: "carrozzone-zingaro_item_canovaccio-01-pulito",
                   3: "carrozzone-zingaro_item_canovaccio-01-usurato",
                   4: "carrozzone-zingaro_item_canovaccio-02-macchiato",
                   5: "carrozzone-zingaro_item_canovaccio-02-pulito",
                   6: "carrozzone-zingaro_item_canovaccio-02-usurato"}

     num_rand = random.randint(1,100)
     if num_rand < 17:
         matassa_label = matasse_db[1]
     elif num_rand < 34:
         matassa_label = matasse_db[2]
     elif num_rand < 50:
         matassa_label = matasse_db[3]
     elif num_rand < 67:
         matassa_label = matasse_db[4]
     elif num_rand < 84:
         matassa_label = matasse_db[5]
     else:
         matassa_label = matasse_db[6]

     matassa = Item(matassa_label)
     matassa.inject(location)

     entity.act("Affondi la $hand verso $N incurante.", TO.ENTITY, target)
     entity.act("Ti senti un po' deprezzato ogni volta $n ti indaga!", TO.TARGET, target)
     entity.act("Incurante $n allunga una $hand verso $N.", TO.OTHERS, target)

     execution_result = command_get(entity, "canovaccio")

     # Il peso del filo viene diminuito man mano che se ne preleva quando
     # ne resta troppo poco viene eliminato
     if target.weight < matassa.weight:
        target.act("E questo era il tuo ultimo pezzo di stoffa...", TO.ENTITY)
        target.act("E questo era l'ultimo pezzo di stoffa...", TO.OTHERS)
        target.extract(1)
     else:
        target.weight = target.weight - matassa.weight

     return execution_result
def quest_reward(player, item, tessi):
    if tessi.location != player.location:
        to_say = "a %s %s, ma dove scappi? Non vuoi la ricompensa dopo tanto affanno? Vabbè!" % (player.code, player.name)
        command_say(tessi, to_say)
        return

    # (GATTO) il valore forse è da tarare
    experience = 100 * max(1, player.level / 2)
    player.experience += experience
    player.send_output("Guadagni [white]%d[close] di esperienza!" % experience)

    tessi.specials["player_on_quest"] = ""
    #to_say = "Quest False"
    #command_say(tessi, to_say)

    to_say_1 = "a %s È proprio il mio fermacapelli! Dopo tanto affanno ecco a te un piccolo presente come ringraziamento." % player.code
    defer_if_possible(1, 1, tessi, player, command_say, tessi, to_say_1)

    # Poiché un'iniezione silenziosa di un oggetto ad un giocatore non è molto
    # friendly allora dà il medaglione alla tessitrice e quest'ultima lo dà
    # al giocatore tramite un give
    medaglione = Item(MEDAGLIONE_PROTO_CODE)
    unguento   = Item(UNGUENTO_PROTO_CODE)
    medaglione.inject(tessi)
    unguento.inject(medaglione)
    defer_if_possible(2, 2, tessi, player, give_reward, tessi, medaglione, player)

    to_say_2 = "a %s Adoperalo con saggezza, solo quando saprai che farne perché potrai utilizzarlo una sola volta." % player.code
    defer_if_possible(3, 3, tessi, player, command_say, tessi, to_say_2)

    defer(4, reset_quest, tessi)
Ejemplo n.º 46
0
def gem_generation(unused_room):
    sum_relative_weight = 0
    for gem_code in GEM_WEIGHTS:
        #print "--> relative weight sum <--", sum_relative_weight
        sum_relative_weight += GEM_WEIGHTS[gem_code]
    #print "--> final reative weight sum <--", sum_relative_weight

    area = database["areas"]["miniere-kezaf"]
    rooms = area.rooms.values()
    #log.bug("start miniere kezaf", log_stack=False)
    rooms_to_fill = len(rooms) - 2
    #print "rooms_to_fill ", rooms_to_fill

    for room in random.sample(rooms, rooms_to_fill):
        for content in room.iter_contains(use_reversed=True): #maledetto, maledetto reversed!
            if FLAG.BURIED in content.flags:
                #log.bug("gem extraction: %s" % content.code, log_stack=False)
                content.extract(1)

        if random.randint(0, 1) == 0:
            #print gem_code_generator(sum_relative_weight)
            chosed_gem_code = gem_code_generator(sum_relative_weight)
            casual_gem = database["proto_items"][chosed_gem_code]
            if not casual_gem:
                log.bug("not casual gem: %s" % casual_gem, log_stack=False)
                return
        
            if casual_gem.has_reached_max_global_quantity():
                log.bug("not inject causa maxquantity of: %s" % casual_gem.code, log_stack=False)
            else:
                casual_gem = Item(chosed_gem_code)
                casual_gem.flags += FLAG.BURIED

                casual_gem.max_vigour = random.randint(MIN_GEM_VIGOUR, MAX_GEM_VIGOUR)
                casual_gem.vigour = random.randint(1,casual_gem.max_vigour)
                casual_gem.max_life = random.randint(MIN_GEM_LIFE, MAX_GEM_LIFE)
                casual_gem.life = random.randint(1,casual_gem.max_life)

                casual_gem.inject(room)

#            #if casual_gem.max_global_quantity == 0 or casual_gem.current_global_quantity < casual_gem.max_global_quantity:
#                casual_gem = Item(chosed_gem_code)
#                casual_gem.flags += FLAG.BURIED
#
#                casual_gem.max_vigour = random.randint(MIN_GEM_VIGOUR, MAX_GEM_VIGOUR)
#                casual_gem.vigour = random.randint(1,casual_gem.max_vigour)
#                casual_gem.max_life = random.randint(MIN_GEM_LIFE, MAX_GEM_LIFE)
#                casual_gem.life = random.randint(1,casual_gem.max_life)
#
#                casual_gem.inject(room)
#                #log.bug("insertion of: %s" % casual_gem.code, log_stack=False) 
#            else:
#                log.bug("not inject causa maxquantity of: %s" % casual_gem.code, log_stack=False)

    return True
def germinate(seed, room, age, fortuna):

    if seed.code not in database["items"]:
        return

    germoglio = Item("karpuram_item_mirtillo-rosso-02-germoglio")
    if not germoglio:
        log.bug("impossibile creare germoglio: %r" % germoglio)
        return

    #rudimentale contollo per vedere che il seme non sia stato spostato nel frattempo
    # 2 i problemi a cui si va incontro
    # aa) qualcuno lo droppa e poi lo raccatta e lo ridroppa 1ora dopo e comunque lui cresce (da evitare)
    # bb) la room stessa si resetta e anche se il seme non è stato spostato la room è cambiate e lui non cresce (da evitare)
    # forse il controllo con le coordinate xyz potrebbe risolvere b 
    # (gatto dice che non si presenta il problema bb anche se la room resetta)
    # c'è da vedere perché al solito credo ci siam fraintesi ed io pensavo al reset di room diverse nelle stesse coordinate

    # per risolvere aa forse basta in qualche modo che un get interrompa lo script (come fare?)
    if room != seed.location:
        # log da rimuovere 
        log.bug("room di drop diversa da room attuale")
        return

    location=seed.location

    seed.act("Di recente $N s'è schiuso...", TO.OTHERS, seed)
    seed.act("Di recente $N s'è schiuso...", TO.ENTITY, seed)

    seed.extract(1)

    germoglio.inject(location)

    germoglio.act("... in $N.", TO.OTHERS, germoglio)
    germoglio.act("... in $N.", TO.ENTITY, germoglio)
    fortuna = fortuna -1
    if random.randint(1, fortuna) == 1:
        reactor.callLater(random.randint( GERM_WAIT_MIN , GERM_WAIT_MAX ), desiccation, germoglio, room, age)
        return
    reactor.callLater(random.randint( GERM_WAIT_MIN , GERM_WAIT_MAX ), growing, germoglio, room, age, fortuna)
def growing(germoglio, room, age, fortuna):

    if germoglio.code not in database["items"]:
        return

    pianta = Item("karpuram_item_mirtillo-rosso-03-pianta")
    if not pianta:
        log.bug("impossibile creare pianta: %r" % pianta)
        return

    location=germoglio.location

    germoglio.act("Quel che poco tempo fa era solo $N, ora ...", TO.OTHERS, germoglio)
    germoglio.act("Quel che poco tempo fa era solo $N, ora ...", TO.ENTITY, germoglio)
    germoglio.extract(1)

    pianta.inject(location)

    pianta.act("... è $N.", TO.OTHERS, pianta)
    fortuna = fortuna -1
    if random.randint(1, fortuna) == 1:
        reactor.callLater(random.randint( PLANT_WAIT_MIN , PLANT_WAIT_MAX ), desiccation, pianta, room, age)
        return
    reactor.callLater(random.randint( PLANT_WAIT_MIN , PLANT_WAIT_MAX ), blooming, pianta, room, age, fortuna)
def before_try_to_get(entity, target, location, behavioured):
    manciata_torba = Item("karpuram_item_torba-manciata")
    laminetta_oro = Item("karpuram_item_laminetta-oro")

    if random.randint(1, 10) == 1:
        laminetta_oro.inject(location)
        entity.act("Metti la $hand in $N ed un luccicore ti distrae dal tuo proponimento!", TO.ENTITY, target)
        entity.act("tu che sei $N ti senti un po' deprezzato ogni volta $n ti indaga!", TO.TARGET, target)
        entity.act("$n affonda una mano in $N e si ferma sorpres$o.", TO.OTHERS, target)
        execution_result = command_get(entity, laminetta_oro.get_numbered_keyword(looker=entity))
    else:
        manciata_torba.inject(location)
        execution_result = command_get(entity, manciata_torba.get_numbered_keyword(looker=entity))

    # Se execution_result a True significa che è stato raccolta con successo
    # una manciata di torba e quindi ferma l'esecuzione del resto del comando get;
    # altrimenti è False e tornando False viene continuato il get del mucchio
    # di torba, che in futuro fallirà per motivi di peso
    return execution_result
def desiccation(generic_plant, room, age):

    if generic_plant.code not in database["items"]:
        return

    pianta_morta = Item("karpuram_item_mirtillo-rosso-06-pianta_morta")
    if not pianta_morta:
        # qui non dovrà uscire dallo script che sennò si frizza la pianta a questo stadio
        log.bug("impossibile creare pianta_morta: %r" % pianta_morta)
        return

    location=generic_plant.location

    generic_plant.act("Il rigoglio di $N ...", TO.OTHERS, generic_plant)
    generic_plant.act("Il rigoglio di $N ...", TO.ENTITY, generic_plant)
    generic_plant.extract()

    pianta_morta.inject(location)
    pianta_morta.descr_sixth = "una pianta che ha passato %r stagioni" % age
    pianta_morta.act("... è tramontato in $N.", TO.OTHERS, pianta_morta)
    pianta_morta.act("... è tramontato in $N.", TO.ENTITY, pianta_morta)
def after_buying(client, dealer, purchase, quantity, behavioured):
    item = Item(random.choice(PROTO_ITEM_CODES))
    item.inject(purchase)
    purchase.value = 0
Ejemplo n.º 52
0
def after_touch(entity, room, descr, detail, behavioured):
    tessera = Item(PROTO_TESSERA_CODE)
    tessera.icon = icona_testo_002
    tessera.inject(room)
def before_move(entity, from_room, direction, to_room, running, behavioured):
    if not entity.IS_PLAYER:
        return

    if direction != DIR.NORTHEAST:
        return

    for content in to_room.iter_contains():
        if content.IS_PLAYER:        
            continue           
        if content.prototype.code == oggetti["contenitore_01"]:
            return

    funghi = Item(oggetti["funghi"])
    contenitore_01 = Item(oggetti["contenitore_01"])
    contenitore_02 = Item(oggetti["contenitore_02"])
    contenitore_03 = Item(oggetti["contenitore_03"])
    premio_01 = Item(oggetti["premio_01"])
    premio_02 = Item(oggetti["premio_02"])
    premio_03 = Item(oggetti["premio_03"])

    funghi.inject(to_room)
    contenitore_01.inject(to_room)
    contenitore_02.inject(to_room)
    contenitore_03.inject(to_room)
    premio_01.inject(contenitore_01)
    premio_02.inject(contenitore_02)
    premio_03.inject(contenitore_03)
    
    to_room.act("\n[mediumturquoise]Una luce provieniente dal centro della cupola ti acceca per pochi attimi... qualcosa è cambiato attorno a te[close].")
    defer(3600, cleaning, to_room)
def after_inject(entity, room):
#   # Defer necessario per attendere il next stage precedente
#   defer(1, after_inject_deferred, seme, room) 
#
#def after_inject_deferred(seme, room):
    print ">>> inserimento fiori via inject"
    if not entity.specials or not 'ancestors' in entity.specials or entity.specials['ancestors'] == False:

        # Qui genero un genotipo solo per fare dei contacci e passare il valore ai successivi genotipi
        # sistema da migliorare...


        entity.specials['ancestors']       = True

        numero_rose = random.randint(4,10)
        for i in range(0,numero_rose):
            genotipo = genera_genotipo()
    
            rosa = Item(PROTO_ROSA_CODE)
            rosa.inject(entity)
            rosa.specials['fiore']             = str(genotipo.fiore_2g)
            rosa.specials['calice']            = str(genotipo.calice_2g)
            rosa.specials['sepali']            = str(genotipo.sepali_2g)
    
            rosa.specials['colore']            = str(genotipo.head_color)
            rosa.specials['colore_calice']     = str(genotipo.color2_2g)
            rosa.specials['colore_sepali']     = str(genotipo.color3_2g)
    
            rosa.specials['fiore_prob']    = genotipo.fiore_prob
            rosa.specials['calice_prob']   = genotipo.calice_prob
            rosa.specials['sepali_prob']   = genotipo.sepali_prob
    
            rosa.specials['colore_prob']   = genotipo.colore_prob
            rosa.specials['colore2_prob']  = genotipo.colore2_prob
            rosa.specials['colore3_prob']  = genotipo.colore3_prob
    
            rosa.specials['prob']          = genotipo.prob
            rosa.specials['price']         = genotipo.price
    
            rosa.specials['ancestors']     = True
    
            rosa.short = genotipo.flower
            rosa.name  = genotipo.flower
            rosa.value = int(max(1, round(genotipo.price)))
    
        # Temporaneo: alcuni dati dell'ultima rosa li metto sul cespuglio per verificare che
        # siano trasferiti sul next stage
        entity.descr += '\n' + genotipo.flower
    
        entity.specials['fiore']             = str(genotipo.fiore_2g)
        entity.specials['calice']            = str(genotipo.calice_2g)
        entity.specials['sepali']            = str(genotipo.sepali_2g)
    
        entity.specials['colore']            = str(genotipo.head_color)
        entity.specials['colore_calice']     = str(genotipo.color2_2g)
        entity.specials['colore_sepali']     = str(genotipo.color3_2g)
    
        entity.specials['fiore_prob']    = genotipo.fiore_prob
        entity.specials['calice_prob']   = genotipo.calice_prob
        entity.specials['sepali_prob']   = genotipo.sepali_prob
    
        entity.specials['colore_prob']   = genotipo.colore_prob
        entity.specials['colore2_prob']  = genotipo.colore2_prob
        entity.specials['colore3_prob']  = genotipo.colore3_prob
    
        entity.specials['prob']          = genotipo.prob
        entity.specials['price']         = genotipo.price
    
        entity.specials['ancestors']     = True
        #defer(1, set_special_after_next_stage, entity, rosa)
    return False
def popping_new_grappolo(room):
    new_grappolo = Item("torreelementi_item_grappolo-glicine-01")
    new_grappolo.inject(room)
def fructification(fiore, room, age, fortuna):

    if fiore.code not in database["items"]:
        return

    fruttificato = Item("karpuram_item_mirtillo-rosso-05-fruttificato")
    if not fruttificato:
        log.bug("impossibile creare fruttificato: %r" % fruttificato)
        return
    #l'istruzione Item è eseguita qui per il chk
    #poi però è ripetuta più volte nel loop
    #qui in qualche modo è codice sporco...
    bacca_buona = Item("karpuram_item_mirtillo-rosso-01-frutto")
    if not fruttificato:
        log.bug("impossibile creare fruttificato: %r" % bacca_buona)
        return
    bacca_cattiva = Item("karpuram_item_mirtillo-rosso-00-frutto-sterile")
    if not fruttificato:
        log.bug("impossibile creare fruttificato: %r" % bacca_cattiva)
        return

    location=fiore.location

    fiore.act("Dei fiori d'un tempo $N non ne ha più...", TO.OTHERS, fiore)
    fiore.act("Dei fiori d'un tempo $N non ne ha più...", TO.ENTITY, fiore)
    fiore.extract(1)

    fruttificato.inject(location)
    
    for q in xrange(MAX_FRUIT_QUANTITY + 2 * age + random.randint(1,4) - 2 ):
        bacca_buona = Item("karpuram_item_mirtillo-rosso-01-frutto")
        bacca_buona.inject(fruttificato) 

    for q in xrange(MAX_FRUIT_QUANTITY + 2 * age + random.randint(1,4) - 2 ):
        bacca_cattiva = Item("karpuram_item_mirtillo-rosso-00-frutto-sterile")
        bacca_cattiva.inject(fruttificato) 

    fruttificato.act("in compenso ora è $N.", TO.OTHERS, fruttificato)
    fortuna = fortuna -1
    if random.randint(1, fortuna) == 1:
        reactor.callLater(random.randint(GROWED_WAIT_MIN,GROWED_WAIT_MAX), desiccation, fruttificato, room, age )
        return
     
    reactor.callLater(random.randint(GROWED_WAIT_MIN,GROWED_WAIT_MAX), renew, fruttificato, room, age, fortuna )
Ejemplo n.º 57
0
	def test_export_same_format_type(self):
		item = Item([TestFormatSubClass(), TestFormatSubClass()])
		with self.assertRaises(ValueError):
				item.export()
Ejemplo n.º 58
0
def before_try_to_get(entity, target, location, behavioured):
    panzerotti_db = ["krablath_item_food-panzerotto-01",
                     "krablath_item_food-panzerotto-02",
                     "krablath_item_food-panzerotto-03"]

    num_rand = random.randint(1, 100)
    if num_rand < 33:
        panzerotto_code = panzerotti_db[0]
    elif num_rand < 66:
        panzerotto_code = panzerotti_db[1]
    else:
        panzerotto_code = panzerotti_db[2]

    # Alternativamente una soluzione che potrebbe essere considerata più
    # elegante del codice sopra potrebbe essere questa sotto.
    # Non hai la granularità del 100 ma chi se ne fre'.. e poi è più facilmente
    # percepibile anche solo ad occhio quali panzerotti verranno caricati di più
    # e quali meno
    #Se vuoi tenerla deve decommentare anche l'import del random in alto ed
    #eventualmente commentare quello del random.randint
    #panzerotti_db = ["karpuram_item_mirtillo-rosso-01-frutto",
    #                  "karpuram_item_mirtillo-rosso-01-frutto",
    #                  "karpuram_item_leccio-01-ghianda-viva",
    #                  "karpuram_item_leccio-01-ghianda-viva",
    #                  "karpuram_item_leccio-01-ghianda-viva",
    #                  "karpuram_item_leccio-02-ghianda-morta",
    #                  "karpuram_item_mirtillo-nero-01-frutto",
    #                  "karpuram_item_mirtillo-nero-01-frutto",
    #                  "karpuram_item_mirtillo-nero-01-frutto",
    #                  "karpuram_item_mirtillo-rosso-00-frutto-marcio",
    #                  "karpuram_item_mirtillo-rosso-00-frutto-marcio",
    #                  "karpuram_item_mirtillo-rosso-00-frutto-sterile",
    #                  "karpuram_item_mirtillo-rosso-00-frutto-sterile",
    #                  "karpuram_item_farnia-01-ghianda-viva",
    #                  "karpuram_item_farnia-01-ghianda-viva",
    #                  "karpuram_item_farnia-01-ghianda-viva",
    #                  "karpuram_item_farnia-01-ghianda-viva",
    #                  "karpuram_item_farnia-01-ghianda-viva",
    #                  "karpuram_item_farnia-02-ghianda-morta",
    #                  "karpuram_item_farnia-02-ghianda-morta",
    #                  "karpuram_item_farnia-02-ghianda-morta",
    #                  "karpuram_item_farnia-02-ghianda-morta"]
    #panzerotto_code = random.choice(panzerotti_db)

    # Crea e inserisce il panzerotto scelto nella locazione da cui prenderlo poi
    panzerotto_founded = Item(panzerotto_code)
    panzerotto_founded.inject(location)
    if random.randint(0, 1) == 1:
        panzerotto_founded.flags += FLAG.NO_LOOK_LIST

    # Attenzione che il get invierà i propri messaggi oltre a questi qua.
    entity.act("Infili la $hand verso $N.", TO.ENTITY, target)
    entity.act("$n allunga una mano verso $N.", TO.OTHERS, target)
    entity.act("Ti senti un po' deprezzato ogni volta che $n ti indaga!", TO.TARGET, target)

    # Bisogna utilizzare la get_numbered_keyword perché non si sa se entity
    # in quel momento stia guardando la short diurna, notturna o il nome
    numbered_keyword = panzerotto_founded.get_numbered_keyword(looker=entity)
    if location.IS_ROOM:
        argument = numbered_keyword
    else:
        argument = "%s %s " % (numbered_keyword, location.get_numbered_keyword(looker=entity))
    execution_result = command_get(entity, argument)

    # Questo è meglio farlo solo se il get è andato a buon fine, cioè quando
    # execution_result ha valore di verità positiva
    if execution_result:
        if target.weight < panzerotto_founded.weight:
            target.act("Dei $n che c'erano ora non resta nulla.", TO.OTHERS)
            target.act("Non resta più molto di te.", TO.ENTITY)
            target.extract(1)
        else:
            target.weight = target.weight - panzerotto_founded.weight

    return execution_result