Simple tidying

This commit is contained in:
Eric Froemling 2020-04-11 21:54:27 -07:00
parent b12ac84f70
commit f0e6e2be77
6 changed files with 103 additions and 132 deletions

View File

@ -771,7 +771,10 @@ class App:
return False return False
# Ok, we're good to go. # Ok, we're good to go.
self.coop_session_args = {'campaign': campaignname, 'level': levelname} self.coop_session_args = {
'campaign': campaignname,
'level': levelname,
}
for arg_name, arg_val in list(args.items()): for arg_name, arg_val in list(args.items()):
self.coop_session_args[arg_name] = arg_val self.coop_session_args[arg_name] = arg_val
@ -782,8 +785,8 @@ class App:
except Exception: except Exception:
from ba import _error from ba import _error
_error.print_exception() _error.print_exception()
from bastd import mainmenu from bastd.mainmenu import MainMenuSession
_ba.new_host_session(mainmenu.MainMenuSession) _ba.new_host_session(MainMenuSession)
_ba.fade_screen(False, endcall=_fade_end) _ba.fade_screen(False, endcall=_fade_end)
return True return True

View File

@ -353,6 +353,7 @@ class CoopSession(Session):
if results.get_score_type() in ('seconds', 'milliseconds', if results.get_score_type() in ('seconds', 'milliseconds',
'time'): 'time'):
score_type = 'time' score_type = 'time'
# Results contains milliseconds; ScoreScreen wants # Results contains milliseconds; ScoreScreen wants
# hundredths; need to fix :-/ # hundredths; need to fix :-/
if score is not None: if score is not None:

View File

@ -289,10 +289,10 @@ class GameActivity(Activity):
@classmethod @classmethod
def supports_session_type(cls, sessiontype: Type[ba.Session]) -> bool: def supports_session_type(cls, sessiontype: Type[ba.Session]) -> bool:
"""Return whether this game supports the provided Session type.""" """Return whether this game supports the provided Session type."""
from ba import _teambasesession from ba._teambasesession import TeamBaseSession
# By default, games support any versus mode # By default, games support any versus mode
return issubclass(sessiontype, _teambasesession.TeamBaseSession) return issubclass(sessiontype, TeamBaseSession)
def __init__(self, settings: Dict[str, Any]): def __init__(self, settings: Dict[str, Any]):
"""Instantiate the Activity.""" """Instantiate the Activity."""
@ -546,6 +546,7 @@ class GameActivity(Activity):
self.end_game() self.end_game()
# FIXME: this logic should live in the session classes.
def _game_begin_analytics(self) -> None: def _game_begin_analytics(self) -> None:
"""Update analytics events for the start of the game.""" """Update analytics events for the start of the game."""
# pylint: disable=too-many-branches # pylint: disable=too-many-branches

View File

