Esempio n. 1
0
def permitobject(df, type=None, id=None, permit_entities=None, all_entities=False, item_rarity=None):
    # Decide what tokens need to be added to the entities based on the object type
    if type == 'REACTION':
        tokens = raws.token(value='PERMITTED_REACTION', args=[id])
    elif type.startswith('BUILDING_'):
        tokens = raws.token(value='PERMITTED_BUILDING', args=[id])
    elif type.startswith('ITEM_'):
        value = type.split('_')[1]
        args = [id, item_rarity] if item_rarity else [id]
        tokens = raws.token(value=value, args=args)
    else:
        tokens = None
    
    pydwarf.log.debug('Permitting object [%s:%s] for %s entities.' % (
        type, id, 'all' if all_entities == '*' else len(permit_entities)
    ))
    
    # Actually add those tokens
    if tokens is None:
        return pydwarf.success('Didn\'t actually permit object [%s:%s] because objects of this type cannot be permitted.' % (type, id))
    elif not permit_entities:
        return pydwarf.failure('No entities were given for permitting.')
    else:
        response = addtoentity(
            df,
            entities = permit_entities,
            tokens = tokens
        )
        if not response:
            return response
        else:
            return pydwarf.success('Permitted object [%s:%s] for %d entities.' % (type, id, len(permit_entities)))
Esempio n. 2
0
def addhack(df, auto_run, onload=True, startup=False, **kwargs):
    name = kwargs.get('name', kwargs.get('path', 'unnamed'))
    
    onload_path = 'raw/onLoad.init'
    startup_path = 'dfhack.init'
    
    if kwargs: 
        pydwarf.log.debug('Adding new file %s.' % name)
        hackfile = df.add(**kwargs)
    else:
        hackfile = None
    
    if auto_run:
        if auto_run is True:
            if not hackfile: return pydwarf.failure('Failed to add lines to DFHack because auto_run was True but no file was created.')
            auto_run = '\n%s' % hackfile.name
        
        pydwarf.log.debug('Adding text %s to the end of dfhack.init.' % auto_run)
        addtext = '\n%s\n' % auto_run
        
        if onload:
            if onload_path not in df:
                init = df.add(
                    loc = 'raw',
                    name = 'onLoad',
                    ext = '.init',
                    kind = raws.binfile
                )
            else:
                init = df[onload_path]
            init.add(addtext)
            
        if startup:
            if startup_path not in df:
                if 'dfhack.init-example' in df:
                    pydwarf.log.info('Copying dfhack.init-example to new file dfhack.init before adding new content to the file.')
                    init = df['dfhack.init-example'].copy().bin()
                    init.name = startup_path
                    df.add(file=init)
                else:
                    return pydwarf.failure('Failed to locate dfhack.init or dfhack.init-example.')
            else:
                init = df[startup_path].bin()
            init.add(addtext)
        
        return pydwarf.success(
            'Added text to %s: "%s"' % (
                ' and '.join(
                    item for item in (
                        onload_path if onload else None, startup_path if startup else None
                    ) if item
                ),
                auto_run
            )
        )
        
    else:
        return pydwarf.success('Added new file %s.' % name)
def restrictnobles_custom(raws, inclusions=None, exclusions=None):
    mountain = raws.get('ENTITY:MOUNTAIN')
    if mountain:
        positions = mountain.alluntil(exact_value='POSITION', until_exact_value='ENTITY')
        if inclusions:
            pydwarf.log.debug('Handling position inclusions %s...' % inclusions)
            for inclusion in inclusions:
                for position in positions: addwm(position, 'ALLOWED_CLASS:WITTY_%s' % inclusion)
                creature = raws.get(exact_value='CREATURE', exact_args=[inclusion])
                if creature:
                    addwm(creature, 'CREATURE_CLASS:WITTY_%s' % inclusion)
                else:
                    return pydwarf.failure('Couldn\'t find CREATURE:%s.' % inclusion)
        if exclusions:
            pydwarf.log.debug('Handling position exclusions %s...' % exclusions)
            for exclusion in exclusions:
                for position in positions: addwm(position, 'REJECTED_CLASS:WITTY_%s' % exclusion)
                creature = raws.get(exact_value='CREATURE', exact_args=[exclusion])
                if creature:
                    addwm(creature, 'CREATURE_CLASS:WITTY_%s' % exclusion)
                else:
                    return pydwarf.failure('Couldn\'t find CREATURE:%s.' % exclusion)
        return pydwarf.success('Restricted %d positions.' % len(positions))
    else:
        return pydwarf.failure('Couldn\'t find ENTITY:MOUNTAIN.')
def easypatch_dirpath(df, path, loc=None, **kwargs):
    for root, dirnames, filenames in os.walk(path):
        for filename in filenames:
            filepath = os.path.join(root, filename)
            response = easypatch_filepath(df, path=filepath, loc=loc, root=root, **kwargs)
            if not response: return response
    return pydwarf.success('Added files from directory %s.' % path)
Esempio n. 5
0
def noaquifers(df):
    aquifers = df.all('AQUIFER')
    if len(aquifers):
        for aquifer in aquifers: aquifer.remove()
        return pydwarf.success('Removed %d AQUIFER tokens.' % len(aquifers))
    else:
        return pydwarf.failure('Found no AQUIFER tokens.')
def materialsplus(df, entities=default_entities):
    # Add properties to various inorganics as defined by the add_properties dict
    errors = 0
    for identifier, re_id, addprops in add_properties:
        additions = df.allobj(type='INORGANIC', re_id=re_id).each(
            lambda token: token.addprop(addprops), none=True
        )
        if len(additions):
            pydwarf.log.debug('Added %s properties to %d inorganics.' % (identifier, len(additions)))
        else:
            errors += 1
            pydwarf.log.error('Failed to add %s properties because no matching inorganics were found.' % identifier)
    
    for path in add_paths:
        pydwarf.log.debug('Adding file at %s.' % path)
        df.add(path=path, loc='raw/objects')
    
    for path in patch_paths:
        response = pydwarf.urist.getfn('pineapple.easypatch')(
            df,
            files = path,
            loc = 'raw/objects',
            permit_entities = entities
        )
        if not response: return response
    
    if not errors:
        return pydwarf.success()
    else:
        return pydwarf.failure('Failed to add inorganic properties for %d groups.' % errors)
