def send_popup(player): if get_status() == GameStatus.BUSY: tell(player, strings_module['fail game_busy']) return arcjail_user = arcjail_user_manager[player.index] popup = PagedMenu(select_callback=popup_select_callback, title=strings_module['popup title']) for item in arcjail_user.iter_all_items(): if player.team not in item.class_.use_team_restriction: continue if not item.class_.manual_activation: continue popup.append(PagedOption( text=strings_module['popup entry'].tokenize( caption=item.class_.caption, amount=item.amount), value=item, )) if not popup: popup.title = strings_module['popup empty_message'] popup.send(player.index)
def launch_voting(player, wont_play_option=False): reason = get_game_denial_reason(player) if reason is not None: tell(player, reason) return global _last_voting if _last_voting is not None: _last_voting.finish() _last_voting = GameVoting() popup = PagedMenu( select_callback=_last_voting.select_callback, title=strings_module['popup title'] ) if wont_play_option: popup.append(PagedOption( text=strings_module['popup option wont_play'], value="WONT_PLAY", )) players = get_players_to_play() for launcher in get_available_launchers(player, players): popup.append(PagedOption( text=launcher.caption, value=launcher, )) _last_voting.start(popup, players, config_manager['timeout'])
def launch_voting(player, wont_play_option=False): reason = get_game_denial_reason(player) if reason is not None: tell(player, reason) return global _last_voting if _last_voting is not None: _last_voting.finish() _last_voting = GameVoting() popup = PagedMenu(select_callback=_last_voting.select_callback, title=strings_module['popup title']) if wont_play_option: popup.append( PagedOption( text=strings_module['popup option wont_play'], value="WONT_PLAY", )) players = get_players_to_play() for launcher in get_available_launchers(player, players): popup.append(PagedOption( text=launcher.caption, value=launcher, )) _last_voting.start(popup, players, config_manager['timeout'])
def send_popup(player): if get_status() == GameStatus.BUSY: tell(player, strings_module['fail game_busy']) return arcjail_user = arcjail_user_manager[player.index] popup = PagedMenu(select_callback=popup_select_callback, title=strings_module['popup title']) for item in arcjail_user.iter_all_items(): if player.team not in item.class_.use_team_restriction: continue if not item.class_.manual_activation: continue popup.append( PagedOption( text=strings_module['popup entry'].tokenize( caption=item.class_.caption, amount=item.amount), value=item, )) if not popup: popup.title = strings_module['popup empty_message'] popup.send(player.index)
def shopinfo_menu_subcats_select(menu, index, choice): userid = userid_from_index(index) item = choice.value iteminfo = wcs.wcs.itemdb.getItem(item) desc = iteminfo['desc'] cost = int(iteminfo['cost']) required = int(iteminfo['level']) required_status = int(iteminfo['dab']) if required_status == 1: required_status = '<alive>' if required_status == 0: required_status = '<dead>' if required_status == 2: required_status = '<always>' duration = int(iteminfo['duration']) if duration == 1: duration = '<Until death>' if duration == 0: duration = '<One round>' maximum = int(iteminfo['max']) shopinfo_race_menu = PagedMenu(title='%s' % iteminfo['name'], parent_menu=menu) shopinfo_race_menu.append(Text('o %s' % desc)) shopinfo_race_menu.append(Text('Required level: %s' % required)) shopinfo_race_menu.append(Text('Cost: %s' % cost)) shopinfo_race_menu.append(Text('Buyable when: %s' % required_status)) shopinfo_race_menu.append(Text('Duration: %s' % duration)) shopinfo_race_menu.send(index)
def get_winners_menu(player): """Return a sorted menu of all winners.""" menu = PagedMenu(title=menu_strings['Winners:Title']) if not winners_database: menu.description = menu_strings['Winners:None'] return menu winners = sorted( winners_database, key=lambda key: ( winners_database[key].wins, -winners_database[key].time_stamp, ), reverse=True, ) for rank, unique_id in enumerate(winners, 1): instance = winners_database[unique_id] menu.append( ListOption( choice_index=rank, text='{name} [{wins}]'.format( name=instance.name, wins=instance.wins ), value=unique_id, highlight=player.uniqueid == unique_id, selectable=False, ) ) return menu
def send_leaders_menu(index): """Send the leaders menu to the player.""" menu = PagedMenu(title=menu_strings['Leader:Current']) language = Player(index).language if GunGameStatus.MATCH is not GunGameMatchStatus.ACTIVE: menu.append(menu_strings['Inactive']) elif gg_plugin_manager.is_team_game: menu.append(menu_strings['Leader:Team']) leader_level = max(team_levels.values()) teams = [ team_names[num] for num, level in team_levels.items() if level == leader_level ] weapon = weapon_order_manager.active[leader_level].weapon if len(teams) == len(team_levels): if len(teams) > 2: message = menu_strings['Leader:Team:All'].get_string( language=language, level=leader_level, weapon=weapon, ) else: message = menu_strings['Leader:Team:Tied'].get_string( language=language, level=leader_level, weapon=weapon, ) elif len(teams) > 1: message = menu_strings['Leader:Team:Multiple'].get_string( language=language, level=leader_level, weapon=weapon, ) message += '\n\t* {teams}'.format( teams=', '.join(teams) ) else: message = menu_strings['Leader:Team:Current'].get_string( language=language, team=teams[0], level=leader_level, weapon=weapon, ) menu.append(StarOption(message)) elif leader_manager.current_leaders is None: menu.append(menu_strings['Leader:None']) else: level = leader_manager.leader_level menu.description = menu_strings['Leader:Level'].get_string( language=language, level=level, weapon=weapon_order_manager.active[level].weapon, ) for userid in leader_manager.current_leaders: menu.append(StarOption(player_dictionary[userid].name)) menu.send(index)
def send_rules(index): """Send the rules menu to the player.""" menu = PagedMenu( title=rules_translations['Rules:Header'], select_callback=_send_plugin_rules, ) loaded_plugins = [ plugin_name for plugin_name in all_gungame_rules if plugin_name in gg_plugin_manager ] if not loaded_plugins: menu.append(rules_translations['Rules:Empty']) menu.send(index) return for plugin_name in sorted(loaded_plugins): menu.append(PagedOption(rules_translations[plugin_name], plugin_name)) menu.send(index)
def _send_plugin_rules(parent_menu, index, choice): plugin_name = choice.value menu = PagedMenu(title=rules_translations[plugin_name]) menu.parent_menu = parent_menu rules = all_gungame_rules[plugin_name] tokens = { key: getattr(value['convar'], 'get_' + value['type'])() for key, value in rules.convar_tokens.items() } for rule in rules: menu.append( StarOption( rules[rule].get_string( language=Player(index).language, **tokens ) ) ) menu.send(index)
def send_weapons_menu(index): """Send the weapon menu to the player.""" menu = PagedMenu(title=menu_strings['Weapons:Title']) if GunGameStatus.MATCH is not GunGameMatchStatus.ACTIVE: menu.append(menu_strings['Inactive']) else: player = player_dictionary[userid_from_index(index)] for level, instance in weapon_order_manager.active.items(): menu.append( ListOption( choice_index=level, text='{weapon} [{multi_kill}]'.format( weapon=instance.weapon, multi_kill=instance.multi_kill, ), value=level, highlight=level == player.level, selectable=False, ) ) menu.send(index)
def send_score_menu(index): """Send the score menu to the player.""" menu = PagedMenu(title=menu_strings['Score:Title']) player = player_dictionary.from_index(index) if GunGameStatus.MATCH is GunGameMatchStatus.WARMUP: menu.append(menu_strings['Warmup']) elif GunGameStatus.MATCH is not GunGameMatchStatus.ACTIVE: menu.append(menu_strings['Inactive']) elif gg_plugin_manager.is_team_game: for team in sorted( team_levels, key=lambda x: team_levels[x], reverse=True, ): menu.append( ListOption( choice_index=team_levels[team], text=team_names[team], value=team, highlight=team == player.team_index, selectable=False, ) ) else: for userid in sorted( player_dictionary, key=lambda key: player_dictionary[key].level, reverse=True, ): current_player = player_dictionary[userid] menu.append( ListOption( choice_index=current_player.level, text=current_player.name, value=current_player.unique_id, highlight=current_player.unique_id == player.unique_id, selectable=False, ) ) menu.send(index)
class _SettingsDictionary(OrderedDict): """Class used to store user settings.""" def __init__(self, name, text=None): """Verify the name value and stores base attributes.""" # Is the given name a proper value for a convar? if not name.replace('_', '').replace(' ', '').isalpha(): # Raise an error raise ValueError( 'Given name "{0}" is not valid'.format(name)) # Set the base attributes self.name = name self.text = text # Create the instance's menu self.menu = PagedMenu( select_callback=self._chosen_item, title=name if text is None else text) # Call the super class' __init__ to initialize the OrderedDict super().__init__() def __setitem__(self, item, value): """Validate the given value and its type before setting the item.""" # Is the given value a proper type? if not isinstance(value, (_SettingsDictionary, SettingsType)): # Raise an error raise ValueError( 'Given value "{0}" is not valid'.format(value)) # Is the item already in the dictionary? if item in self: # Raise an error raise ValueError( 'Given item "{0}" is already registered'.format(item)) # Set the item in the dictionary super().__setitem__(item, value) # Get the new object value = self[item] # Set the item's prefix value.prefix = self.prefix if not value.prefix.endswith('_'): value.prefix += '_' # Does the section's name need added to the prefix? if not isinstance(self, PlayerSettings): # Add the section's name to the prefix value.prefix += self.name.lower().replace(' ', '_') + '_' # Add the option to the menu self.menu.append(PagedOption( value.name if value.text is None else value.text, value)) def add_int_setting( self, name, default, text=None, min_value=None, max_value=None): """Add a new integer setting to the dictionary.""" self[name] = IntegerSetting(name, default, text, min_value, max_value) return self[name] def add_bool_setting(self, name, default, text=None): """Add a new boolean setting to the dictionary.""" self[name] = BoolSetting(name, default, text) return self[name] def add_string_setting(self, name, default, text=None): """Add a new string setting to the dictionary.""" self[name] = StringSetting(name, default, text) return self[name] def add_section(self, name, text=None): """Add a new section to the dictionary.""" self[name] = _SettingsDictionary(name, text) return self[name] @staticmethod def _chosen_item(menu, index, option): """Called when an item is chosen from the instance's menu.""" # Is the chosen value another branch of settings? if isinstance(option.value, _SettingsDictionary): # Send the new menu option.value.menu.send(index) # No need to go further return # TODO: Placeholder for sending setting specific menus option.value.menu.send(index)
def raceinfo_menu_select(menu, index, choice): race = choice.value raceinfo = wcs.wcs.racedb.getRace(race) required = raceinfo['required'] maximum = raceinfo['maximum'] allowonly = raceinfo['allowonly'] desc = raceinfo['desc'] skillnames = raceinfo['skillnames'].split('|') skilldesc = raceinfo['skilldescr'].split('|') numberofskills = int(raceinfo['numberofskills']) - 1 raceinfo_race_menu = PagedMenu(title='Raceinfo - %s' % race, parent_menu=menu) raceinfo_race_menu.append(Text('Required level: %s' % required)) raceinfo_race_menu.append(Text('Maximum level: %s' % maximum)) if allowonly: raceinfo_race_menu.append(Text('<Private Race>')) if desc: raceinfo_race_menu.append(Text('Description: %s' % desc)) raceinfo_race_menu.append(Text('Skills:')) x = 0 while x <= numberofskills: raceinfo_race_menu.append( PagedOption('%s' % skillnames[x], value=None, highlight=True, selectable=False)) #raceinfo_race_menu.append(Text('o %s' % skillnames[x])) v = str(skilldesc[x]).split('+') raceinfo_race_menu.append(Text('%s' % v[0])) for y in v[1:]: raceinfo_race_menu.append(Text('%s' % y)) x += 1 raceinfo_race_menu.send(index)
"""Cut the chosen wire.""" cut_chosen_wire(option.value, PlayerEntity(index)) # ============================================================================= # >> MENU CREATION # ============================================================================= # Create the wire cut menu wire_menu = PagedMenu( description=wire_strings['Title'], select_callback=bomb_choice) # Loop through all choices of wire colors for _color in _colors: # Add the color to the menu wire_menu.append(PagedOption(wire_strings[_color], _color)) # ============================================================================= # >> HELPER FUNCTIONS # ============================================================================= def get_bomb_entity(): """Return the bomb's BaseEntity instance.""" for entity in EntityIter('planted_c4', return_types='entity'): return entity def cut_chosen_wire(chosen_wire, player): """Cut a wire to defuse or explode the bomb.""" # Get the bomb's instance bomb = get_bomb_entity()
class _SettingsDictionary(OrderedDict): """Class used to store user settings.""" def __init__(self, name, text=None): """Verify the name value and stores base attributes.""" # Is the given name a proper value for a convar? if not name.replace('_', '').replace(' ', '').isalpha(): # Raise an error raise ValueError('Given name "{0}" is not valid'.format(name)) # Set the base attributes self.name = name self.text = text # Create the instance's menu self.menu = PagedMenu(select_callback=self._chosen_item, title=name if text is None else text) # Call the super class' __init__ to initialize the OrderedDict super().__init__() def __setitem__(self, item, value): """Validate the given value and its type before setting the item.""" # Is the given value a proper type? if not isinstance(value, (_SettingsDictionary, SettingsType)): # Raise an error raise ValueError('Given value "{0}" is not valid'.format(value)) # Is the item already in the dictionary? if item in self: # Raise an error raise ValueError( 'Given item "{0}" is already registered'.format(item)) # Set the item in the dictionary super().__setitem__(item, value) # Get the new object value = self[item] # Set the item's prefix value.prefix = self.prefix if not value.prefix.endswith('_'): value.prefix += '_' # Does the section's name need added to the prefix? if not isinstance(self, PlayerSettings): # Add the section's name to the prefix value.prefix += self.name.lower().replace(' ', '_') + '_' # Add the option to the menu self.menu.append( PagedOption(value.name if value.text is None else value.text, value)) def add_int_setting(self, name, default, text=None, min_value=None, max_value=None): """Add a new integer setting to the dictionary.""" self[name] = IntegerSetting(name, default, text, min_value, max_value) return self[name] def add_bool_setting(self, name, default, text=None): """Add a new boolean setting to the dictionary.""" self[name] = BoolSetting(name, default, text) return self[name] def add_string_setting(self, name, default, text=None): """Add a new string setting to the dictionary.""" self[name] = StringSetting(name, default, text) return self[name] def add_section(self, name, text=None): """Add a new section to the dictionary.""" self[name] = _SettingsDictionary(name, text) return self[name] @staticmethod def _chosen_item(menu, index, option): """Called when an item is chosen from the instance's menu.""" # Is the chosen value another branch of settings? if isinstance(option.value, _SettingsDictionary): # Send the new menu option.value.menu.send(index) # No need to go further return # TODO: Placeholder for sending setting specific menus option.value.menu.send(index)
"""Cut the chosen wire.""" cut_chosen_wire(option.value, PlayerEntity(index)) # ============================================================================= # >> MENU CREATION # ============================================================================= # Create the wire cut menu wire_menu = PagedMenu(description=wire_strings['Title'], select_callback=bomb_choice) # Loop through all choices of wire colors for _color in _colors: # Add the color to the menu wire_menu.append(PagedOption(wire_strings[_color], _color)) # ============================================================================= # >> HELPER FUNCTIONS # ============================================================================= def get_bomb_entity(): """Return the bomb's BaseEntity instance.""" for entity in EntityIter('planted_c4', return_types='entity'): return entity def cut_chosen_wire(chosen_wire, player): """Cut a wire to defuse or explode the bomb.""" # Get the bomb's instance bomb = get_bomb_entity()