@ -60,26 +60,29 @@ def filter_playlist(playlist: PlaylistType,
unowned_game_types = set() unowned_game_types = set()
for entry in copy.deepcopy(playlist): for entry in copy.deepcopy(playlist):
# 'map' used to be called 'level' here # 'map' used to be called 'level' here.
if 'level' in entry: if 'level' in entry:
entry['map'] = entry['level'] entry['map'] = entry['level']
del entry['level'] del entry['level']
# we now stuff map into settings instead of it being its own thing
# We now stuff map into settings instead of it being its own thing.
if 'map' in entry: if 'map' in entry:
entry['settings']['map'] = entry['map'] entry['settings']['map'] = entry['map']
del entry['map'] del entry['map']
# update old map names to new ones
# Update old map names to new ones.
entry['settings']['map'] = _map.get_filtered_map_name( entry['settings']['map'] = _map.get_filtered_map_name(
entry['settings']['map']) entry['settings']['map'])
if remove_unowned and entry['settings']['map'] in unowned_maps: if remove_unowned and entry['settings']['map'] in unowned_maps:
continue continue
# ok, for each game in our list, try to import the module and grab
# Ok, for each game in our list, try to import the module and grab
# the actual game class. add successful ones to our initial list # the actual game class. add successful ones to our initial list
# to present to the user # to present to the user.
if not isinstance(entry['type'], str): if not isinstance(entry['type'], str):
raise Exception("invalid entry format") raise Exception("invalid entry format")
try: try:
# do some type filters for backwards compat. # Do some type filters for backwards compat.
if entry['type'] in ('Assault.AssaultGame', if entry['type'] in ('Assault.AssaultGame',
'Happy_Thoughts.HappyThoughtsGame', 'Happy_Thoughts.HappyThoughtsGame',
'bsAssault.AssaultGame', 'bsAssault.AssaultGame',
@ -147,7 +150,7 @@ def filter_playlist(playlist: PlaylistType,
if mark_unowned and gameclass in unowned_game_types: if mark_unowned and gameclass in unowned_game_types:
entry['is_unowned_game'] = True entry['is_unowned_game'] = True
# make sure all settings the game defines are present # Make sure all settings the game defines are present.
neededsettings = gameclass.get_settings(sessiontype) neededsettings = gameclass.get_settings(sessiontype)
for setting_name, setting in neededsettings: for setting_name, setting in neededsettings:
if (setting_name not in entry['settings'] if (setting_name not in entry['settings']
@ -164,6 +167,7 @@ def filter_playlist(playlist: PlaylistType,
def get_default_free_for_all_playlist() -> PlaylistType: def get_default_free_for_all_playlist() -> PlaylistType:
"""Return a default playlist for free-for-all mode.""" """Return a default playlist for free-for-all mode."""
# NOTE: these are currently using old type/map names, # NOTE: these are currently using old type/map names,
# but filtering translates them properly to the new ones. # but filtering translates them properly to the new ones.
# (is kinda a handy way to ensure filtering is working). # (is kinda a handy way to ensure filtering is working).
@ -177,8 +181,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Doom Shroom' 'map': 'Doom Shroom'
}, },
'type': 'bs_death_match.DeathMatchGame' 'type': 'bs_death_match.DeathMatchGame'
}, }, {
{
'settings': { 'settings': {
'Chosen One Gets Gloves': True, 'Chosen One Gets Gloves': True,
'Chosen One Gets Shield': False, 'Chosen One Gets Shield': False,
@ -189,8 +192,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Monkey Face' 'map': 'Monkey Face'
}, },
'type': 'bs_chosen_one.ChosenOneGame' 'type': 'bs_chosen_one.ChosenOneGame'
}, }, {
{
'settings': { 'settings': {
'Hold Time': 30, 'Hold Time': 30,
'Respawn Times': 1.0, 'Respawn Times': 1.0,
@ -198,15 +200,13 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Zigzag' 'map': 'Zigzag'
}, },
'type': 'bs_king_of_the_hill.KingOfTheHillGame' 'type': 'bs_king_of_the_hill.KingOfTheHillGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'map': 'Rampage' 'map': 'Rampage'
}, },
'type': 'bs_meteor_shower.MeteorShowerGame' 'type': 'bs_meteor_shower.MeteorShowerGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': 1, 'Epic Mode': 1,
'Lives Per Player': 1, 'Lives Per Player': 1,
@ -215,8 +215,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Tip Top' 'map': 'Tip Top'
}, },
'type': 'bs_elimination.EliminationGame' 'type': 'bs_elimination.EliminationGame'
}, }, {
{
'settings': { 'settings': {
'Hold Time': 30, 'Hold Time': 30,
'Respawn Times': 1.0, 'Respawn Times': 1.0,
@ -224,8 +223,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'The Pad' 'map': 'The Pad'
}, },
'type': 'bs_keep_away.KeepAwayGame' 'type': 'bs_keep_away.KeepAwayGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': True, 'Epic Mode': True,
'Kills to Win Per Player': 10, 'Kills to Win Per Player': 10,
@ -234,8 +232,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Rampage' 'map': 'Rampage'
}, },
'type': 'bs_death_match.DeathMatchGame' 'type': 'bs_death_match.DeathMatchGame'
}, }, {
{
'settings': { 'settings': {
'Bomb Spawning': 1000, 'Bomb Spawning': 1000,
'Epic Mode': False, 'Epic Mode': False,
@ -246,8 +243,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Big G' 'map': 'Big G'
}, },
'type': 'bs_race.RaceGame' 'type': 'bs_race.RaceGame'
}, }, {
{
'settings': { 'settings': {
'Hold Time': 30, 'Hold Time': 30,
'Respawn Times': 1.0, 'Respawn Times': 1.0,
@ -255,8 +251,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Happy Thoughts' 'map': 'Happy Thoughts'
}, },
'type': 'bs_king_of_the_hill.KingOfTheHillGame' 'type': 'bs_king_of_the_hill.KingOfTheHillGame'
}, }, {
{
'settings': { 'settings': {
'Enable Impact Bombs': 1, 'Enable Impact Bombs': 1,
'Enable Triple Bombs': False, 'Enable Triple Bombs': False,
@ -264,8 +259,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Doom Shroom' 'map': 'Doom Shroom'
}, },
'type': 'bs_target_practice.TargetPracticeGame' 'type': 'bs_target_practice.TargetPracticeGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Lives Per Player': 5, 'Lives Per Player': 5,
@ -274,8 +268,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Step Right Up' 'map': 'Step Right Up'
}, },
'type': 'bs_elimination.EliminationGame' 'type': 'bs_elimination.EliminationGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Kills to Win Per Player': 10, 'Kills to Win Per Player': 10,
@ -284,8 +277,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Crag Castle' 'map': 'Crag Castle'
}, },
'type': 'bs_death_match.DeathMatchGame' 'type': 'bs_death_match.DeathMatchGame'
}, }, {
{
'map': 'Lake Frigid', 'map': 'Lake Frigid',
'settings': { 'settings': {
'Bomb Spawning': 0, 'Bomb Spawning': 0,
@ -296,7 +288,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Lake Frigid' 'map': 'Lake Frigid'
}, },
'type': 'bs_race.RaceGame' 'type': 'bs_race.RaceGame'
}] # yapf: disable }]
def get_default_teams_playlist() -> PlaylistType: def get_default_teams_playlist() -> PlaylistType:
@ -317,8 +309,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Bridgit' 'map': 'Bridgit'
}, },
'type': 'bs_capture_the_flag.CTFGame' 'type': 'bs_capture_the_flag.CTFGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Respawn Times': 1.0, 'Respawn Times': 1.0,
@ -327,8 +318,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Step Right Up' 'map': 'Step Right Up'
}, },
'type': 'bs_assault.AssaultGame' 'type': 'bs_assault.AssaultGame'
}, }, {
{
'settings': { 'settings': {
'Balance Total Lives': False, 'Balance Total Lives': False,
'Epic Mode': False, 'Epic Mode': False,
@ -339,8 +329,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Rampage' 'map': 'Rampage'
}, },
'type': 'bs_elimination.EliminationGame' 'type': 'bs_elimination.EliminationGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Kills to Win Per Player': 5, 'Kills to Win Per Player': 5,
@ -349,8 +338,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Roundabout' 'map': 'Roundabout'
}, },
'type': 'bs_death_match.DeathMatchGame' 'type': 'bs_death_match.DeathMatchGame'
}, }, {
{
'settings': { 'settings': {
'Respawn Times': 1.0, 'Respawn Times': 1.0,
'Score to Win': 1, 'Score to Win': 1,
@ -358,8 +346,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Hockey Stadium' 'map': 'Hockey Stadium'
}, },
'type': 'bs_hockey.HockeyGame' 'type': 'bs_hockey.HockeyGame'
}, }, {
{
'settings': { 'settings': {
'Hold Time': 30, 'Hold Time': 30,
'Respawn Times': 1.0, 'Respawn Times': 1.0,
@ -367,8 +354,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Monkey Face' 'map': 'Monkey Face'
}, },
'type': 'bs_keep_away.KeepAwayGame' 'type': 'bs_keep_away.KeepAwayGame'
}, }, {
{
'settings': { 'settings': {
'Balance Total Lives': False, 'Balance Total Lives': False,
'Epic Mode': True, 'Epic Mode': True,
@ -379,8 +365,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Tip Top' 'map': 'Tip Top'
}, },
'type': 'bs_elimination.EliminationGame' 'type': 'bs_elimination.EliminationGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Respawn Times': 1.0, 'Respawn Times': 1.0,
@ -389,8 +374,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Crag Castle' 'map': 'Crag Castle'
}, },
'type': 'bs_assault.AssaultGame' 'type': 'bs_assault.AssaultGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Kills to Win Per Player': 5, 'Kills to Win Per Player': 5,
@ -399,15 +383,13 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Doom Shroom' 'map': 'Doom Shroom'
}, },
'type': 'bs_death_match.DeathMatchGame' 'type': 'bs_death_match.DeathMatchGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'map': 'Rampage' 'map': 'Rampage'
}, },
'type': 'bs_meteor_shower.MeteorShowerGame' 'type': 'bs_meteor_shower.MeteorShowerGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Flag Idle Return Time': 30, 'Flag Idle Return Time': 30,
@ -418,8 +400,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Roundabout' 'map': 'Roundabout'
}, },
'type': 'bs_capture_the_flag.CTFGame' 'type': 'bs_capture_the_flag.CTFGame'
}, }, {
{
'settings': { 'settings': {
'Respawn Times': 1.0, 'Respawn Times': 1.0,
'Score to Win': 21, 'Score to Win': 21,
@ -427,8 +408,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Football Stadium' 'map': 'Football Stadium'
}, },
'type': 'bs_football.FootballTeamGame' 'type': 'bs_football.FootballTeamGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': True, 'Epic Mode': True,
'Respawn Times': 0.25, 'Respawn Times': 0.25,
@ -437,8 +417,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Bridgit' 'map': 'Bridgit'
}, },
'type': 'bs_assault.AssaultGame' 'type': 'bs_assault.AssaultGame'
}, }, {
{
'map': 'Doom Shroom', 'map': 'Doom Shroom',
'settings': { 'settings': {
'Enable Impact Bombs': 1, 'Enable Impact Bombs': 1,
@ -447,8 +426,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Doom Shroom' 'map': 'Doom Shroom'
}, },
'type': 'bs_target_practice.TargetPracticeGame' 'type': 'bs_target_practice.TargetPracticeGame'
}, }, {
{
'settings': { 'settings': {
'Hold Time': 30, 'Hold Time': 30,
'Respawn Times': 1.0, 'Respawn Times': 1.0,
@ -456,8 +434,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Tip Top' 'map': 'Tip Top'
}, },
'type': 'bs_king_of_the_hill.KingOfTheHillGame' 'type': 'bs_king_of_the_hill.KingOfTheHillGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Respawn Times': 1.0, 'Respawn Times': 1.0,
@ -466,8 +443,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Zigzag' 'map': 'Zigzag'
}, },
'type': 'bs_assault.AssaultGame' 'type': 'bs_assault.AssaultGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Flag Idle Return Time': 30, 'Flag Idle Return Time': 30,
@ -478,8 +454,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Happy Thoughts' 'map': 'Happy Thoughts'
}, },
'type': 'bs_capture_the_flag.CTFGame' 'type': 'bs_capture_the_flag.CTFGame'
}, }, {
{
'settings': { 'settings': {
'Bomb Spawning': 1000, 'Bomb Spawning': 1000,
'Epic Mode': True, 'Epic Mode': True,
@ -489,8 +464,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Big G' 'map': 'Big G'
}, },
'type': 'bs_race.RaceGame' 'type': 'bs_race.RaceGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Kills to Win Per Player': 5, 'Kills to Win Per Player': 5,
@ -499,8 +473,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Monkey Face' 'map': 'Monkey Face'
}, },
'type': 'bs_death_match.DeathMatchGame' 'type': 'bs_death_match.DeathMatchGame'
}, }, {
{
'settings': { 'settings': {
'Hold Time': 30, 'Hold Time': 30,
'Respawn Times': 1.0, 'Respawn Times': 1.0,
@ -508,8 +481,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Lake Frigid' 'map': 'Lake Frigid'
}, },
'type': 'bs_keep_away.KeepAwayGame' 'type': 'bs_keep_away.KeepAwayGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': False, 'Epic Mode': False,
'Flag Idle Return Time': 30, 'Flag Idle Return Time': 30,
@ -520,8 +492,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Tip Top' 'map': 'Tip Top'
}, },
'type': 'bs_capture_the_flag.CTFGame' 'type': 'bs_capture_the_flag.CTFGame'
}, }, {
{
'settings': { 'settings': {
'Balance Total Lives': False, 'Balance Total Lives': False,
'Epic Mode': False, 'Epic Mode': False,
@ -532,8 +503,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Crag Castle' 'map': 'Crag Castle'
}, },
'type': 'bs_elimination.EliminationGame' 'type': 'bs_elimination.EliminationGame'
}, }, {
{
'settings': { 'settings': {
'Epic Mode': True, 'Epic Mode': True,
'Respawn Times': 0.25, 'Respawn Times': 0.25,
@ -541,4 +511,4 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Zigzag' 'map': 'Zigzag'
}, },
'type': 'bs_conquest.ConquestGame' 'type': 'bs_conquest.ConquestGame'
}] # yapf: disable }]