Esempio n. 7
0
def full(df, variety='24x24', properties=properties_path):
    pydwarf.log.info('Running dragondeplatino.gemset.twbt.')
    response = twbt(df, variety)
    if not response: return response
    
    pydwarf.log.info('Running dragondeplatino.gemset.graphics.')
    response = graphics(df, variety)
    if not response: return response
    
    pydwarf.log.info('Running dragondeplatino.gemset.font.')
    response = font(df, variety)
    if not response: return response
    
    pydwarf.log.info('Running dragondeplatino.gemset.art.')
    response = art(df, variety)
    if not response: return response
    
    pydwarf.log.info('Running dragondeplatino.gemset.hack.')
    response = hack(df)
    if not response: return response
    
    pydwarf.log.info('Running dragondeplatino.gemset.objects.')
    response = objects(df, properties)
    if not response: return response
    
    # All done
    return pydwarf.success()
Esempio n. 8
0
def maxage(df, required_property=default_required_property, apply_to_creatures=None):
    removedfrom = []
    creaturedict = df.objdict('CREATURE')
    
    # Handle by properties
    if required_property:
        remove_all = len(required_property) == 1 and required_property[0] == '*'
        for creaturename, creaturetoken in creaturedict.iteritems():
            if remove_all or (creaturetoken.getprop(value_in=required_property) is not None):
                maxage = creaturetoken.getprop('MAXAGE')
                if maxage: maxage.remove(); removedfrom.append(creaturetoken)
                    
    # Handle by creature names
    if apply_to_creatures:
        for creaturename in apply_to_creatures:
            creaturetoken = creaturedict.get(creaturename)
            if creaturetoken:
                maxage = creaturetoken.getprop('MAXAGE')
                if maxage: maxage.remove(); removedfrom.append(creaturetoken)
            else:
                pydwarf.log.error('Couldn\'t find creature %s for removal of MAXAGE token.' % creaturename)
                
    # All done!
    pydwarf.log.debug('Removed MAXAGE tokens from creatures: %s.' % [token.args[0] for token in removedfrom])
    if len(removedfrom):
        return pydwarf.success('Removed MAXAGE tokens from %d creatues.' % len(removedfrom))
    else:
        return pydwarf.failure('Found no MAXAGE tokens to remove.')
        
def controllable(df, entities='*'):
    controllable = set()
    
    if entities == '*': # Enable all entities
        for entity in df.allobj('ENTITY'):
            entity.setprop('SITE_CONTROLLABLE')
            controllable.add(entity.args[0])
    else: # Enable listed entities and disable others
        entities = set([entities]) if isinstance(entities, basestring) else set(entities)
        for entity in df.allobj('ENTITY'):
            if entity.args[0] in entities:
                entity.setprop('SITE_CONTROLLABLE')
                controllable.add(entity.args[0])
                entities.remove(entity.args[0])
            else:
                entity.removeprop('SITE_CONTROLLABLE')
        if entities:
            pydwarf.log.error(
                'Nonexistent objects in controllable entities list: %s' % ', '.join(entities)
            )
                
    if controllable:
        return pydwarf.success('Assigned %d controllable entities.' % len(controllable))
    else:
        return pydwarf.failure('Assigned no controllable entities.')
Esempio n. 10
0
def stoneclarity(dfraws, rules=default_rules, query=default_inorganics_query, fuels=None):
    if rules and len(rules):
        groups, ids = builddicts(query, dfraws, fuels if fuels else autofuels(dfraws, pydwarf.log), pydwarf.log)
        applyrules(rules, groups, ids)
        return pydwarf.success('Finished applying %d rules to %d inorganic groups and %d inorganic ids.' % (len(rules), len(groups), len(ids)))
    else:
        return pydwarf.failure('I was given no rules to follow.')
def prefstring(df):
    # Get the smallthings ModBase raws, which is where this data will be coming from
    smallraws = getsmallraws()
    if not smallraws: return pydwarf.failure('Failed to read smallthings raws.')
    
    # Get all creatures
    smallcreatures = smallraws.allobj('CREATURE')
    dfcreaturesdict = df.objdict('CREATURE')
    
    # Add the new prefstrings
    failedcreatures = 0
    for smallcreature in smallcreatures:
        dfcreature = dfcreaturesdict.get(smallcreature.args[0])
        if not dfcreature:
            pydwarf.log.debug('Found prefstrings for %s but there was no corresponding creature in the DF raws. Skipping.' % smallcreature)
            failedcreatures += 1
        else:
            prefs = smallcreature.allprop(exact_value='PREFSTRING', args_count=1)
            dfcreature.add(tokens=prefs.copy())
            pydwarf.log.debug('Added %d prefstrings to %s.' % (len(prefs), dfcreature))
            
    # All done!
    if (len(smallcreatures) - failedcreatures):
        return pydwarf.success('Added prefstrings to %d creatures.' % (len(smallcreatures) - failedcreatures))
    else:
        return pydwarf.failure('Added prefstrings to no creatures.')
Esempio n. 12
0
def subterraneanplants(df):
    # Get subterranean plants
    subplants = []
    for plant in df.allobj('PLANT'):
        if plant.getprop('BIOME:SUBTERRANEAN_WATER'):
            subplants.append(plant)
    if not len(subplants): return pydwarf.failure('Found no subterranean plants.')
    
    # Ensure each has all four seasons
    pydwarf.log.info('Found %d subterranean plants. Modifying...' % len(subplants))
    modified = 0
    for subplant in subplants:
        seasontokens = subplant.allprop(value_in=seasons)
        if len(seasontokens) > 0 and len(seasontokens) < len(seasons):
            pydwarf.log.debug('Adding season tokens to %s...' % subplant)
            # First remove the existing tokens (To avoid making duplicates)
            for seasontoken in seasontokens:
                seasontoken.remove()
            # Then add all four anew
            for season in seasons:
                subplant.add(raws.token(value=season))
            modified += 1
        else:
            pydwarf.log.debug('Plant %s either has no seasonal tokens or already has all of them, skipping.' % subplant)
    
    # All done
    if modified > 0:
        return pydwarf.success('Made %d subterranean plants grow year-round.' % modified)
    else:
        return pydwarf.failure('All subterranean plants already grew year-round.')
Esempio n. 13
0
def metalitems(df, metals=default_metals, items=default_item_tokens):
    # Handle each metal
    modified = 0
    for inorganictoken in df.allobj('INORGANIC'):
        if inorganictoken.args[0] in metals:
            metal = inorganictoken.args[0]
            pydwarf.log.debug('Handling metal %s...' % metal)
            itemtokens = inorganictoken.allprop(value_in=items)
            if len(itemtokens) < len(items):
                pydwarf.log.debug('Adding tokens to metal %s...' % metal)
                # Remove existing item tokens from the list (To avoid making duplicates)
                for itemtoken in itemtokens:
                    itemtoken.remove()
                # Add new ones
                templatetoken = inorganictoken.getlastprop('USE_MATERIAL_TEMPLATE')
                addaftertoken = templatetoken if templatetoken else inorganictoken
                for item in items:
                    addaftertoken.add(item)
                modified += 1
            else:
                pydwarf.log.debug('Metal %s already allows all the item types specified, skipping.' % metal)
            
    # All done
    if modified > 0:
        return pydwarf.success('Added tokens to %d metals.' % modified)
    else:
        return pydwarf.failure('No tokens were added to any metals.')
