示例#1
0
def exportTemplates(file):
    kv = KeyValues('WaveSchedule')
    log.info("Saving to {0}...".format(file))
    kv['Templates'] = KeyValues('Templates')
    for id in templates:
        kv['Templates'][id] = templates[id]
    kv.save(file)
    log.info("Saved {0} templates to {1}.".format(len(templates), file))
示例#2
0
def makeOptimizedTemplate(current, file, cwd):
    name = current['Name']
    if name not in namecounts:
        namecounts[name] = 0
    namecounts[name] += 1
    nameToUse = ''
    while True:
        #finalName=name.replace(" ","_")
        finalName = REGEX_INVALID_TEMPLATE_KEY_CHARS.sub('_', name).strip('_')
        if namecounts[name] > 1:
            finalName = 'T_OPT_TFBot_{0}_{1}'.format(finalName,
                                                     namecounts[name])
        else:
            finalName = 'T_OPT_TFBot_{0}'.format(finalName)
        if (finalName in templates and duplicateOf(
                current, templates[finalName])) or finalName not in templates:
            nameToUse = finalName
            break
        namecounts[name] += 1
    importTemplate(nameToUse, current)
    if nameToUse not in template_uses:
        template_uses[nameToUse] = 1
    else:
        template_uses[nameToUse] += 1
    current = KeyValues()
    current['Template'] = nameToUse
    return current
示例#3
0
    def get_events(self):
        """Returns a list of events found in the resource file."""
        if not self.path.exists():
            raise ESEventError('Resource file (%s) does not ' % self.path +
                               'exist!')

        return KeyValues(filename=self.path).keys()
示例#4
0
    def to_dict(self):
        """Converts a resource file to a python dictionary which contains the
        event names as keys and a sub-dictionary containing the event variables
        as keys, and the data keys as values.

        """
        if not self.path.exists():
            raise ESEventError('Resource file (%s) does not ' % self.path +
                               'exist!')

        # Set up the dictionary that will be returned
        return_dict = {}

        # Retrieve the keygroup
        res = KeyValues(filename=self.path)

        # Loop through each event and retrieve its variables
        for event in res:
            return_dict[str(event)] = {}

            for ev in res[event]:
                # Prints the event variable and data key
                return_dict[str(event)][str(ev)] = str(res[event][ev])

        return return_dict
示例#5
0
def exportPopfile(kv, file):
    log.info("Saving to {0}...".format(file))
    if 'Templates' not in kv:
        kv['Templates'] = KeyValues('Templates')
    skipped = []
    new_kv = KeyValues("Templates")
    for id in sorted(templates):
        if id in template_uses:
            new_kv[id] = templates[id]
            new_kv.set_comment(id, 'Used {0} times'.format(template_uses[id]),
                               0)
        else:
            skipped.append(id)
    kv['Templates'] = new_kv
    kv.save(file)
    log.info("Saved {0} templates to {1} ({2} skipped).".format(
        len(kv['Templates']), file, len(skipped)))
示例#6
0
    def _close(self, player_index):
        """See :meth:`menus.base._BaseMenu._close`."""
        queue = self.get_user_queue(player_index)
        queue.priority -= 1

        # Unfortunately, this doesn't hide the menu :(
        data = KeyValues('menu')
        data.set_string('title', '')
        data.set_int('level', queue.priority)
        data.set_int('time', 10)
        data.set_string('msg', '')
        create_message(edict_from_index(player_index), DialogType.MENU, data)
示例#7
0
    def _get_menu_data(self, player_index):
        """See :meth:`menus.base._BaseMenu._get_menu_data`."""
        data = KeyValues('menu')
        data.set_string(
            'msg', _translate_text(self.description or '', player_index))

        # Get the player's current page
        page = self._player_pages[player_index]
        page.options = {}

        # Format the menu
        self._format_header(player_index, page, data)
        self._format_body(player_index, page, data)
        self._format_footer(player_index, page, data)

        # Return the menu data
        return data
