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
# 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()):
self.coop_session_args[arg_name] = arg_val
@ -782,8 +785,8 @@ class App:
except Exception:
from ba import _error
_error.print_exception()
from bastd import mainmenu
_ba.new_host_session(mainmenu.MainMenuSession)
from bastd.mainmenu import MainMenuSession
_ba.new_host_session(MainMenuSession)
_ba.fade_screen(False, endcall=_fade_end)
return True

View File

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

View File

@ -289,10 +289,10 @@ class GameActivity(Activity):
@classmethod
def supports_session_type(cls, sessiontype: Type[ba.Session]) -> bool:
"""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
return issubclass(sessiontype, _teambasesession.TeamBaseSession)
return issubclass(sessiontype, TeamBaseSession)
def __init__(self, settings: Dict[str, Any]):
"""Instantiate the Activity."""
@ -546,6 +546,7 @@ class GameActivity(Activity):
self.end_game()
# FIXME: this logic should live in the session classes.
def _game_begin_analytics(self) -> None:
"""Update analytics events for the start of the game."""
# pylint: disable=too-many-branches

View File

@ -60,26 +60,29 @@ def filter_playlist(playlist: PlaylistType,
unowned_game_types = set()
for entry in copy.deepcopy(playlist):
# 'map' used to be called 'level' here
# 'map' used to be called 'level' here.
if 'level' in entry:
entry['map'] = 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:
entry['settings']['map'] = 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'])
if remove_unowned and entry['settings']['map'] in unowned_maps:
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
# to present to the user
# to present to the user.
if not isinstance(entry['type'], str):
raise Exception("invalid entry format")
try:
# do some type filters for backwards compat.
# Do some type filters for backwards compat.
if entry['type'] in ('Assault.AssaultGame',
'Happy_Thoughts.HappyThoughtsGame',
'bsAssault.AssaultGame',
@ -147,7 +150,7 @@ def filter_playlist(playlist: PlaylistType,
if mark_unowned and gameclass in unowned_game_types:
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)
for setting_name, setting in neededsettings:
if (setting_name not in entry['settings']
@ -164,6 +167,7 @@ def filter_playlist(playlist: PlaylistType,
def get_default_free_for_all_playlist() -> PlaylistType:
"""Return a default playlist for free-for-all mode."""
# NOTE: these are currently using old type/map names,
# but filtering translates them properly to the new ones.
# (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'
},
'type': 'bs_death_match.DeathMatchGame'
},
{
}, {
'settings': {
'Chosen One Gets Gloves': True,
'Chosen One Gets Shield': False,
@ -189,8 +192,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Monkey Face'
},
'type': 'bs_chosen_one.ChosenOneGame'
},
{
}, {
'settings': {
'Hold Time': 30,
'Respawn Times': 1.0,
@ -198,15 +200,13 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Zigzag'
},
'type': 'bs_king_of_the_hill.KingOfTheHillGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'map': 'Rampage'
},
'type': 'bs_meteor_shower.MeteorShowerGame'
},
{
}, {
'settings': {
'Epic Mode': 1,
'Lives Per Player': 1,
@ -215,8 +215,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Tip Top'
},
'type': 'bs_elimination.EliminationGame'
},
{
}, {
'settings': {
'Hold Time': 30,
'Respawn Times': 1.0,
@ -224,8 +223,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'The Pad'
},
'type': 'bs_keep_away.KeepAwayGame'
},
{
}, {
'settings': {
'Epic Mode': True,
'Kills to Win Per Player': 10,
@ -234,8 +232,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Rampage'
},
'type': 'bs_death_match.DeathMatchGame'
},
{
}, {
'settings': {
'Bomb Spawning': 1000,
'Epic Mode': False,
@ -246,8 +243,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Big G'
},
'type': 'bs_race.RaceGame'
},
{
}, {
'settings': {
'Hold Time': 30,
'Respawn Times': 1.0,
@ -255,8 +251,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Happy Thoughts'
},
'type': 'bs_king_of_the_hill.KingOfTheHillGame'
},
{
}, {
'settings': {
'Enable Impact Bombs': 1,
'Enable Triple Bombs': False,
@ -264,8 +259,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Doom Shroom'
},
'type': 'bs_target_practice.TargetPracticeGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Lives Per Player': 5,
@ -274,8 +268,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Step Right Up'
},
'type': 'bs_elimination.EliminationGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Kills to Win Per Player': 10,
@ -284,8 +277,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Crag Castle'
},
'type': 'bs_death_match.DeathMatchGame'
},
{
}, {
'map': 'Lake Frigid',
'settings': {
'Bomb Spawning': 0,
@ -296,7 +288,7 @@ def get_default_free_for_all_playlist() -> PlaylistType:
'map': 'Lake Frigid'
},
'type': 'bs_race.RaceGame'
}] # yapf: disable
}]
def get_default_teams_playlist() -> PlaylistType:
@ -317,8 +309,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Bridgit'
},
'type': 'bs_capture_the_flag.CTFGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Respawn Times': 1.0,
@ -327,8 +318,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Step Right Up'
},
'type': 'bs_assault.AssaultGame'
},
{
}, {
'settings': {
'Balance Total Lives': False,
'Epic Mode': False,
@ -339,8 +329,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Rampage'
},
'type': 'bs_elimination.EliminationGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Kills to Win Per Player': 5,
@ -349,8 +338,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Roundabout'
},
'type': 'bs_death_match.DeathMatchGame'
},
{
}, {
'settings': {
'Respawn Times': 1.0,
'Score to Win': 1,
@ -358,8 +346,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Hockey Stadium'
},
'type': 'bs_hockey.HockeyGame'
},
{
}, {
'settings': {
'Hold Time': 30,
'Respawn Times': 1.0,
@ -367,8 +354,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Monkey Face'
},
'type': 'bs_keep_away.KeepAwayGame'
},
{
}, {
'settings': {
'Balance Total Lives': False,
'Epic Mode': True,
@ -379,8 +365,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Tip Top'
},
'type': 'bs_elimination.EliminationGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Respawn Times': 1.0,
@ -389,8 +374,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Crag Castle'
},
'type': 'bs_assault.AssaultGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Kills to Win Per Player': 5,
@ -399,15 +383,13 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Doom Shroom'
},
'type': 'bs_death_match.DeathMatchGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'map': 'Rampage'
},
'type': 'bs_meteor_shower.MeteorShowerGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Flag Idle Return Time': 30,
@ -418,8 +400,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Roundabout'
},
'type': 'bs_capture_the_flag.CTFGame'
},
{
}, {
'settings': {
'Respawn Times': 1.0,
'Score to Win': 21,
@ -427,8 +408,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Football Stadium'
},
'type': 'bs_football.FootballTeamGame'
},
{
}, {
'settings': {
'Epic Mode': True,
'Respawn Times': 0.25,
@ -437,8 +417,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Bridgit'
},
'type': 'bs_assault.AssaultGame'
},
{
}, {
'map': 'Doom Shroom',
'settings': {
'Enable Impact Bombs': 1,
@ -447,8 +426,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Doom Shroom'
},
'type': 'bs_target_practice.TargetPracticeGame'
},
{
}, {
'settings': {
'Hold Time': 30,
'Respawn Times': 1.0,
@ -456,8 +434,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Tip Top'
},
'type': 'bs_king_of_the_hill.KingOfTheHillGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Respawn Times': 1.0,
@ -466,8 +443,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Zigzag'
},
'type': 'bs_assault.AssaultGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Flag Idle Return Time': 30,
@ -478,8 +454,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Happy Thoughts'
},
'type': 'bs_capture_the_flag.CTFGame'
},
{
}, {
'settings': {
'Bomb Spawning': 1000,
'Epic Mode': True,
@ -489,8 +464,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Big G'
},
'type': 'bs_race.RaceGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Kills to Win Per Player': 5,
@ -499,8 +473,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Monkey Face'
},
'type': 'bs_death_match.DeathMatchGame'
},
{
}, {
'settings': {
'Hold Time': 30,
'Respawn Times': 1.0,
@ -508,8 +481,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Lake Frigid'
},
'type': 'bs_keep_away.KeepAwayGame'
},
{
}, {
'settings': {
'Epic Mode': False,
'Flag Idle Return Time': 30,
@ -520,8 +492,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Tip Top'
},
'type': 'bs_capture_the_flag.CTFGame'
},
{
}, {
'settings': {
'Balance Total Lives': False,
'Epic Mode': False,
@ -532,8 +503,7 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Crag Castle'
},
'type': 'bs_elimination.EliminationGame'
},
{
}, {
'settings': {
'Epic Mode': True,
'Respawn Times': 0.25,
@ -541,4 +511,4 @@ def get_default_teams_playlist() -> PlaylistType:
'map': 'Zigzag'
},
'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,
depsets: Sequence[ba.DependencySet],
team_names: Sequence[str] = None,
@ -107,26 +99,23 @@ class Session:
from ba._error import DependencyError
from ba._dependency import Dependency, AssetPackage
# print(' WOULD LOOK AT DEP SETS', depsets)
# first off, resolve all dep-sets we were passed.
# if things are missing, we'll try to gather them into
# a single missing-deps exception if possible
# to give the caller a clean path to download missing
# stuff and try again.
# First off, resolve all dependency-sets we were passed.
# If things are missing, we'll try to gather them into 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()
for depset in depsets:
try:
depset.resolve()
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):
for dep in exc.deps:
assert isinstance(dep.config, str)
missing_asset_packages.add(dep.config)
else:
missing_info = [(d.cls, d.config) for d in exc.deps]
raise Exception(
raise RuntimeError(
f'Missing non-asset dependencies: {missing_info}')
# Throw a combined exception if we found anything missing.
@ -153,11 +142,11 @@ class Session:
# FIXME: This stuff shouldn't be here.
self.sharedobjs: Dict[str, Any] = {}
# TeamGameActivity uses this to display a help overlay on
# the first activity only.
# TeamGameActivity uses this to display a help overlay on the first
# activity only.
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.
self.campaign_state: Dict[str, str] = {}
@ -167,8 +156,8 @@ class Session:
self._in_set_activity = False
self._allow_mid_activity_joins = allow_mid_activity_joins
self.teams = []
self.players = []
self.teams: List[ba.Team] = []
self.players: List[ba.Player] = []
self._next_team_id = 0
self._activity_retained: Optional[ba.Activity] = 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 = weakref.ref(_EmptyObj()) # type: ignore
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.wants_to_end = False
@ -190,6 +178,7 @@ class Session:
self.min_players = min_players
self.max_players = max_players
# Create Teams.
if self._use_teams:
assert team_names is not None
assert team_colors is not None
@ -206,10 +195,10 @@ class Session:
self.on_team_join(team)
except Exception:
from ba import _error
_error.print_exception('exception in on_team_join for',
self)
_error.print_exception(
f'Error in on_team_join for {self}.')
self.lobby = Lobby()
self.lobby: ba.Lobby = Lobby()
self.stats = Stats()
# Instantiate our session globals node
@ -238,8 +227,8 @@ class Session:
if len(self.players) >= self.max_players:
# Print a rejection message *only* to the client trying to join
# (prevents spamming everyone else in the game).
# Print a rejection message *only* to the client trying to
# join (prevents spamming everyone else in the game).
_ba.playsound(_ba.getsound('error'))
_ba.screenmessage(
Lstr(resource='playerLimitReachedText',
@ -287,7 +276,7 @@ class Session:
_error.print_exception(
'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:
_ba.screenmessage(
Lstr(resource='playerLeftText',
@ -298,7 +287,7 @@ class Session:
# team lists every activity)
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 len(team.players) != 1:
_error.print_error("expected 1 player in FFA team")
@ -324,7 +313,7 @@ class Session:
player.set_activity(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
try:
with _ba.Context(activity):
@ -373,6 +362,7 @@ class Session:
except Exception:
_error.print_exception(
'exception in on_team_leave for session', self)
# Clear the team's session-data (so dying stuff will
# have proper context).
try:
@ -450,20 +440,22 @@ class Session:
"""
from ba._general import Call
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:
return
# if this activity hasn't begun yet, just set it up to end immediately
# once it does
# If this activity hasn't begun yet, just set it up to end immediately
# once it does.
if not activity.has_begun():
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:
if (not activity.has_ended()) or force:
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(
delay,
Call(self._complete_end_activity, activity, results),
@ -479,8 +471,8 @@ class Session:
return None
if isinstance(msg, PlayerProfilesChangedMessage):
# if we have a current activity with a lobby, ask it to
# reload profiles
# If we have a current activity with a lobby, ask it to reload
# profiles.
with _ba.Context(self):
self.lobby.reload_profiles()
return None
@ -507,7 +499,7 @@ class Session:
"Session.set_activity() cannot be called recursively.")
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.
if self._ending:
@ -570,7 +562,7 @@ class Session:
prev_activity._transitioning_out = True
# 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):
prev_activity.on_transition_out()
@ -609,6 +601,7 @@ class Session:
_ba.timer(activity.transition_time,
prev_activity._destroy,
timetype=TimeType.REAL)
# Just run immediately.
else:
# noinspection PyProtectedMember
@ -716,6 +709,7 @@ class Session:
_ba.playsound(_ba.getsound('error'))
else:
return
# Otherwise just add players on the fly.
else:
self._add_chosen_player(chooser)

View File

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