Esempio n. 14
0
def font(df, variety='24x24'):
    # Copy over the font image
    mapfile = 'gemset_map.png'
    df.add(
        path = pydwarf.rel(gemset_dir, 'data/art/', variety, mapfile),
        loc = 'data/art',
        kind = raws.reffile
    )
    
    # Copy over the curses image
    cursesfile = 'gemset_curses_%s.png' % curses_resolutions.get(variety)
    df.add(
        path = pydwarf.rel(gemset_dir, 'data/art/', variety, cursesfile),
        loc = 'data/art',
        kind = raws.reffile
    )
    
    # Adjust init.txt settings accordingly
    init = df['data/init/init.txt'].raw()
    init.set(value='FONT', arg=cursesfile)
    init.set(value='FULLFONT', arg=cursesfile)
    init.set('GRAPHICS:YES')
    init.set(value='GRAPHICS_FONT', arg=mapfile)
    init.set(value='GRAPHICS_FULLFONT', arg=mapfile)
    init.set('PRINT_MODE:TWBT')
    init.set('BLACK_SPACE:YES')
    init.set('TRUETYPE:NO')
    
    # All done
    return pydwarf.success()
Esempio n. 15
0
def vegan(df, labors=default_labors, lua_file=default_lua_file, auto_run=False, entities=default_entities, add_to_file=default_file):
    # Add the reactions
    addreaction = pydwarf.urist.getfn('pineapple.utils.addobject')
    for reactionid, reactioncontent in vegan_reactions.iteritems():
        pydwarf.log.debug('Adding reaction %s.' % reactionid)
        response = addreaction(
            df,
            type = 'REACTION',
            id = reactionid,
            tokens = reactioncontent,
            add_to_file = add_to_file,
            permit_entities = entities
        )
        if not response.success: return response
    
    # Add the dfhack script
    if labors and lua_file:
        pydwarf.log.debug('Adding DFHack script %s.' % lua_file)
        pydwarf.urist.getfn('pineapple.utils.addhack')(
            df,
            name = lua_file,
            content = format_lua_content(lua_content, labors),
            auto_run = auto_run
        )
    
    # All done
    return pydwarf.success()
Esempio n. 16
0
def orientation(df,
                creatures=default_creatures,
                mode='hetero',
                lover_chance=default_lover_chance):
    if isinstance(mode, basestring):
        if mode not in mode_info:
            return pydwarf.failure(
                'Invalid mode %s. Recognized modes are these: %s.' %
                (mode, ', '.join(mode_tokens.keys())))
        usemode = mode_info[mode]
    else:
        usemode = mode

    # Unpack variables for convenience
    disinterestsame, loversame, commitsame, disinterestother, loverother, commitother = usemode

    # Get tokens for all the specified creatures
    creatures = df.allobj(type='CREATURE', id_in=creatures)
    pydwarf.log.debug('Found %d applicable creatures.' % len(creatures))

    # Add tokens after [FEMALE] and [MALE] tokens
    added = 0
    for creature in creatures:
        pydwarf.log.debug('Applying ORIENTATION changes to %s.' % creature)

        # Remove any existing ORIENTATION tokens
        removetokens = creature.allprop(exact_value='ORIENTATION')
        if len(removetokens):
            pydwarf.log.debug(
                'Removing %d existing ORIENTATION tokens from token %s.' %
                (len(removetokens), gendertoken))
            for removetoken in removetokens:
                removetoken.remove()

        # Add the new orientation tokens
        gendertokens = creature.allprop(value_in=('FEMALE', 'MALE'),
                                        args_count=0)
        for gendertoken in gendertokens:
            othergender = 'FEMALE' if gendertoken.value == 'MALE' else 'MALE'
            gendertoken.add(
                raws.token(value='ORIENTATION',
                           args=[
                               othergender, disinterestother, loverother,
                               commitother
                           ]))
            gendertoken.add(
                raws.token(value='ORIENTATION',
                           args=[
                               gendertoken.value, disinterestsame, loversame,
                               commitsame
                           ]))
            added += 1

    # All done!
    if added > 0:
        return pydwarf.success(
            'Appended ORIENTATION tokens after %d gender tokens.' % added)
    else:
        return pydwarf.failure('Found no gender tokens to add ORIENTATION to.')
Esempio n. 17
0
def flybears(raws):
    bears = raws.allobj('CREATURE', re_id='BEAR_.+')
    for bear in bears:
        bear.get('CASTE:FEMALE').add('FLIER')
    if len(bears):
        return pydwarf.success('Made %d bear species fliers.' % len(bears))
    else:
        return pydwarf.failure('Couldn\'t find any bears to make fliers.')
def noaquifers(df):
    # Do the removing
    aquifers = df.removeall('AQUIFER')
    # All done!
    if len(aquifers):
        return pydwarf.success('Removed %d AQUIFER tokens.' % len(aquifers))
    else:
        return pydwarf.failure('Found no AQUIFER tokens.')
Esempio n. 19
0
def noaquifers(df):
    # Do the removing
    aquifers = df.removeall('AQUIFER')
    # All done!
    if len(aquifers):
        return pydwarf.success('Removed %d AQUIFER tokens.' % len(aquifers))
    else:
        return pydwarf.failure('Found no AQUIFER tokens.')