示例#8
0
    def send(self, *player_indexes, **tokens):
        """Send the Dialog message to the appropriate recipients.

        :param player_indexes: Values can be a player index, multiple player
            indexes (star args),
            a :class:`filters.players.PlayerIter` instance,
            or a :class:`filters.recipients.RecipientFilter` instance.
        :param tokens: Keyword arguments used to replace values in messages.
        """
        # Get a recipient filter of the given users
        recipients = RecipientFilter(*player_indexes)

        # Get the KeyValues instance
        keyvalues = KeyValues(self.message_type.name.lower())

        # Set the time for the message to display
        keyvalues.set_int('time', self.time)

        # Loop through all recipients
        for index in recipients:

            # Get a Player instance for the current player
            player = Player(index)

            # Is the player not human?
            if player.is_fake_client():
                continue

            # Get the level for the message
            level = self._get_player_level(player.userid)

            # Set the level for the player
            keyvalues.set_int('level', level)

            # Set the title (value should be server IP address)
            keyvalues.set_string(
                'title', self._get_text(self.title, player, **tokens))

            # Set any remaining keyvalues
            self._set_keyvalues(keyvalues, player, **tokens)

            # Send the message
            create_message(player.edict, self.message_type, keyvalues)
示例#9
0
    def _get_menu_data(self, player_index):
        """Return all menu data as a :class:`keyvalues.KeyValues` object.

        :param int player_index: See
            :meth:`menus.base._BaseMenu._get_menu_data`.
        """
        data = KeyValues('menu')
        data.set_string(
            'msg', _translate_text(self.description or '', player_index))

        if self.title is not None:
            data.set_string(
                'title', _translate_text(self.title, player_index))

        data.set_color('color', self.title_color)

        page = self._player_pages[player_index]
        page.options = {}

        # Loop through all options of the current page
        for raw_data in self:
            if isinstance(raw_data, SimpleESCOption):
                page.options[raw_data.choice_index] = raw_data
                button = data.find_key(str(raw_data.choice_index), True)
                button.set_string('msg', raw_data._render(player_index))
                button.set_string('command', '{0} {1}'.format(
                    ESC_SELECTION_CMD, raw_data.choice_index))

        close = SimpleESCOption(0, 'Close')
        button = data.find_key(str(close.choice_index), True)
        button.set_string('msg', close._render(player_index))
        button.set_string('command', '{0} {1}'.format(
            ESC_SELECTION_CMD, close.choice_index))

        # Return the menu data
        return data
示例#10
0
def importTemplates(file):
    _kv = KeyValues()
    log.info("Loading {0}".format(file))
    _kv.load(file)
    for id in _kv['Templates']:
        importTemplate(id, _kv['Templates'][id])
示例#11
0
if not os.path.isdir(outdir):
    os.makedirs(outdir)

log.basicConfig(format='%(asctime)s [%(levelname)-8s]: %(message)s',
                datefmt='%m/%d/%Y %I:%M:%S %p',
                filename=outfile + '.log',
                filemode='w',
                level=log.DEBUG)

for included_file in args.include:
    importTemplates(included_file)

if args.spawnpoints != '':
    importSpawnPoints(args.spawnpoints)

kv = KeyValues()
kv.load(sys.argv[1])
if 'Templates' in kv:
    for id in kv['Templates']:
        templates[id] = kv['Templates'][id]
log.info('Loaded {0} templates.'.format(len(templates)))

scanForInvalidTemplates(kv, args.input_file, ['WaveSchedule'])

log.info('Finished scanning: {0} warnings, {1} errors.'.format(
    stats['warnings'], stats['errors']))

log.info('Used templates: {0}'.format(len(template_uses)))
for key in sorted(template_uses.keys()):
    log.info('Template {0}: Used {1} times.'.format(key, template_uses[key]))