View File

@ -75,14 +75,6 @@ class Session:
""" """
# Annotate our attrs at class level so they're available for introspection.
teams: List[ba.Team]
campaign: Optional[ba.Campaign]
lobby: ba.Lobby
min_players: int
max_players: int
players: List[ba.Player]
def __init__(self, def __init__(self,
depsets: Sequence[ba.DependencySet], depsets: Sequence[ba.DependencySet],
team_names: Sequence[str] = None, team_names: Sequence[str] = None,
@ -107,26 +99,23 @@ class Session:
from ba._error import DependencyError from ba._error import DependencyError
from ba._dependency import Dependency, AssetPackage from ba._dependency import Dependency, AssetPackage
# print(' WOULD LOOK AT DEP SETS', depsets) # First off, resolve all dependency-sets we were passed.
# If things are missing, we'll try to gather them into a single
# first off, resolve all dep-sets we were passed. # missing-deps exception if possible to give the caller a clean
# if things are missing, we'll try to gather them into # path to download missing stuff and try again.
# a single missing-deps exception if possible
# to give the caller a clean path to download missing
# stuff and try again.
missing_asset_packages: Set[str] = set() missing_asset_packages: Set[str] = set()
for depset in depsets: for depset in depsets:
try: try:
depset.resolve() depset.resolve()
except DependencyError as exc: except DependencyError as exc:
# we gather/report missing assets only; barf on anything else # Gather/report missing assets only; barf on anything else.
if all(issubclass(d.cls, AssetPackage) for d in exc.deps): if all(issubclass(d.cls, AssetPackage) for d in exc.deps):
for dep in exc.deps: for dep in exc.deps:
assert isinstance(dep.config, str) assert isinstance(dep.config, str)
missing_asset_packages.add(dep.config) missing_asset_packages.add(dep.config)
else: else:
missing_info = [(d.cls, d.config) for d in exc.deps] missing_info = [(d.cls, d.config) for d in exc.deps]
raise Exception( raise RuntimeError(
f'Missing non-asset dependencies: {missing_info}') f'Missing non-asset dependencies: {missing_info}')
# Throw a combined exception if we found anything missing. # Throw a combined exception if we found anything missing.
@ -153,11 +142,11 @@ class Session:
# FIXME: This stuff shouldn't be here. # FIXME: This stuff shouldn't be here.
self.sharedobjs: Dict[str, Any] = {} self.sharedobjs: Dict[str, Any] = {}
# TeamGameActivity uses this to display a help overlay on # TeamGameActivity uses this to display a help overlay on the first
# the first activity only. # activity only.
self.have_shown_controls_help_overlay = False self.have_shown_controls_help_overlay = False
self.campaign = None self.campaign: Optional[ba.Campaign] = None
# FIXME: Should be able to kill this I think. # FIXME: Should be able to kill this I think.
self.campaign_state: Dict[str, str] = {} self.campaign_state: Dict[str, str] = {}
@ -167,8 +156,8 @@ class Session:
self._in_set_activity = False self._in_set_activity = False
self._allow_mid_activity_joins = allow_mid_activity_joins self._allow_mid_activity_joins = allow_mid_activity_joins
self.teams = [] self.teams: List[ba.Team] = []
self.players = [] self.players: List[ba.Player] = []
self._next_team_id = 0 self._next_team_id = 0
self._activity_retained: Optional[ba.Activity] = None self._activity_retained: Optional[ba.Activity] = None
self.launch_end_session_activity_time: Optional[float] = None self.launch_end_session_activity_time: Optional[float] = None
@ -180,9 +169,8 @@ class Session:
self._activity_weak: ReferenceType[ba.Activity] self._activity_weak: ReferenceType[ba.Activity]
self._activity_weak = weakref.ref(_EmptyObj()) # type: ignore self._activity_weak = weakref.ref(_EmptyObj()) # type: ignore
if self._activity_weak() is not None: if self._activity_weak() is not None:
raise Exception("error creating empty weak ref") raise Exception("Error creating empty activity weak ref.")
self._next_activity: Optional[ba.Activity] = None self._next_activity: Optional[ba.Activity] = None
self.wants_to_end = False self.wants_to_end = False
@ -190,6 +178,7 @@ class Session:
self.min_players = min_players self.min_players = min_players
self.max_players = max_players self.max_players = max_players
# Create Teams.
if self._use_teams: if self._use_teams:
assert team_names is not None assert team_names is not None
assert team_colors is not None assert team_colors is not None
@ -206,10 +195,10 @@ class Session:
self.on_team_join(team) self.on_team_join(team)
except Exception: except Exception:
from ba import _error from ba import _error
_error.print_exception('exception in on_team_join for', _error.print_exception(
self) f'Error in on_team_join for {self}.')
self.lobby = Lobby() self.lobby: ba.Lobby = Lobby()
self.stats = Stats() self.stats = Stats()
# Instantiate our session globals node # Instantiate our session globals node
@ -238,8 +227,8 @@ class Session:
if len(self.players) >= self.max_players: if len(self.players) >= self.max_players:
# Print a rejection message *only* to the client trying to join # Print a rejection message *only* to the client trying to
# (prevents spamming everyone else in the game). # join (prevents spamming everyone else in the game).
_ba.playsound(_ba.getsound('error')) _ba.playsound(_ba.getsound('error'))
_ba.screenmessage( _ba.screenmessage(
Lstr(resource='playerLimitReachedText', Lstr(resource='playerLimitReachedText',
@ -287,7 +276,7 @@ class Session:
_error.print_exception( _error.print_exception(
'Error in Lobby.remove_chooser()') 'Error in Lobby.remove_chooser()')
# *if* he was actually in the game, announce his departure # *If* they were actually in the game, announce their departure.
if team is not None: if team is not None:
_ba.screenmessage( _ba.screenmessage(
Lstr(resource='playerLeftText', Lstr(resource='playerLeftText',
@ -298,7 +287,7 @@ class Session:
# team lists every activity) # team lists every activity)
if team is not None and player in team.players: if team is not None and player in team.players:
# Testing.. can remove this eventually. # Testing; can remove this eventually.
if isinstance(self, FreeForAllSession): if isinstance(self, FreeForAllSession):
if len(team.players) != 1: if len(team.players) != 1:
_error.print_error("expected 1 player in FFA team") _error.print_error("expected 1 player in FFA team")
@ -324,7 +313,7 @@ class Session:
player.set_activity(None) player.set_activity(None)
player.set_node(None) player.set_node(None)
# reset the player - this will remove its actor-ref and clear # Reset the player; this will remove its actor-ref and clear
# its calls/etc # its calls/etc
try: try:
with _ba.Context(activity): with _ba.Context(activity):
@ -373,6 +362,7 @@ class Session:
except Exception: except Exception:
_error.print_exception( _error.print_exception(
'exception in on_team_leave for session', self) 'exception in on_team_leave for session', self)
# Clear the team's session-data (so dying stuff will # Clear the team's session-data (so dying stuff will
# have proper context). # have proper context).
try: try:
@ -450,20 +440,22 @@ class Session:
""" """
from ba._general import Call from ba._general import Call
from ba._enums import TimeType from ba._enums import TimeType
# only pay attention if this is coming from our current activity..
# Only pay attention if this is coming from our current activity.
if activity is not self._activity_retained: if activity is not self._activity_retained:
return return
# if this activity hasn't begun yet, just set it up to end immediately # If this activity hasn't begun yet, just set it up to end immediately
# once it does # once it does.
if not activity.has_begun(): if not activity.has_begun():
activity.set_immediate_end(results, delay, force) activity.set_immediate_end(results, delay, force)
# the activity has already begun; get ready to end it.. # The activity has already begun; get ready to end it.
else: else:
if (not activity.has_ended()) or force: if (not activity.has_ended()) or force:
activity.set_has_ended(True) activity.set_has_ended(True)
# set a timer to set in motion this activity's demise
# Set a timer to set in motion this activity's demise.
self._activity_end_timer = _ba.Timer( self._activity_end_timer = _ba.Timer(
delay, delay,
Call(self._complete_end_activity, activity, results), Call(self._complete_end_activity, activity, results),
@ -479,8 +471,8 @@ class Session:
return None return None
if isinstance(msg, PlayerProfilesChangedMessage): if isinstance(msg, PlayerProfilesChangedMessage):
# if we have a current activity with a lobby, ask it to # If we have a current activity with a lobby, ask it to reload
# reload profiles # profiles.
with _ba.Context(self): with _ba.Context(self):
self.lobby.reload_profiles() self.lobby.reload_profiles()
return None return None
@ -507,7 +499,7 @@ class Session:
"Session.set_activity() cannot be called recursively.") "Session.set_activity() cannot be called recursively.")
if activity.session is not _ba.getsession(): if activity.session is not _ba.getsession():
raise Exception("provided activity's session is not current") raise Exception("Provided Activity's Session is not current.")
# Quietly ignore this if the whole session is going down. # Quietly ignore this if the whole session is going down.
if self._ending: if self._ending:
@ -570,7 +562,7 @@ class Session:
prev_activity._transitioning_out = True prev_activity._transitioning_out = True
# pylint: enable=protected-access # pylint: enable=protected-access
# activity will be None until the next one begins. # Activity will be None until the next one begins.
with _ba.Context(prev_activity): with _ba.Context(prev_activity):
prev_activity.on_transition_out() prev_activity.on_transition_out()
@ -609,6 +601,7 @@ class Session:
_ba.timer(activity.transition_time, _ba.timer(activity.transition_time,
prev_activity._destroy, prev_activity._destroy,
timetype=TimeType.REAL) timetype=TimeType.REAL)
# Just run immediately. # Just run immediately.
else: else:
# noinspection PyProtectedMember # noinspection PyProtectedMember
@ -716,6 +709,7 @@ class Session:
_ba.playsound(_ba.getsound('error')) _ba.playsound(_ba.getsound('error'))
else: else:
return return
# Otherwise just add players on the fly. # Otherwise just add players on the fly.
else: else:
self._add_chosen_player(chooser) self._add_chosen_player(chooser)

View File

@ -101,6 +101,7 @@ class TeamBaseSession(Session):
if (self._playlist_name != '__default__' if (self._playlist_name != '__default__'
and self._playlist_name in playlists): and self._playlist_name in playlists):
# Make sure to copy this, as we muck with it in place once we've # Make sure to copy this, as we muck with it in place once we've
# got it and we don't want that to affect our config. # got it and we don't want that to affect our config.
playlist = copy.deepcopy(playlists[self._playlist_name]) playlist = copy.deepcopy(playlists[self._playlist_name])
@ -177,22 +178,21 @@ class TeamBaseSession(Session):
TeamSeriesVictoryScoreScreenActivity) TeamSeriesVictoryScoreScreenActivity)
from ba import _activitytypes from ba import _activitytypes
# If we have a tutorial to show, # If we have a tutorial to show, that's the first thing we do no
# that's the first thing we do no matter what. # matter what.
if self._tutorial_activity_instance is not None: if self._tutorial_activity_instance is not None:
self.set_activity(self._tutorial_activity_instance) self.set_activity(self._tutorial_activity_instance)
self._tutorial_activity_instance = None self._tutorial_activity_instance = None
# If we're leaving the tutorial activity, # If we're leaving the tutorial activity, pop a transition activity
# pop a transition activity to transition # to transition us into a round gracefully (otherwise we'd snap from
# us into a round gracefully (otherwise we'd # one terrain to another instantly).
# snap from one terrain to another instantly).
elif isinstance(activity, TutorialActivity): elif isinstance(activity, TutorialActivity):
self.set_activity( self.set_activity(
_ba.new_activity(_activitytypes.TransitionActivity)) _ba.new_activity(_activitytypes.TransitionActivity))
# If we're in a between-round activity or a restart-activity, # If we're in a between-round activity or a restart-activity, hop
# hop into a round. # into a round.
elif isinstance( elif isinstance(
activity, activity,
(_activitytypes.JoiningActivity, _activitytypes.TransitionActivity, (_activitytypes.JoiningActivity, _activitytypes.TransitionActivity,
@ -204,6 +204,7 @@ class TeamBaseSession(Session):
self._game_number = 0 self._game_number = 0
for team in self.teams: for team in self.teams:
team.sessiondata['score'] = 0 team.sessiondata['score'] = 0
# Otherwise just set accum (per-game) scores. # Otherwise just set accum (per-game) scores.
else: else:
self.stats.reset_accum() self.stats.reset_accum()
@ -217,7 +218,7 @@ class TeamBaseSession(Session):
# Instantiate the next now so they have plenty of time to load. # Instantiate the next now so they have plenty of time to load.
self._instantiate_next_game() self._instantiate_next_game()
# (re)register all players and wire stats to our next activity # (Re)register all players and wire stats to our next activity.
for player in self.players: for player in self.players:
# ..but only ones who have been placed on a team # ..but only ones who have been placed on a team
# (ie: no longer sitting in the lobby). # (ie: no longer sitting in the lobby).
@ -322,6 +323,7 @@ class ShuffleList:
continue continue
if test_obj['type'] == self.last_gotten['type']: if test_obj['type'] == self.last_gotten['type']:
continue continue
# Sufficiently different; lets go with it. # Sufficiently different; lets go with it.
break break