Esempio n. 20
0
def trans(dfraws, species=default_species, beards=True, frequency=500):
    # Add new interaction
    pydwarf.log.debug('Adding sterility interaction...')
    objinteraction = dfraws.get('OBJECT:INTERACTION')
    if objinteraction:
        objinteraction.add(pretty=add_sterile_interaction)
    else:
        return pydwarf.failure('Unable to add sterility interaction.')
    
    # Add new castes
    creaturetokendict = dfraws.objdict('CREATURE')
    castefailures = []
    for creature in species:
        pydwarf.log.debug('Handling creature %s...' % creature)
        creaturetoken = creaturetokendict.get(creature)
        if creaturetoken:
            castes = creaturetoken.alluntil(exact_value='CASTE', args_count=1, until_exact_value='CREATURE')
            if len(castes) == 2 and ((castes[0].args[0] == 'MALE' and castes[1].args[0] == 'FEMALE') or (castes[1].args[0] == 'MALE' and castes[0].args[0] == 'FEMALE')):
                
                # Remove DESCRIPTION token from the creature and add it to each caste
                descriptiontoken = creaturetoken.get(exact_value='DESCRIPTION', args_count=1)
                if descriptiontoken:
                    descriptiontoken.remove()
                    for castetoken in castes: castetoken.add(token=raws.token.copy(descriptiontoken))
                
                # Handle existing castes
                for caste in castes:
                    # Add beards to dwarven women
                    if beards and caste.args[0] == 'FEMALE': caste.add(pretty=add_beard_tokens)
                    # Add population ratio token
                    caste.add(raws.token(value='POP_RATIO', args=[str(frequency)]))
                
                # Add each new caste
                for castename, castedict in additional_castes.iteritems():
                    castetoken = castes[0].add(raws.token(value='CASTE', args=[castename]), reverse=True)
                    # Every new caste gets these tokens
                    castetoken.add(pretty=add_trans_tokens)
                    # Add beards to new dwarf castes
                    if beards and creature == 'DWARF': castetoken.add(pretty=add_beard_tokens)
                    # Tokens unique to each new caste
                    if 'addtokens' in castedict: castetoken.add(pretty=castedict['addtokens'])
                    # Add the caste-specific description
                    description = ' '.join((descriptiontoken.args[0], castedict['description'])) if descriptiontoken else castedict['description']
                    castetoken.add(raws.token(value='DESCRIPTION', args=[description]))
                    
            else:
                pydwarf.log.error('Unexpected castes for creature %s: %s.' % (creature, castes))
                castefailures.append(creature)
        
        else:
            pydwarf.log.error('Failed to find token for creature %s.' % creature)
            castefailures.append(creature)
    
    if len(castefailures) == 0:
        return pydwarf.success('Added new castes to %d creatures.' % len(species))
    else:
        return pydwarf.failure('Added new castes to %d creatures, but failed to add castes to %s.' % (len(species) - len(castefailures), castefailures))
Esempio n. 21
0
def noexotic(df):
    pets = df.all('PET_EXOTIC')
    mounts = df.all('MOUNT_EXOTIC')
    for token in pets: token.value = 'PET'
    for token in mounts: token.value = 'MOUNT'
    if len(pets) or len(mounts):
        return pydwarf.success('Replaced %d PET_EXOTIC and %d MOUNT_EXOTIC tokens.' % (len(pets), len(mounts)))
    else:
        return pydwarf.failure('I found no PET_EXOTIC or MOUNT_EXOTIC tokens to replace.')
Esempio n. 22
0
def nograzers(raws):
    grazers = raws.all(exact_value='GRAZER')
    standardgrazers = raws.all('STANDARD_GRAZER')
    for grazer in grazers: grazer.remove()
    for grazer in standardgrazers: grazer.remove()
    if len(grazers) or len(standardgrazers):
        return pydwarf.success('Removed %d GRAZER and %d STANDARD_GRAZER tokens.' % (len(grazers), len(standardgrazers)))
    else:
        return pydwarf.failure('I found no grazer tokens to replace.')
Esempio n. 23
0
def art(df, variety='24x24'):
    # Copy over image files
    for artfile in art_files:
        df.add(path=pydwarf.rel(gemset_dir, 'data/art', variety, artfile),
               loc='data/art',
               replace=True,
               kind=raws.reffile)

    # All done
    return pydwarf.success()
Esempio n. 24
0
def addreaction(df, id, tokens, add_to_file='reaction_custom', permit_entities=None):
    if permit_entities is not None and (not addtoentity(df, permit_entities, permitted_reaction=(id,)).success):
        return pydwarf.failure('Failed to add permitted reactions to entites.')
    else:
        if df.getobj(type='REACTION', exact_id=id):
            return pydwarf.failure('Reaction %s already exists.' % id)
        else:
            rfile = df.getfile(add_to_file, create=True)
            rfile.add(raws.token(value='REACTION', args=[id], prefix='\n\n')).add(tokens)
            return pydwarf.success('Added reaction %s to file %s and entities %s.' % (id, add_to_file, permit_entities))
Esempio n. 25
0
def noexotic(df):
    # Do the removing
    pets = df.all('PET_EXOTIC').each(lambda token: token.setvalue('PET'), none=True)
    mounts = df.all('MOUNT_EXOTIC').each(lambda token: token.setvalue('MOUNT'), none=True)
    
    # All done!
    if len(pets) or len(mounts):
        return pydwarf.success('Replaced %d PET_EXOTIC and %d MOUNT_EXOTIC tokens.' % (len(pets), len(mounts)))
    else:
        return pydwarf.failure('I found no PET_EXOTIC or MOUNT_EXOTIC tokens to replace.')
Esempio n. 26
0
def nograzers(df):
    # Do the removing
    grazers = df.removeall('GRAZER')
    standardgrazers = df.removeall('STANDARD_GRAZER')
    
    # All done!
    if len(grazers) or len(standardgrazers):
        return pydwarf.success('Removed %d GRAZER and %d STANDARD_GRAZER tokens.' % (len(grazers), len(standardgrazers)))
    else:
        return pydwarf.failure('I found no grazer tokens to remove.')
Esempio n. 27
0
def nograzers(df):
    # Do the removing
    grazers = df.removeall('GRAZER')
    standardgrazers = df.removeall('STANDARD_GRAZER')
    
    # All done!
    if len(grazers) or len(standardgrazers):
        return pydwarf.success('Removed %d GRAZER and %d STANDARD_GRAZER tokens.' % (len(grazers), len(standardgrazers)))
    else:
        return pydwarf.failure('I found no grazer tokens to remove.')
Esempio n. 28
0
def easypatch_dirpath(df, path, loc=None, **kwargs):
    for root, dirnames, filenames in os.walk(path):
        for filename in filenames:
            filepath = os.path.join(root, filename)
            response = easypatch_filepath(df,
                                          path=filepath,
                                          loc=loc,
                                          root=root,
                                          **kwargs)
            if not response: return response
    return pydwarf.success('Added files from directory %s.' % path)
Esempio n. 29
0
def noanimalmen(df):
    # Do the removing
    removed = [removedprop for removedprop in df.allobj('CREATURE').each(
        lambda token: token.removeselfandprops() if token.arg().endswith('_MAN') or token.getprop('APPLY_CREATURE_VARIATION:ANIMAL_PERSON') else None
    ) if removedprop]
    
    # All done!
    if removed:
        return pydwarf.success('Removed %d species of animal men.' % len(removed))
    else:
        return pydwarf.failure('Found no animal men to remove.')
