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 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))
Пример #3
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)
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)))
Пример #5
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()
Пример #6
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
Пример #7
0
def register_for_event_file(file_name):
    events = KeyValues('event')
    if not events.load_from_file(file_name):
        _set_last_error('Couldn\'t load events file.')
        return False

    import es

    kv = events.first_sub_key
    while kv:
        es.dbgmsg(1, 'Added: {}'.format(kv.name))
        game_event_manager.add_listener(es_event_listener, kv.name, True)
        kv = kv.next_key

    es.dbgmsg(1, 'Done loading events.')
    return True
Пример #8
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
Пример #9
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)))
Пример #10
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
Пример #11
0
    def _close(self, player_index):
        """Close a menu by overriding it with an empty menu.

        @param <player_index>:
        A player index.
        """
        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)
Пример #12
0
    def _get_menu_data(self, player_index):
        """Return all relevant menu data as a KeyValues instance.

        @param <player_index>:
        A player index.
        """
        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
Пример #13
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
Пример #14
0
def register_for_event_file(file_name):
    events = KeyValues.load_from_file(file_name)
    if events is None:
        _set_last_error('Couldn\'t load events file.')
        return False

    import es

    kv = events.first_sub_key
    while kv:
        es.dbgmsg(1, 'Added: {}'.format(kv.name))
        game_event_manager.add_listener(es_event_listener, kv.name, True)
        kv = kv.next_key

    es.dbgmsg(1, 'Done loading events.')
    return True
Пример #15
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)
Пример #16
0
    def _get_menu_data(self, player_index):
        """Return all relevant menu data as a KeyValues instance.

        @param <player_index>:
        A player index.
        """
        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
Пример #17
0
    def fire_game_event(self, event_name, **kwargs):
        """Creates and fires an event to this player.

        :param str event_name:
            The name of the event to create and fire.
        :param dict kwargs:
            The variables to set to the event.
        """
        # Create the event
        game_event = game_event_manager.create_event(event_name, True)

        # Set the variables
        game_event.variables.recursive_copy(
            KeyValues.from_dict(event_name, kwargs))

        # Fire the event
        self.base_client.fire_game_event(game_event)

        # Free the event
        game_event_manager.free_event(game_event)
Пример #18
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)
Пример #19
0
def _apply_update_stage1_windows():
    """Apply the Windows specific part of stage 1.

    On Windows files that are currently in use (``source-python.dll``) can't be
    replaced. Thus, this function checks if ``source-python.vdf`` exists. If it
    does, the new ``source-python.dll`` is copied to the addons directory with
    a new name (``source-python2.dll``). After that the VDF entry is modified
    to point to the new loader.
    If ``source-python.vdf`` does not exist, manual action is required.
    """
    if not VDF_FILE.isfile():
        update_logger.log_message(
            f'Stage 1 has been applied. Please shutdown your server and move '
            f'(do not copy) {LOADER_UPDATE_FILE} to {LOADER_FILE}. After that '
            f'start your server to apply stage 2.')
    else:
        update_logger.log_debug('Determining current VDF entry...')
        kv = KeyValues.from_file(VDF_FILE)

        # Get the current and new entry for the VDF file
        current_entry = kv.get_string('file')
        if current_entry == SP_VDF2:
            new_entry = SP_VDF1
        elif current_entry == SP_VDF1:
            new_entry = SP_VDF2
        else:
            raise ValueError(f'Unexpected entry in VDF: {current_entry}')

        update_logger.log_debug(f'Current VDF entry: {current_entry}')
        update_logger.log_debug(f'New VDF entry: {new_entry}')

        update_logger.log_debug(
            'Moving new loader binary to game directory...')
        LOADER_UPDATE_FILE.move(GAME_PATH / f'{new_entry}.{BINARY_EXT}')

        kv.set_string('file', new_entry)
        kv.save_to_file(VDF_FILE)

        update_logger.log_message(
            'Stage 1 has been applied. Restart your server to apply stage 2.')
Пример #20
0
def _apply_update_stage1_windows():
    """Apply the Windows specific part of stage 1.

    On Windows files that are currently in use (``source-python.dll``) can't be
    replaced. Thus, this function checks if ``source-python.vdf`` exists. If it
    does, the new ``source-python.dll`` is copied to the addons directory with
    a new name (``source-python2.dll``). After that the VDF entry is modified
    to point to the new loader.
    If ``source-python.vdf`` does not exist, manual action is required.
    """
    if not VDF_FILE.isfile():
        update_logger.log_message(
            f'Stage 1 has been applied. Please shutdown your server and move '
            f'(do not copy) {LOADER_UPDATE_FILE} to {LOADER_FILE}. After that '
            f'start your server to apply stage 2.')
    else:
        update_logger.log_debug('Determining current VDF entry...')
        kv = KeyValues.load_from_file(VDF_FILE)

        # Get the current and new entry for the VDF file
        current_entry = kv.get_string('file')
        if current_entry == SP_VDF2:
            new_entry = SP_VDF1
        elif current_entry == SP_VDF1:
            new_entry = SP_VDF2
        else:
            raise ValueError(f'Unexpected entry in VDF: {current_entry}')

        update_logger.log_debug(f'Current VDF entry: {current_entry}')
        update_logger.log_debug(f'New VDF entry: {new_entry}')

        update_logger.log_debug('Moving new loader binary to game directory...')
        LOADER_UPDATE_FILE.move(GAME_PATH / f'{new_entry}.{BINARY_EXT}')

        kv.set_string('file', new_entry)
        kv.save_to_file(VDF_FILE)

        update_logger.log_message(
            'Stage 1 has been applied. Restart your server to apply stage 2.')
Пример #21
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]))
Пример #22
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])
Пример #23
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])
Пример #24
0
if outfile == '':
	outfile=args.input_file+'.new'
outfile = os.path.abspath(outfile)
outdir = os.path.dirname(outfile)
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]))

#exportTemplates('PARSED_TEMPLATES.pop')