Esempio n. 30
0
def removeattacks(df, remove_attacks=('SCRATCH', 'BITE'), remove_attacks_from=('DWARF', 'HUMAN', 'ELF')):
    removed = 0
    for creature in df.allobj(type='CREATURE', id_in=remove_attacks_from):
        for attack in creature.allprop(exact_value='ATTACK', arg_in=((0, remove_attacks),)):
            pydwarf.log.debug('Removing attack %s from creature %s.' % (attack, creature))
            for token in attack.all(until_re_value='(?!ATTACK_).+'): token.remove()
            attack.remove()
            removed += 1
    if removed:
        return pydwarf.success('Removed %d attacks from %d creatures.' % (removed, len(remove_attacks_from)))
    else:
        return pydwarf.failure('Removed no attacks from creatures.')
Esempio n. 31
0
def art(df, variety='24x24'):
    # Copy over image files
    for artfile in art_files:
        df.add(
            path = pydwarf.rel(gemset_dir, 'data/art', variety, artfile),
            loc = 'data/art',
            replace = True,
            kind = raws.reffile
        )
    
    # All done
    return pydwarf.success()
Esempio n. 32
0
def armourypack(dfraws, remove_entity_items=True, remove_attacks=('SCRATCH', 'BITE'), remove_attacks_from=('DWARF', 'HUMAN', 'ELF')):
    try:
        armouryraws = raws.dir(path=armourydir, log=pydwarf.log)
    except:
        return pydwarf.failure('Unable to load armoury raws.')
    
    additemstoraws(dfraws, armouryraws)
    additemstoents(dfraws, armouryraws, remove_entity_items)
    addreactions(dfraws, armouryraws)
    removeattacks(dfraws, remove_attacks, remove_attacks_from)
    
    return pydwarf.success()
Esempio n. 33
0
def permitobjects(df, objects, **kwargs):
    pydwarf.log.debug('Permitting %d objects.' % len(objects))
    for item in objects:
        if isinstance(item, raws.token):
            type, id = item.value, item.arg()
        elif isinstance(item, basestring):
            type, id = item.split(':')
        else:
            type, id = item
        response = permitobject(df, type, id, **kwargs)
        if not response: return response
    return pydwarf.success('Permitted %d objects.' % len(objects))
Esempio n. 34
0
def graphics(df, variety='24x24', remove_example=True):
    # Remove example file if it still exists
    examplepath = 'raw/graphics/graphics_example.txt'
    if remove_example and examplepath in df: df.remove(examplepath)

    # Copy over image and graphics files
    df.add(path=pydwarf.rel(gemset_dir, 'raw/graphics', variety),
           loc='raw/graphics',
           replace=True)

    # All done
    return pydwarf.success()
Esempio n. 35
0
def flybears(df):
    # Get all bear creature tokens
    bears = df.allobj('CREATURE', re_id='BEAR_.+')
    
    # Add [FLIER] to each of them, immediately after the first CASTE:FEMALE token
    for bear in bears:
        bear.get('CASTE:FEMALE').add('FLIER')
        
    # All done!
    if len(bears):
        return pydwarf.success('Made %d bear species fliers.' % len(bears))
    else:
        return pydwarf.failure('Couldn\'t find any bears to make fliers.')
Esempio n. 36
0
def nograzers(raws):
    grazers = raws.all(exact_value='GRAZER')
    standardgrazers = raws.all('STANDARD_GRAZER')
    for grazer in grazers:
        grazer.remove()
    for grazer in standardgrazers:
        grazer.remove()
    if len(grazers) or len(standardgrazers):
        return pydwarf.success(
            'Removed %d GRAZER and %d STANDARD_GRAZER tokens.' %
            (len(grazers), len(standardgrazers)))
    else:
        return pydwarf.failure('I found no grazer tokens to replace.')
Esempio n. 37
0
def permitobjects(df, objects, **kwargs):
    pydwarf.log.debug('Permitting %d objects.' % len(objects))
    for item in objects:
        if isinstance(item, raws.token):
            type, id = item.value, item.arg()
        elif isinstance(item, basestring):
            type, id = item.split(':')
        else:
            type, id = item
        response = permitobject(df, type, id, **kwargs)
        if not response: return response
    return pydwarf.success('Permitted %d objects.' % len(objects))
    
Esempio n. 38
0
def addtoentity(df, entities, tokens):
    if isinstance(entities, basestring): entities = (entities,)
    pydwarf.log.debug('Adding tokens to entities %s.' % ', '.join(str(ent) for ent in entities))
    entitytokens = df.allobj(type='ENTITY', id_in=entities)
    
    for entitytoken in entitytokens:
        entitytoken.addprop(tokens)
        if isinstance(tokens, raws.queryable): tokens = raws.helpers.copy(tokens) # TODO: What about other iterables containing token objects, e.g. lists and tuples?
        
    if len(entitytokens) != len(entities):
        return pydwarf.failure('Failed to add tokens to all given entities because only %d of %d exist.' % (len(entitytokens), len(entities)))
    else:
        return pydwarf.success('Added tokens to %d entities.' % len(entitytokens))
Esempio n. 39
0
def playanimalmen(df):
    added = set()

    for animalman in df.allobj('CREATURE', re_id='.+MAN'):
        needprops = ('LARGE_ROAMING', 'CAN_LEARN', 'CAN_SPEAK')
        if (animalman.getprop('APPLY_CREATURE_VARIATION:ANIMAL_PERSON')
                or all(animalman.getprop(prop) for prop in needprops)):
            animalman.addprop('OUTSIDER_CONTROLLABLE')
            added.add(animalman.args[0])

    # All done, now let PyDwarf know the script did its job successfully.
    return pydwarf.success(
        'Added OUTSIDER_CONTROLLABLE tokens to %d creatures.' % len(added))
def engraving(df):
    if 'descriptor_shape_umiman' in df: return pydwarf.failure('File descriptor_shape_umiman already exists.')
        
    # Get the smallthings ModBase raws, which is where this data will be coming from
    smallraws = getsmallraws()
    if not smallraws: return pydwarf.failure('Failed to read smallthings raws.')
    
    # Get existing words and shapes
    dfwordsdict = df.objdict('WORD')
    dfshapesdict = df.objdict('SHAPE')
    
    # Add a new file for the new shapes
    dfshapesfile = df.add('raw/objects/descriptor_shape_umiman.txt')
    dfshapesfile.add('OBJECT:DESCRIPTOR_SHAPE')
    shapesadded = 0
    
    # Add each shape
    smallshapes = smallraws['descriptor_shape_standard']
    if smallshapes is None: return pydwarf.failure('Failed to find smallthings raws file named descriptor_shape_standard.')
    for smallshape in smallshapes.all(exact_value='SHAPE'):
        if smallshape.args[0] not in dfshapesdict: # Verify that the shape isn't already in the raws
            pydwarf.log.debug('Adding shape %s...' % smallshape)
            
            # Get the tokens describing this shape
            smallshapetokens = smallshape.all(until_exact_value='SHAPE')
            
            # Shapes in DF's descriptor_shape_standard all have a [WORD:X] token but these do not
            # To compensate, let's do our best to map each shape to a word automatically
            smallshapename = smallshape.get(exact_value='NAME', args_count=2)
            if smallshapename:
                useshapename = smallshapename.args[0].upper()
                if useshapename in shapenamedict: useshapename = shapenamedict[useshapename]
                shapeword = dfwordsdict.get(useshapename)
            else:
                pydwarf.log.error('Found no names for %s.' % shallshape)
                
            # Actually add the new shape to the raws
            dfshapesfile.add(smallshape.copy())
            dfshapesfile.add(smallshapetokens.copy())
            
            # And also add the word, provided one was found
            if shapeword:
                dfshapesfile.add(raws.token(value='WORD', args=(shapeword.args[0],)))
            else:
                pydwarf.log.info('Found no word for %s, named %s.' % (smallshape, smallshapename))
            
            # And on to the next iteration
            shapesadded += 1
    
    # All done!
    return pydwarf.success('Added %s new shapes.' % shapesadded)
Esempio n. 41
0
def maxage(df,
           ages=default_ages,
           apply_default_age=None,
           output_needs_age=False):
    added = []
    modified = []

    # Handle each creature
    for creaturetoken in df.allobj('CREATURE'):
        creaturename = creaturetoken.args[0]
        maxage = creaturetoken.getprop('MAXAGE')

        # Creature is in the ages dict, give it the age specified
        if creaturename in ages:
            agetuple = ages.get(creaturename)
            if agetuple is not None:
                pydwarf.log.debug('Applying MAXAGE %s to %s...' %
                                  (agetuple, creaturetoken))
                if maxage:
                    modified.append(creaturename)
                    maxage.args = list(agetuple)
                else:
                    added.append(creaturename)
                    creaturetoken.addprop(
                        raws.token(value='MAXAGE', args=list(agetuple)))

        # Creature isn't in the ages dict, check about applying a default or simply outputting its existence
        elif (not maxage) and (output_needs_age or apply_default_age):
            props = creaturetoken.propdict()
            if not ('COPY_TAGS_FROM' in props or 'EQUIPMENT_WAGON' in props
                    or 'MEGABEAST' in props or 'DOES_NOT_EXIST' in props
                    or 'NOT_LIVING' in props):
                if apply_default_age is not None:
                    pydwarf.log.debug('Applying default MAXAGE %s to %s...' %
                                      (apply_default_age, creaturetoken))
                    creaturetoken.addprop(
                        raws.token(value='MAXAGE',
                                   args=list(apply_default_age)))
                    added.append(creaturename)
                else:
                    pydwarf.log.info('Creature %s has no MAXAGE.')

    # All done!
    pydwarf.log.debug('Modified MAXAGE tokens of creatures: %s.' % modified)
    pydwarf.log.debug('Added MAXAGE tokens to creatures: %s.' % added)
    if len(added) or len(modified):
        return pydwarf.success(
            'Added %d MAXAGE tokens and modified %d existing ones.' %
            (len(added), len(modified)))
    else:
        return pydwarf.failure('No MAXAGE tokens affected.')
Esempio n. 42
0
def noexotic(raws):
    pets = raws.all('PET_EXOTIC')
    mounts = raws.all('MOUNT_EXOTIC')
    for token in pets:
        token.value = 'PET'
    for token in mounts:
        token.value = 'MOUNT'
    if len(pets) or len(mounts):
        return pydwarf.success(
            'Replaced %d PET_EXOTIC and %d MOUNT_EXOTIC tokens.' %
            (len(pets), len(mounts)))
    else:
        return pydwarf.failure(
            'I found no PET_EXOTIC or MOUNT_EXOTIC tokens to replace.')
Esempio n. 43
0
def permitobject(df,
                 type=None,
                 id=None,
                 permit_entities=None,
                 all_entities=False,
                 item_rarity=None):
    # Decide what tokens need to be added to the entities based on the object type
    if type == 'REACTION':
        tokens = raws.token(value='PERMITTED_REACTION', args=[id])
    elif type.startswith('BUILDING_'):
        tokens = raws.token(value='PERMITTED_BUILDING', args=[id])
    elif type.startswith('ITEM_'):
        value = type.split('_')[1]
        args = [id, item_rarity] if item_rarity else [id]
        tokens = raws.token(value=value, args=args)
    else:
        tokens = None

    pydwarf.log.debug(
        'Permitting object [%s:%s] for %s entities.' %
        (type, id, 'all' if all_entities == '*' else len(permit_entities)))

    # Actually add those tokens
    if tokens is None:
        return pydwarf.success(
            'Didn\'t actually permit object [%s:%s] because objects of this type cannot be permitted.'
            % (type, id))
    elif not permit_entities:
        return pydwarf.failure('No entities were given for permitting.')
    else:
        response = addtoentity(df, entities=permit_entities, tokens=tokens)
        if not response:
            return response
        else:
            return pydwarf.success(
                'Permitted object [%s:%s] for %d entities.' %
                (type, id, len(permit_entities)))
Esempio n. 44
0
def addobject(df,
              add_to_file,
              tokens,
              type=None,
              id=None,
              permit_entities=None,
              item_rarity=None,
              object_header=None):
    # If type and id weren't explicitly given then assume the first given token is the TYPE:ID header and get the info from there.
    header_in_tokens = type is None and id is None
    header = None
    if header_in_tokens:
        if isinstance(tokens, basestring): tokens = raws.parseplural(tokens)
        header = tokens[0]
        type = header.value
        id = header.arg()
        pydwarf.log.debug(
            'Extracted object type %s and id %s from given tokens.' %
            (type, id))

    # Get the applicable object dict which knows how to map TYPE:ID to its corresponding OBJECT:TYPE header.
    if object_header is None:
        object_header = raws.objects.headerforobject(type)

    # If add_to_file already exists, fetch it. Otherwise add it to the raws.
    add_to_file = add_to_file % {'type': object_header.lower()}
    if add_to_file in df:
        file = df.getfile(add_to_file)
    else:
        file = df.add(add_to_file)
        file.add(raws.token(value='OBJECT', args=[object_header]))
        pydwarf.log.debug('Added new file %s to dir.' % add_to_file)

    # Add the object itself to the raws.
    if not header_in_tokens:
        header = file.add(raws.token(value=type, args=[id]))
    file.add(tokens)

    # Add tokens to entities to permit the use of this object.
    if permit_entities:
        response = permitobject(df,
                                type=type,
                                id=id,
                                permit_entities=permit_entities,
                                item_rarity=item_rarity)
        if not response: return response

    # All done!
    return pydwarf.success('Added object %s to file %s.' % (header, file))
Esempio n. 45
0
def armourypack(dfraws,
                remove_entity_items=True,
                remove_attacks=('SCRATCH', 'BITE'),
                remove_attacks_from=('DWARF', 'HUMAN', 'ELF')):
    try:
        armouryraws = raws.dir(path=armourydir, log=pydwarf.log)
    except:
        return pydwarf.failure('Unable to load armoury raws.')

    additemstoraws(dfraws, armouryraws)
    additemstoents(dfraws, armouryraws, remove_entity_items)
    addreactions(dfraws, armouryraws)
    removeattacks(dfraws, remove_attacks, remove_attacks_from)

    return pydwarf.success()
Esempio n. 46
0
def easypatch_file(df, file, collision_fails=True, replace=False, **kwargs):
    if replace or str(file) not in df:
        df.add(file, replace=replace)
        objects = file.allobj()
        response = pydwarf.urist.getfn('pineapple.utils.permitobjects')(
            df, objects=objects, **kwargs)
        return response
    elif collision_fails:
        return pydwarf.failure(
            'Failed to add file because a file by the same name already exists in the dir.'
        )
    else:
        return pydwarf.success(
            'Didn\'t add the file because a file by the same name already exists in the dir.'
        )
Esempio n. 47
0
def milkbooze(df, entities=["MOUNTAIN"]):
    # Add material templates to milkable creatures
    beers_added = 0
    for file in df.files.values():
        if file.name.startswith("creature_"):
            last_name_token = None
            last_caste_token = None
            for token in file.tokens():
                if token.value == "CASTE":
                    last_caste_token = token
                elif token.value == "NAME":
                    last_name_token = token
                elif(
                    last_caste_token and
                    last_name_token and
                    token.next and
                    token.value == "USE_MATERIAL_TEMPLATE" and
                    token.args[0] == "MILK" and
                    token.args[1] == "MILK_TEMPLATE"
                ):
                    adjective = last_name_token.args[-1]
                    last_caste_token.addafter(
                        milk_beer_material_template % {"adj": adjective}
                    )
                    beers_added = beers_added + 1
                    pydwarf.log.debug("Added %s milk beer material template." % adjective)
    # Add MATERIAL_REACTION to milk template
    for cheese in df.all(
        "MATERIAL_REACTION_PRODUCT:CHEESE_MAT:LOCAL_CREATURE_MAT:CHEESE"
    ):
        pydwarf.log.debug(
            "Adding a milk beer material reaction product inside file %s." % str(cheese.file)
        )
        cheese.addafter(
            "[MATERIAL_REACTION_PRODUCT:DRINK_MAT:LOCAL_CREATURE_MAT:MILK_BEER]"
        )
    # Add a new reaction to stills to produce milk beers,
    # and give the specified entities access to that reaction
    addobject = pydwarf.scripts.pineapple.utils.addobject(
        df,
        add_to_file="raw/objects/reaction_milk_beer.txt",
        tokens=milk_beer_reaction,
        permit_entities=entities
    )
    if not addobject:
        return addobject
    else:
        return pydwarf.success("Added milk beers to %d milkable creatures." % beers_added)
Esempio n. 48
0
def noanimalmen(df):
    # Do the removing
    removed = [
        removedprop for removedprop in df.allobj('CREATURE').each(
            lambda token: token.removeselfandprops() if (token.arg().endswith(
                '_MAN') or token.arg().endswith(' MAN') or token.getprop(
                    'APPLY_CREATURE_VARIATION:ANIMAL_PERSON')) else None)
        if removedprop
    ]

    # All done!
    if removed:
        return pydwarf.success('Removed %d species of animal men.' %
                               len(removed))
    else:
        return pydwarf.failure('Found no animal men to remove.')
Esempio n. 49
0
def metalitems(df, metals=default_metals, items=default_item_tokens):
    # Turn the item names into a list of tokens
    itemtokens = [raws.token(value=item) for item in items]

    # Apply to each metal
    affected = df.allobj(type='INORGANIC', id_in=metals).each(lambda token: (
        # Remove existing tokens first to prevent duplicates when adding
        token.removeallprop(value_in=items),
        # And now add the specified tokens
        token.addprop(raws.helpers.copytokens(itemtokens))))

    # All done!
    if affected:
        return pydwarf.success('Affected %d metals.' % len(affected))
    else:
        return pydwarf.failure('Affected no metals.')
Esempio n. 50
0
def twbt(df, variety='24x24'):
    # Copy over the overrides.txt file
    df.add(path=pydwarf.rel(gemset_dir, 'data/init/overrides.txt'),
           loc='data/init',
           kind=raws.reffile,
           replace=True)

    # Copy over the image files
    for overridefile in override_files:
        df.add(path=pydwarf.rel(gemset_dir, 'data/art/', variety,
                                overridefile),
               loc='data/art',
               kind=raws.reffile,
               replace=True)

    # All done
    return pydwarf.success()
Esempio n. 51
0
def catechudye(df):
    acacia = df.getobj('PLANT:ACACIA')
    acacia.addafter('''
        [USE_MATERIAL_TEMPLATE:MILL:PLANT_POWDER_TEMPLATE]
            [STATE_NAME_ADJ:ALL_SOLID:catechu dye]
            [STATE_COLOR:ALL_SOLID:BROWN]
            [DISPLAY_COLOR:4:0:1]
            [MATERIAL_VALUE:20]
            [POWDER_DYE:RED]
            [PREFIX:NONE]
        [MILL:LOCAL_PLANT_MAT:MILL]
    ''')
    acacia.getprop('USE_MATERIAL_TEMPLATE:WOOD:WOOD_TEMPLATE').addafter('''
        [MATERIAL_REACTION_PRODUCT:MILL_PLANT_PART_POWDER:LOCAL_PLANT_MAT:POWDER]
        [STOCKPILE_PLANT_GROWTH]
    ''')
    return pydwarf.success('Added catechu dye product to acacia tree.')
Esempio n. 52
0
def skillrust(df, creatures=default_creatures, rates=default_rates):
    failures = []

    # Handle each creature
    creaturetokens = df.allobj(type='CREATURE', id_in=creatures)
    for creaturetoken in creaturetokens:
        pydwarf.log.debug('Handling skill rust for %s.' % creaturetoken)

        # First see about editing existing skill tokens
        needsnew = True
        editedtotal = 0
        existingtokens = creaturetoken.allprop(value_in=('SKILL_RATE',
                                                         'SKILL_RUST_RATE',
                                                         'SKILL_RATES',
                                                         'SKILL_RUST_RATES'))
        for existingtoken in existingtokens:
            pydwarf.log.debug('Modifying arguments for existing token %s.' %
                              existingtoken)
            edited = False
            if existingtoken.value in ('SKILL_RATES', 'SKILL_RUST_RATES'):
                needsnew = False
            editedtoken = edittoken(existingtoken, rates)
            editedtotal += editedtoken
            pydwarf.log.debug((
                'Modified arguments for token.') if editedtoken else (
                    'Token already has no skill rust.'))

        # Add a new one if no token affecting all skills was found
        if needsnew:
            pydwarf.log.debug('Adding new SKILL_RUST_RATES token.')
            creaturetoken.addprop('SKILL_RUST_RATES:NONE:NONE:NONE')

        # Creature already had no skill rust; consider this a failure
        elif not editedtotal:
            pydwarf.log.error('%s already has no skill rust.' % creaturetoken)
            failures.append(creaturetoken)

    # All done!
    failurecount = len(failures) + len(creatures) - len(creaturetokens)
    if failurecount == 0:
        return pydwarf.success('Removed skill rust from %d creatures.' %
                               len(creatures))
    else:
        return pydwarf.failure(
            'Failed to remove skill rust from %d creatures.' % failurecount)
Esempio n. 53
0
def nogiantanimals(df):
    # Do the removing
    removed = [
        removedprop for removedprop
        in df.allobj('CREATURE').each(lambda token: (token.removeselfandprops(
        ) if (token.arg().startswith('GIANT_') or token.arg(
        ).endswith(', GIANT') or token.arg().endswith('_GIANT') or token.arg(
        ).startswith('GIANT ') or token.arg().startswith('GIGANTIC ') or token.
              getprop('APPLY_CREATURE_VARIATION:GIANT')) else None))
        if removedprop
    ]

    # All done!
    if removed:
        return pydwarf.success('Removed %d species of giant animals.' %
                               len(removed))
    else:
        return pydwarf.failure('Found no giant animals to remove.')
Esempio n. 54
0
def deerappear(raws, creature='DEER', tile="'d'", color=['6','0','1']):
    # Find the first token that looks like [CREATURE:DEER]
    deertoken = raws.getobj('CREATURE', creature)
    if deertoken:
        # Find the first token, following [CREATURE:DEER], that looks like [CREATURE_TILE:'D']
        deertile = deertoken.getuntil(exact_value='CREATURE_TILE', args_count=1, until_exact_value='CREATURE')
        # Find the first token, following [CREATURE:DEER], that looks like [COLOR:6:0:0]
        deercolor = deertoken.getuntil(exact_value='COLOR', args_count=3, until_exact_value='CREATURE')
        if deertile and deercolor:
            # Change the token to look like [CREATURE_TILE:'d']
            deertile.args[0] = tile
            # Change the token to look like [COLOR:6:0:1]
            deercolor.args = color
            return pydwarf.success()
        else:
            return pydwarf.failure('Didn\'t find CREATURE_TILE and COLOR tokens as expected.')
    else:
        return pydwarf.failure('I couldn\'t find the deer token.')
Esempio n. 55
0
def removeattacks(df,
                  remove_attacks=('SCRATCH', 'BITE'),
                  remove_attacks_from=('DWARF', 'HUMAN', 'ELF')):
    removed = 0
    for creature in df.allobj(type='CREATURE', id_in=remove_attacks_from):
        for attack in creature.allprop(exact_value='ATTACK',
                                       arg_in=((0, remove_attacks), )):
            pydwarf.log.debug('Removing attack %s from creature %s.' %
                              (attack, creature))
            for token in attack.all(until_re_value='(?!ATTACK_).+'):
                token.remove()
            attack.remove()
            removed += 1
    if removed:
        return pydwarf.success('Removed %d attacks from %d creatures.' %
                               (removed, len(remove_attacks_from)))
    else:
        return pydwarf.failure('Removed no attacks from creatures.')
Esempio n. 56
0
def subterraneanplants(dfraws):
    subplants = []
    for plant in dfraws.allobj('PLANT'):
        if plant.getuntil(pretty='BIOME:SUBTERRANEAN_WATER',
                          until_exact_value='PLANT'):
            subplants.append(plant)
    if not len(subplants):
        return pydwarf.failure('Found no subterranean plants.')
    pydwarf.log.info('Found %d subterranean plants. Modifying...' %
                     len(subplants))
    for subplant in subplants:
        pydwarf.log.debug('Handling %s...' % subplant)
        for seasontoken in subplant.alluntil(value_in=seasons,
                                             until_exact_value='PLANT'):
            seasontoken.remove()
        for season in seasons:
            subplant.add(raws.token(value=season))
    return pydwarf.success('Made %d subterranean plants grow year-round.' %
                           len(subplants))
Esempio n. 57
0
def easypatch(df, files, **kwargs):
    if isinstance(files, basestring):
        if os.path.isfile(files):
            return easypatch_filepath(df, files, **kwargs)
        elif os.path.isdir(files):
            return easypatch_dirpath(df,
                                     files,
                                     collision_fails=False,
                                     **kwargs)
        else:
            return easypatch_content(df, files, **kwargs)
    elif isinstance(files, raws.tokenlist):
        return easypatch_tokens(df, files, **kwargs)
    elif isinstance(files, raws.rawfile):
        return easypatch_file(df, files, **kwargs)
    else:
        for file in files:
            response = easypatch(df, file, collision_fails=False, **kwargs)
            if not response: return response
        return pydwarf.success('Added %d files.' % len(files))
Esempio n. 58
0
def microreduce(dfraws):
    mountain = dfraws.get('ENTITY:MOUNTAIN')
    if mountain:
        # Add files
        genericpath = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                   'Microreduce', '%s.txt')
        for filename in ('building_macro_fantastic', 'item_macro_fantastic',
                         'reaction_macro_fantastic'):
            rfile = dfraws.addfile(path=genericpath % filename)
            # Add PERMITTED_BUILDING and PERMITTED_REACTION tokens to ENTITY:MOUNTAIN
            for building in rfile.all(re_value='BUILDING.*', args_count=1):
                mountain.add(
                    raws.token(value='PERMITTED_BUILDING',
                               args=[building.args[0]]))
            for reaction in rfile.all(exact_value='REACTION', args_count=1):
                mountain.add(
                    raws.token(value='REACTION', args=[reaction.args[0]]))
        return pydwarf.success()
    else:
        return pydwarf.failure('Couldn\'t find ENTITY:MOUNTAIN.')