[ci] auto-format

This commit is contained in:
brostosjoined 2024-01-24 11:26:19 +00:00 committed by github-actions[bot]
parent da505cd56b
commit 36673fc368
8 changed files with 1204 additions and 1124 deletions

View file

@ -4,8 +4,8 @@
"""Egg game and support classes.""" """Egg game and support classes."""
# The Egg Game - throw egg as far as you can # The Egg Game - throw egg as far as you can
# created in BCS (Bombsquad Consultancy Service) - opensource bombsquad mods for all # created in BCS (Bombsquad Consultancy Service) - opensource bombsquad mods for all
# discord.gg/ucyaesh join now and give your contribution # discord.gg/ucyaesh join now and give your contribution
# The Egg game by mr.smoothy # The Egg game by mr.smoothy
# ba_meta require api 8 # ba_meta require api 8
# (see https://ballistica.net/wiki/meta-tag-system) # (see https://ballistica.net/wiki/meta-tag-system)
@ -45,14 +45,14 @@ class Puck(bs.Actor):
# Spawn just above the provided point. # Spawn just above the provided point.
self._spawn_pos = (position[0], position[1] + 1.0, position[2]) self._spawn_pos = (position[0], position[1] + 1.0, position[2])
self.last_players_to_touch =None self.last_players_to_touch = None
self.scored = False self.scored = False
self.egg_mesh = bs.getmesh('egg') self.egg_mesh = bs.getmesh('egg')
self.egg_tex_1 = bs.gettexture('eggTex1') self.egg_tex_1 = bs.gettexture('eggTex1')
self.egg_tex_2 = bs.gettexture('eggTex2') self.egg_tex_2 = bs.gettexture('eggTex2')
self.egg_tex_3 = bs.gettexture('eggTex3') self.egg_tex_3 = bs.gettexture('eggTex3')
self.eggtx=[self.egg_tex_1,self.egg_tex_2,self.egg_tex_3] self.eggtx = [self.egg_tex_1, self.egg_tex_2, self.egg_tex_3]
regg=random.randrange(0,3) regg = random.randrange(0, 3)
assert activity is not None assert activity is not None
assert isinstance(activity, EggGame) assert isinstance(activity, EggGame)
pmats = [shared.object_material, activity.puck_material] pmats = [shared.object_material, activity.puck_material]
@ -65,7 +65,7 @@ class Puck(bs.Actor):
'reflection': 'soft', 'reflection': 'soft',
'reflection_scale': [0.2], 'reflection_scale': [0.2],
'shadow_size': 0.5, 'shadow_size': 0.5,
'body_scale':0.7, 'body_scale': 0.7,
'is_area_of_interest': True, 'is_area_of_interest': True,
'position': self._spawn_pos, 'position': self._spawn_pos,
'materials': pmats 'materials': pmats
@ -180,14 +180,14 @@ class EggGame(bs.TeamGameActivity[Player, Team]):
self.puck_scored_tex = bs.gettexture('landMineLit') self.puck_scored_tex = bs.gettexture('landMineLit')
self._puck_sound = bui.getsound('metalHit') self._puck_sound = bui.getsound('metalHit')
self.puck_material = bs.Material() self.puck_material = bs.Material()
self._fake_wall_material=bs.Material() self._fake_wall_material = bs.Material()
self.HIGHEST=0 self.HIGHEST = 0
self._fake_wall_material.add_actions( self._fake_wall_material.add_actions(
conditions=('they_have_material', shared.player_material), conditions=('they_have_material', shared.player_material),
actions=( actions=(
('modify_part_collision', 'collide', True), ('modify_part_collision', 'collide', True),
('modify_part_collision', 'physical', True) ('modify_part_collision', 'physical', True)
)) ))
self.puck_material.add_actions(actions=(('modify_part_collision', self.puck_material.add_actions(actions=(('modify_part_collision',
'friction', 0.5))) 'friction', 0.5)))
@ -232,8 +232,8 @@ class EggGame(bs.TeamGameActivity[Player, Team]):
actions=(('modify_part_collision', 'collide', actions=(('modify_part_collision', 'collide',
True), ('modify_part_collision', 'physical', False), True), ('modify_part_collision', 'physical', False),
('call', 'at_connect', self._handle_score))) ('call', 'at_connect', self._handle_score)))
self.main_ground_material= bs.Material() self.main_ground_material = bs.Material()
self.main_ground_material.add_actions( self.main_ground_material.add_actions(
conditions=('they_have_material', self.puck_material), conditions=('they_have_material', self.puck_material),
actions=(('modify_part_collision', 'collide', actions=(('modify_part_collision', 'collide',
@ -243,7 +243,7 @@ class EggGame(bs.TeamGameActivity[Player, Team]):
self._puck_spawn_pos: Optional[Sequence[float]] = None self._puck_spawn_pos: Optional[Sequence[float]] = None
self._score_regions: Optional[List[bs.NodeActor]] = None self._score_regions: Optional[List[bs.NodeActor]] = None
self._puck: Optional[Puck] = None self._puck: Optional[Puck] = None
self._pucks=[] self._pucks = []
self._score_to_win = int(settings['Score to Win']) self._score_to_win = int(settings['Score to Win'])
self._time_limit = float(settings['Time Limit']) self._time_limit = float(settings['Time Limit'])
@ -255,8 +255,8 @@ class EggGame(bs.TeamGameActivity[Player, Team]):
def on_begin(self) -> None: def on_begin(self) -> None:
super().on_begin() super().on_begin()
if self._time_limit==0.0: if self._time_limit == 0.0:
self._time_limit=60 self._time_limit = 60
self.setup_standard_time_limit(self._time_limit) self.setup_standard_time_limit(self._time_limit)
# self.setup_standard_powerup_drops() # self.setup_standard_powerup_drops()
self._puck_spawn_pos = self.map.get_flag_position(None) self._puck_spawn_pos = self.map.get_flag_position(None)
@ -269,10 +269,10 @@ class EggGame(bs.TeamGameActivity[Player, Team]):
# Set up the two score regions. # Set up the two score regions.
defs = self.map.defs defs = self.map.defs
self._score_regions = [] self._score_regions = []
pos=(11.88630542755127, 0.3009839951992035, 1.33331298828125) pos = (11.88630542755127, 0.3009839951992035, 1.33331298828125)
# mat=bs.Material() # mat=bs.Material()
# mat.add_actions( # mat.add_actions(
# actions=( ('modify_part_collision','physical',True), # actions=( ('modify_part_collision','physical',True),
# ('modify_part_collision','collide',True)) # ('modify_part_collision','collide',True))
# ) # )
@ -299,13 +299,14 @@ class EggGame(bs.TeamGameActivity[Player, Team]):
bs.NodeActor( bs.NodeActor(
bs.newnode('region', bs.newnode('region',
attrs={ attrs={
'position': (-9.21,defs.boxes['goal2'][0:3][1],defs.boxes['goal2'][0:3][2]), 'position': (-9.21, defs.boxes['goal2'][0:3][1], defs.boxes['goal2'][0:3][2]),
'scale': defs.boxes['goal2'][6:9], 'scale': defs.boxes['goal2'][6:9],
'type': 'box', 'type': 'box',
'materials': (self._fake_wall_material, ) 'materials': (self._fake_wall_material, )
}))) })))
pos=(0,0.1,-5) pos = (0, 0.1, -5)
self.main_ground=bs.newnode('region',attrs={'position': pos,'scale': (25,0.001,22),'type': 'box','materials': [self.main_ground_material]}) self.main_ground = bs.newnode('region', attrs={'position': pos, 'scale': (
25, 0.001, 22), 'type': 'box', 'materials': [self.main_ground_material]})
self._update_scoreboard() self._update_scoreboard()
self._chant_sound.play() self._chant_sound.play()
@ -326,63 +327,63 @@ class EggGame(bs.TeamGameActivity[Player, Team]):
def _kill_puck(self) -> None: def _kill_puck(self) -> None:
self._puck = None self._puck = None
def _handle_egg_collision(self) -> None: def _handle_egg_collision(self) -> None:
no=bs.getcollision().opposingnode no = bs.getcollision().opposingnode
pos=no.position pos = no.position
egg=no.getdelegate(Puck) egg = no.getdelegate(Puck)
source_player=egg.last_players_to_touch source_player = egg.last_players_to_touch
if source_player==None or pos[0]< -8 or not source_player.node.exists() : if source_player == None or pos[0] < -8 or not source_player.node.exists():
return return
try: try:
col=source_player.team.color col = source_player.team.color
self.flagg=Flag(pos,touchable=False,color=col).autoretain() self.flagg = Flag(pos, touchable=False, color=col).autoretain()
self.flagg.is_area_of_interest=True self.flagg.is_area_of_interest = True
player_pos=source_player.node.position player_pos = source_player.node.position
distance = math.sqrt( pow(player_pos[0]-pos[0],2) + pow(player_pos[2]-pos[2],2)) distance = math.sqrt(pow(player_pos[0]-pos[0], 2) + pow(player_pos[2]-pos[2], 2))
dis_mark = bs.newnode('text',
dis_mark=bs.newnode('text',
attrs={
attrs={ 'text': str(round(distance, 2))+"m",
'text':str(round(distance,2))+"m", 'in_world': True,
'in_world':True, 'scale': 0.02,
'scale':0.02, 'h_align': 'center',
'h_align':'center', 'position': (pos[0], 1.6, pos[2]),
'position':(pos[0],1.6,pos[2]), 'color': col
'color':col })
}) bs.animate(dis_mark, 'scale', {
bs.animate(dis_mark,'scale',{ 0.0: 0, 0.5: 0.01
0.0:0, 0.5:0.01
}) })
if distance > self.HIGHEST: if distance > self.HIGHEST:
self.HIGHEST=distance self.HIGHEST = distance
self.stats.player_scored( self.stats.player_scored(
source_player, source_player,
10, 10,
big_message=False) big_message=False)
no.delete() no.delete()
bs.timer(2,self._spawn_puck) bs.timer(2, self._spawn_puck)
source_player.team.score=int(distance) source_player.team.score = int(distance)
except(): except ():
pass pass
def spawn_player(self, player: Player) -> bs.Actor: def spawn_player(self, player: Player) -> bs.Actor:
zoo = random.randrange(-4, 5)
zoo=random.randrange(-4,5) pos = (-11.204887390136719, 0.2998693287372589, zoo)
pos=(-11.204887390136719, 0.2998693287372589, zoo)
spaz = self.spawn_player_spaz( spaz = self.spawn_player_spaz(
player, position=pos, angle=90 ) player, position=pos, angle=90)
assert spaz.node assert spaz.node
# Prevent controlling of characters before the start of the race. # Prevent controlling of characters before the start of the race.
return spaz return spaz
def _handle_score(self) -> None: def _handle_score(self) -> None:
"""A point has been scored.""" """A point has been scored."""
@ -481,11 +482,12 @@ class EggGame(bs.TeamGameActivity[Player, Team]):
# bs.animate(light, 'intensity', {0.0: 0, 0.25: 1, 0.5: 0}, loop=True) # bs.animate(light, 'intensity', {0.0: 0, 0.25: 1, 0.5: 0}, loop=True)
# bs.timer(1.0, light.delete) # bs.timer(1.0, light.delete)
pass pass
def _spawn_puck(self) -> None: def _spawn_puck(self) -> None:
# self._swipsound.play() # self._swipsound.play()
# self._whistle_sound.play() # self._whistle_sound.play()
self._flash_puck_spawn() self._flash_puck_spawn()
assert self._puck_spawn_pos is not None assert self._puck_spawn_pos is not None
zoo=random.randrange(-5,6) zoo = random.randrange(-5, 6)
pos=(-11.204887390136719, 0.2998693287372589, zoo) pos = (-11.204887390136719, 0.2998693287372589, zoo)
self._pucks.append (Puck(position=pos)) self._pucks.append(Puck(position=pos))

View file

@ -425,12 +425,12 @@ class NewBomb(Bomb):
self._exploded = True self._exploded = True
if self.node: if self.node:
blast = NewBlast(position=self.node.position, blast = NewBlast(position=self.node.position,
velocity=self.node.velocity, velocity=self.node.velocity,
blast_radius=self.blast_radius, blast_radius=self.blast_radius,
blast_type=self.bomb_type, blast_type=self.bomb_type,
source_player=babase.existing(self._source_player), source_player=babase.existing(self._source_player),
hit_type=self.hit_type, hit_type=self.hit_type,
hit_subtype=self.hit_subtype).autoretain() hit_subtype=self.hit_subtype).autoretain()
for callback in self._explode_callbacks: for callback in self._explode_callbacks:
callback(self, blast) callback(self, blast)
@ -458,7 +458,7 @@ class TNT(bs.Actor):
self._collide_material.add_actions( self._collide_material.add_actions(
actions=('modify_part_collision', 'collide', True), actions=('modify_part_collision', 'collide', True),
) )
if teleport: if teleport:
collide = self._collide_material collide = self._collide_material
else: else:
@ -649,7 +649,7 @@ class RaceGame(bs.TeamGameActivity[Player, Team]):
('modify_part_collision', 'physical', False), ('modify_part_collision', 'physical', False),
('call', 'at_connect', ('call', 'at_connect',
self._handle_race_point_collide), self._handle_race_point_collide),
)) ))
for rpt in pts: for rpt in pts:
self._regions.append(RaceRegion(rpt, len(self._regions))) self._regions.append(RaceRegion(rpt, len(self._regions)))
@ -685,18 +685,18 @@ class RaceGame(bs.TeamGameActivity[Player, Team]):
collision = bs.getcollision() collision = bs.getcollision()
try: try:
region = collision.sourcenode.getdelegate(RaceRegion, True) region = collision.sourcenode.getdelegate(RaceRegion, True)
spaz = collision.opposingnode.getdelegate(PlayerSpaz,True) spaz = collision.opposingnode.getdelegate(PlayerSpaz, True)
except bs.NotFoundError: except bs.NotFoundError:
return return
if not spaz.is_alive(): if not spaz.is_alive():
return return
try: try:
player = spaz.getplayer(Player, True) player = spaz.getplayer(Player, True)
except bs.NotFoundError: except bs.NotFoundError:
return return
last_region = player.last_region last_region = player.last_region
this_region = region.index this_region = region.index
@ -713,7 +713,7 @@ class RaceGame(bs.TeamGameActivity[Player, Team]):
translate=('statements', 'Killing ${NAME} for' translate=('statements', 'Killing ${NAME} for'
' skipping part of the track!'), ' skipping part of the track!'),
subs=[('${NAME}', player.getname(full=True))]), subs=[('${NAME}', player.getname(full=True))]),
color=(1, 0, 0)) color=(1, 0, 0))
else: else:
# If this player is in first, note that this is the # If this player is in first, note that this is the
# front-most race-point. # front-most race-point.
@ -788,10 +788,10 @@ class RaceGame(bs.TeamGameActivity[Player, Team]):
player.actor.node.connectattr( player.actor.node.connectattr(
'torso_position', mathnode, 'input2') 'torso_position', mathnode, 'input2')
tstr = babase.Lstr(resource='lapNumberText', tstr = babase.Lstr(resource='lapNumberText',
subs=[('${CURRENT}', subs=[('${CURRENT}',
str(player.lap + 1)), str(player.lap + 1)),
('${TOTAL}', str(self._laps)) ('${TOTAL}', str(self._laps))
]) ])
txtnode = bs.newnode('text', txtnode = bs.newnode('text',
owner=mathnode, owner=mathnode,
attrs={ attrs={
@ -828,7 +828,7 @@ class RaceGame(bs.TeamGameActivity[Player, Team]):
'${TEAM} is disqualified because ${PLAYER} left'), '${TEAM} is disqualified because ${PLAYER} left'),
subs=[('${TEAM}', player.team.name), subs=[('${TEAM}', player.team.name),
('${PLAYER}', player.getname(full=True))]), ('${PLAYER}', player.getname(full=True))]),
color=(1, 1, 0)) color=(1, 1, 0))
player.team.finished = True player.team.finished = True
player.team.time = None player.team.time = None
player.team.lap = 0 player.team.lap = 0
@ -967,55 +967,54 @@ class RaceGame(bs.TeamGameActivity[Player, Team]):
self._tnt((-6, 5, 1), (0, 0, 0), 1.3) self._tnt((-6, 5, 1), (0, 0, 0), 1.3)
bs.timer(0.1, bs.WeakCall(self._tnt, (-3.2, 5, 1), bs.timer(0.1, bs.WeakCall(self._tnt, (-3.2, 5, 1),
(0, 0, 0), 1.0, (0, 20, 60)), repeat=True) (0, 0, 0), 1.0, (0, 20, 60)), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(6, 7, 1), (0, 0, 0), 1.0, 1.0), repeat=True) (6, 7, 1), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(6.8, 7, 1), (0, 0, 0), 1.0, 1.0), repeat=True) (6.8, 7, 1), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(7.6, 7, 1), (0, 0, 0), 1.0, 1.0), repeat=True) (7.6, 7, 1), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(6, 7, -2.2), (0, 0, 0), 1.0, 1.0), repeat=True) (6, 7, -2.2), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(6.8, 7, -2.2), (0, 0, 0), 1.0, 1.0), repeat=True) (6.8, 7, -2.2), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(7.6, 7, -2.2), (0, 0, 0), 1.0, 1.0), repeat=True) (7.6, 7, -2.2), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(6, 7, -5.2), (0, 0, 0), 1.0, 1.0), repeat=True) (6, 7, -5.2), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(6.8, 7, -5.2), (0, 0, 0), 1.0, 1.0), repeat=True) (6.8, 7, -5.2), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(7.6, 7, -5.2), (0, 0, 0), 1.0, 1.0), repeat=True) (7.6, 7, -5.2), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(6, 7, -8), (0, 0, 0), 1.0, 1.0), repeat=True) (6, 7, -8), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(6.8, 7, -8), (0, 0, 0), 1.0, 1.0), repeat=True) (6.8, 7, -8), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(7.6, 7, -8), (0, 0, 0), 1.0, 1.0), repeat=True) (7.6, 7, -8), (0, 0, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(-5, 5, 0), (0, 0, 0), 1.0, 1.0, (0, 20, 3)), repeat=True) (-5, 5, 0), (0, 0, 0), 1.0, 1.0, (0, 20, 3)), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'impact', bs.timer(1.6, bs.WeakCall(self._bomb, 'impact',
(-1.5, 5, 0), (0, 0, 0), 1.0, 1.0, (0, 20, 3)), repeat=True) (-1.5, 5, 0), (0, 0, 0), 1.0, 1.0, (0, 20, 3)), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky', bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky',
(-1, 5, -8), (0, 10, 0), 1.0, 1.0), repeat=True) (-1, 5, -8), (0, 10, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky', bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky',
(-1, 5, -9), (0, 10, 0), 1.0, 1.0), repeat=True) (-1, 5, -9), (0, 10, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky', bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky',
(-1, 5, -10), (0, 10, 0), 1.0, 1.0), repeat=True) (-1, 5, -10), (0, 10, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky', bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky',
(-4.6, 5, -8), (0, 10, 0), 1.0, 1.0), repeat=True) (-4.6, 5, -8), (0, 10, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky', bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky',
(-4.6, 5, -9), (0, 10, 0), 1.0, 1.0), repeat=True) (-4.6, 5, -9), (0, 10, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky', bs.timer(1.6, bs.WeakCall(self._bomb, 'sticky',
(-4.6, 5, -10), (0, 10, 0), 1.0, 1.0), repeat=True) (-4.6, 5, -10), (0, 10, 0), 1.0, 1.0), repeat=True)
bs.timer(1.6, bs.WeakCall( bs.timer(1.6, bs.WeakCall(
self._powerup, (2, 5, -5), 'curse', (0, 20, -3)), repeat=True) self._powerup, (2, 5, -5), 'curse', (0, 20, -3)), repeat=True)
@ -1029,7 +1028,7 @@ class RaceGame(bs.TeamGameActivity[Player, Team]):
extra_acceleration: float = None) -> None: extra_acceleration: float = None) -> None:
if extra_acceleration: if extra_acceleration:
TNT(position, velocity, tnt_scale, False).autoretain( TNT(position, velocity, tnt_scale, False).autoretain(
).node.extra_acceleration = extra_acceleration ).node.extra_acceleration = extra_acceleration
else: else:
TNT(position, velocity, tnt_scale).autoretain() TNT(position, velocity, tnt_scale).autoretain()
@ -1044,7 +1043,7 @@ class RaceGame(bs.TeamGameActivity[Player, Team]):
NewBomb(position=position, NewBomb(position=position,
velocity=velocity, velocity=velocity,
bomb_type=type).autoretain( bomb_type=type).autoretain(
).node.extra_acceleration = extra_acceleration ).node.extra_acceleration = extra_acceleration
else: else:
NewBomb(position=position, NewBomb(position=position,
velocity=velocity, velocity=velocity,
@ -1057,7 +1056,7 @@ class RaceGame(bs.TeamGameActivity[Player, Team]):
if extra_acceleration: if extra_acceleration:
PowerupBox(position=position, PowerupBox(position=position,
poweruptype=poweruptype).autoretain( poweruptype=poweruptype).autoretain(
).node.extra_acceleration = extra_acceleration ).node.extra_acceleration = extra_acceleration
else: else:
PowerupBox(position=position, poweruptype=poweruptype).autoretain() PowerupBox(position=position, poweruptype=poweruptype).autoretain()

File diff suppressed because it is too large Load diff

View file

@ -17,173 +17,210 @@ from bascenev1lib.actor.onscreentimer import OnScreenTimer
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Any, Sequence, Optional, List, Dict, Type, Type from typing import Any, Sequence, Optional, List, Dict, Type, Type
class _GotTouched(): class _GotTouched():
pass pass
class UFO(bs.Actor): class UFO(bs.Actor):
def __init__(self, pos: float = (0,0,0)): def __init__(self, pos: float = (0, 0, 0)):
super().__init__() super().__init__()
shared = SharedObjects.get() shared = SharedObjects.get()
self.r: Optional[int] = 0 self.r: Optional[int] = 0
self.dis: Optional[List] = [] self.dis: Optional[List] = []
self.target: float = (0.0, 0.0, 0.0) self.target: float = (0.0, 0.0, 0.0)
self.regs: List[bs.NodeActor] = [] self.regs: List[bs.NodeActor] = []
self.node = bs.newnode('prop', self.node = bs.newnode('prop',
delegate=self, delegate=self,
attrs={'body':'landMine', attrs={'body': 'landMine',
'position': pos, 'position': pos,
'mesh':bs.getmesh('landMine'), 'mesh': bs.getmesh('landMine'),
'mesh_scale': 1.5, 'mesh_scale': 1.5,
'body_scale': 0.01, 'body_scale': 0.01,
'shadow_size': 0.000001, 'shadow_size': 0.000001,
'gravity_scale': 0.0, 'gravity_scale': 0.0,
'color_texture': bs.gettexture("achievementCrossHair"), 'color_texture': bs.gettexture("achievementCrossHair"),
'materials': [shared.object_material]}) 'materials': [shared.object_material]})
self.ufo_collide = None self.ufo_collide = None
def create_target(self): def create_target(self):
if not self.node.exists(): return if not self.node.exists():
self.dis = [] return
shared = SharedObjects.get() self.dis = []
try: shared = SharedObjects.get()
def pass_(): try:
self.regs.clear() def pass_():
bs.timer(3875*0.001, self.move) self.regs.clear()
try: bs.timer(3277*0.001, lambda: Bomb(velocity=(0,0,0), position=(self.target[0], self.node.position[1]-0.43999, self.target[2]), bomb_type='impact').autoretain().arm()) bs.timer(3875*0.001, self.move)
except: pass try:
key = bs.Material() bs.timer(3277*0.001, lambda: Bomb(velocity=(0, 0, 0), position=(
key.add_actions( self.target[0], self.node.position[1]-0.43999, self.target[2]), bomb_type='impact').autoretain().arm())
conditions=('they_have_material', shared.object_material), except:
actions=( pass
('modify_part_collision', 'collide', True), key = bs.Material()
('modify_part_collision', 'physical', False), key.add_actions(
('call', 'at_connect', pass_()), conditions=('they_have_material', shared.object_material),
)) actions=(
except: pass ('modify_part_collision', 'collide', True),
self.regs.append(bs.NodeActor(bs.newnode('region', ('modify_part_collision', 'physical', False),
attrs={ ('call', 'at_connect', pass_()),
'position': self.target, ))
'scale': (0.04, 22, 0.04), except:
'type': 'sphere', pass
'materials':[key]}))) self.regs.append(bs.NodeActor(bs.newnode('region',
attrs={
'position': self.target,
'scale': (0.04, 22, 0.04),
'type': 'sphere',
'materials': [key]})))
def move(self): def move(self):
if not self.node.exists(): return if not self.node.exists():
try: return
self.create_target() try:
for j in bs.getnodes(): self.create_target()
n = j.getdelegate(object) for j in bs.getnodes():
if j.getnodetype() == 'prop' and isinstance(n, TileFloor): n = j.getdelegate(object)
if n.node.exists(): self.dis.append(n.node) if j.getnodetype() == 'prop' and isinstance(n, TileFloor):
self.r = random.randint(0,len(self.dis)-1) if n.node.exists():
self.target = (self.dis[self.r].position[0], self.node.position[1], self.dis[self.r].position[2]) self.dis.append(n.node)
bs.animate_array(self.node, 'position', 3, { self.r = random.randint(0, len(self.dis)-1)
0:self.node.position, self.target = (self.dis[self.r].position[0],
3.0:self.target}) self.node.position[1], self.dis[self.r].position[2])
except: pass bs.animate_array(self.node, 'position', 3, {
def handlemessage(self, msg): 0: self.node.position,
3.0: self.target})
except:
pass
if isinstance(msg, bs.DieMessage): def handlemessage(self, msg):
self.node.delete()
elif isinstance(msg ,bs.OutOfBoundsMessage): self.handlemessage(bs.DieMessage()) if isinstance(msg, bs.DieMessage):
else: super().handlemessage(msg) self.node.delete()
elif isinstance(msg, bs.OutOfBoundsMessage):
self.handlemessage(bs.DieMessage())
else:
super().handlemessage(msg)
class TileFloor(bs.Actor): class TileFloor(bs.Actor):
def __init__(self, def __init__(self,
pos: float = (0, 0, 0)): pos: float = (0, 0, 0)):
super().__init__() super().__init__()
get_mat = SharedObjects.get() get_mat = SharedObjects.get()
self.pos = pos self.pos = pos
self.scale = 1.5 self.scale = 1.5
self.mat, self.mat2, self.test = bs.Material(), bs.Material(), bs.Material() self.mat, self.mat2, self.test = bs.Material(), bs.Material(), bs.Material()
self.mat.add_actions(conditions=('we_are_older_than', 1), actions=(('modify_part_collision', 'collide', False))) self.mat.add_actions(conditions=('we_are_older_than', 1),
self.mat2.add_actions(conditions=('we_are_older_than', 1), actions=(('modify_part_collision', 'collide', True))) actions=(('modify_part_collision', 'collide', False)))
self.test.add_actions( self.mat2.add_actions(conditions=('we_are_older_than', 1),
actions=(('modify_part_collision', 'collide', True)))
self.test.add_actions(
conditions=('they_have_material', BombFactory.get().bomb_material), conditions=('they_have_material', BombFactory.get().bomb_material),
actions=( actions=(
('modify_part_collision', 'collide', True), ('modify_part_collision', 'collide', True),
('modify_part_collision', 'physical', False), ('modify_part_collision', 'physical', False),
('message', 'our_node', 'at_connect', _GotTouched()))) ('message', 'our_node', 'at_connect', _GotTouched())))
self.node = bs.newnode('prop', self.node = bs.newnode('prop',
delegate=self, delegate=self,
attrs={'body':'puck', attrs={'body': 'puck',
'position': self.pos, 'position': self.pos,
'mesh':bs.getmesh('buttonSquareOpaque'), 'mesh': bs.getmesh('buttonSquareOpaque'),
'mesh_scale': self.scale*1.16, 'mesh_scale': self.scale*1.16,
'body_scale': self.scale, 'body_scale': self.scale,
'shadow_size': 0.0002, 'shadow_size': 0.0002,
'gravity_scale': 0.0, 'gravity_scale': 0.0,
'color_texture': bs.gettexture("tnt"), 'color_texture': bs.gettexture("tnt"),
'is_area_of_interest': True, 'is_area_of_interest': True,
'materials': [self.mat, self.test]}) 'materials': [self.mat, self.test]})
self.node_support = bs.newnode('region', self.node_support = bs.newnode('region',
attrs={ attrs={
'position': self.pos, 'position': self.pos,
'scale': (self.scale*0.8918, 0.1, self.scale*0.8918), 'scale': (self.scale*0.8918, 0.1, self.scale*0.8918),
'type': 'box', 'type': 'box',
'materials':[get_mat.footing_material, self.mat2] 'materials': [get_mat.footing_material, self.mat2]
}) })
def handlemessage(self, msg):
if isinstance(msg, bs.DieMessage): def handlemessage(self, msg):
self.node.delete() if isinstance(msg, bs.DieMessage):
self.node_support.delete() self.node.delete()
elif isinstance(msg, _GotTouched): self.node_support.delete()
def do(): self.handlemessage(bs.DieMessage()) elif isinstance(msg, _GotTouched):
bs.timer(0.1, do) def do(): self.handlemessage(bs.DieMessage())
else: super().handlemessage(msg) bs.timer(0.1, do)
else:
super().handlemessage(msg)
class defs(): class defs():
points = boxes = {} points = boxes = {}
boxes['area_of_interest_bounds'] = (-1.3440, 1.185751251, 3.7326226188) + ( boxes['area_of_interest_bounds'] = (-1.3440, 1.185751251, 3.7326226188) + (
0.0, 0.0, 0.0) + (29.8180273, 15.57249038, 22.93859993) 0.0, 0.0, 0.0) + (29.8180273, 15.57249038, 22.93859993)
boxes['map_bounds'] = (0.0, 2.585751251, 0.4326226188) + (0.0, 0.0, 0.0) + (29.09506485, 15.81173179, 33.76723155) boxes['map_bounds'] = (0.0, 2.585751251, 0.4326226188) + (0.0, 0.0,
0.0) + (29.09506485, 15.81173179, 33.76723155)
class DummyMapForGame(bs.Map): class DummyMapForGame(bs.Map):
defs, name = defs(), 'Tile Lands' defs, name = defs(), 'Tile Lands'
@classmethod @classmethod
def get_play_types(cls) -> List[str]: def get_play_types(cls) -> List[str]:
return [] return []
@classmethod @classmethod
def get_preview_texture_name(cls) -> str: def get_preview_texture_name(cls) -> str:
return 'achievementCrossHair' return 'achievementCrossHair'
@classmethod @classmethod
def on_preload(cls) -> Any: def on_preload(cls) -> Any:
data: Dict[str, Any] = {'bg_1': bs.gettexture('rampageBGColor'),'bg_2': bs.gettexture('rampageBGColor2'),'bg_mesh_1': bs.getmesh('rampageBG'),'bg_mesh_2': bs.getmesh('rampageBG2'),} data: Dict[str, Any] = {'bg_1': bs.gettexture('rampageBGColor'), 'bg_2': bs.gettexture(
'rampageBGColor2'), 'bg_mesh_1': bs.getmesh('rampageBG'), 'bg_mesh_2': bs.getmesh('rampageBG2'), }
return data return data
def __init__(self) -> None: def __init__(self) -> None:
super().__init__() super().__init__()
self.bg1 = bs.newnode('terrain',attrs={'mesh': self.preloaddata['bg_mesh_1'],'lighting': False,'background': True,'color_texture': self.preloaddata['bg_2']}) self.bg1 = bs.newnode('terrain', attrs={
self.bg2 = bs.newnode('terrain',attrs={ 'mesh': self.preloaddata['bg_mesh_2'], 'lighting': False,'background': True, 'color_texture': self.preloaddata['bg_2']}) 'mesh': self.preloaddata['bg_mesh_1'], 'lighting': False, 'background': True, 'color_texture': self.preloaddata['bg_2']})
self.bg2 = bs.newnode('terrain', attrs={
'mesh': self.preloaddata['bg_mesh_2'], 'lighting': False, 'background': True, 'color_texture': self.preloaddata['bg_2']})
a = bs.getactivity().globalsnode a = bs.getactivity().globalsnode
a.tint, a.ambient_color, a.vignette_outer, a.vignette_inner = (1.2, 1.1, 0.97), (1.3, 1.2, 1.03), (0.62, 0.64, 0.69), (0.97, 0.95, 0.93) a.tint, a.ambient_color, a.vignette_outer, a.vignette_inner = (
1.2, 1.1, 0.97), (1.3, 1.2, 1.03), (0.62, 0.64, 0.69), (0.97, 0.95, 0.93)
class DummyMapForGame2(bs.Map): class DummyMapForGame2(bs.Map):
defs, name = defs(), 'Tile Lands Night' defs, name = defs(), 'Tile Lands Night'
@classmethod @classmethod
def get_play_types(cls) -> List[str]: def get_play_types(cls) -> List[str]:
return [] return []
@classmethod @classmethod
def get_preview_texture_name(cls) -> str: def get_preview_texture_name(cls) -> str:
return 'achievementCrossHair' return 'achievementCrossHair'
@classmethod @classmethod
def on_preload(cls) -> Any: def on_preload(cls) -> Any:
data: Dict[str, Any] = {'bg_1': bs.gettexture('menuBG'),'bg_2': bs.gettexture('menuBG'),'bg_mesh_1': bs.getmesh('thePadBG'),'bg_mesh_2': bs.getmesh('thePadBG'),} data: Dict[str, Any] = {'bg_1': bs.gettexture('menuBG'), 'bg_2': bs.gettexture(
'menuBG'), 'bg_mesh_1': bs.getmesh('thePadBG'), 'bg_mesh_2': bs.getmesh('thePadBG'), }
return data return data
def __init__(self) -> None: def __init__(self) -> None:
super().__init__() super().__init__()
self.bg1 = bs.newnode('terrain',attrs={'mesh': self.preloaddata['bg_mesh_1'],'lighting': False,'background': True,'color_texture': self.preloaddata['bg_2']}) self.bg1 = bs.newnode('terrain', attrs={
self.bg2 = bs.newnode('terrain',attrs={ 'mesh': self.preloaddata['bg_mesh_2'], 'lighting': False,'background': True, 'color_texture': self.preloaddata['bg_2']}) 'mesh': self.preloaddata['bg_mesh_1'], 'lighting': False, 'background': True, 'color_texture': self.preloaddata['bg_2']})
self.bg2 = bs.newnode('terrain', attrs={
'mesh': self.preloaddata['bg_mesh_2'], 'lighting': False, 'background': True, 'color_texture': self.preloaddata['bg_2']})
a = bs.getactivity().globalsnode a = bs.getactivity().globalsnode
a.tint, a.ambient_color, a.vignette_outer, a.vignette_inner = (0.5, 0.7, 1.27), (2.5, 2.5, 2.5), (0.62, 0.64, 0.69), (0.97, 0.95, 0.93) a.tint, a.ambient_color, a.vignette_outer, a.vignette_inner = (
0.5, 0.7, 1.27), (2.5, 2.5, 2.5), (0.62, 0.64, 0.69), (0.97, 0.95, 0.93)
bs._map.register_map(DummyMapForGame) bs._map.register_map(DummyMapForGame)
bs._map.register_map(DummyMapForGame2) bs._map.register_map(DummyMapForGame2)
class Player(bs.Player['Team']): class Player(bs.Player['Team']):
"""Our player type for this game.""" """Our player type for this game."""
@ -202,12 +239,12 @@ class UFOAttackGame(bs.TeamGameActivity[Player, Team]):
name = 'UFO Attack' name = 'UFO Attack'
description = 'Dodge the falling bombs.' description = 'Dodge the falling bombs.'
available_settings = [ available_settings = [
bs.BoolSetting('Epic Mode', default=False), bs.BoolSetting('Epic Mode', default=False),
bs.BoolSetting('Enable Run', default=True), bs.BoolSetting('Enable Run', default=True),
bs.BoolSetting('Enable Jump', default=True), bs.BoolSetting('Enable Jump', default=True),
bs.BoolSetting('Display Map Area Dimension', default=False), bs.BoolSetting('Display Map Area Dimension', default=False),
bs.IntSetting('No. of Rows' + u'',max_value=13, min_value=1, default=8, increment=1), bs.IntSetting('No. of Rows' + u'', max_value=13, min_value=1, default=8, increment=1),
bs.IntSetting('No. of Columns' + u'', max_value=12, min_value=1, default=6, increment=1) bs.IntSetting('No. of Columns' + u'', max_value=12, min_value=1, default=6, increment=1)
] ]
scoreconfig = bs.ScoreConfig(label='Survived', scoreconfig = bs.ScoreConfig(label='Survived',
scoretype=bs.ScoreType.SECONDS, scoretype=bs.ScoreType.SECONDS,
@ -215,9 +252,11 @@ class UFOAttackGame(bs.TeamGameActivity[Player, Team]):
# Print messages when players die (since its meaningful in this game). # Print messages when players die (since its meaningful in this game).
announce_player_deaths = True announce_player_deaths = True
@classmethod @classmethod
def get_supported_maps(cls, sessiontype: Type[bs.Session]) -> List[str]: def get_supported_maps(cls, sessiontype: Type[bs.Session]) -> List[str]:
return ['Tile Lands', 'Tile Lands Night'] return ['Tile Lands', 'Tile Lands Night']
@classmethod @classmethod
def supports_session_type(cls, sessiontype: Type[bs.Session]) -> bool: def supports_session_type(cls, sessiontype: Type[bs.Session]) -> bool:
return (issubclass(sessiontype, bs.DualTeamSession) return (issubclass(sessiontype, bs.DualTeamSession)
@ -225,7 +264,7 @@ class UFOAttackGame(bs.TeamGameActivity[Player, Team]):
def __init__(self, settings: dict): def __init__(self, settings: dict):
super().__init__(settings) super().__init__(settings)
self.col = int(settings['No. of Columns' + u'']) self.col = int(settings['No. of Columns' + u''])
self.row = int(settings['No. of Rows' + u'']) self.row = int(settings['No. of Rows' + u''])
self.bool1 = bool(settings['Enable Run']) self.bool1 = bool(settings['Enable Run'])
@ -237,7 +276,8 @@ class UFOAttackGame(bs.TeamGameActivity[Player, Team]):
if self._epic_mode else bs.MusicType.SURVIVAL) if self._epic_mode else bs.MusicType.SURVIVAL)
if bool(settings["Display Map Area Dimension"]): if bool(settings["Display Map Area Dimension"]):
self.game_name = "UFO Attack " + "(" + str(self.col) + "x" + str(self.row) + ")" self.game_name = "UFO Attack " + "(" + str(self.col) + "x" + str(self.row) + ")"
else: self.game_name = "UFO Attack" else:
self.game_name = "UFO Attack"
if self._epic_mode: if self._epic_mode:
self.slow_motion = True self.slow_motion = True
@ -248,11 +288,11 @@ class UFOAttackGame(bs.TeamGameActivity[Player, Team]):
super().on_begin() super().on_begin()
self._timer = OnScreenTimer() self._timer = OnScreenTimer()
self._timer.start() self._timer.start()
#bs.timer(5.0, self._check_end_game) # bs.timer(5.0, self._check_end_game)
for r in range(self.col): for r in range(self.col):
for j in range(self.row): for j in range(self.row):
tile = TileFloor(pos=(-6.204283+(j*1.399), 3.425666, tile = TileFloor(pos=(-6.204283+(j*1.399), 3.425666,
-1.3538+(r*1.399))).autoretain() -1.3538+(r*1.399))).autoretain()
self.ufo = UFO(pos=(-5.00410667, 6.616383286, -2.503472)).autoretain() self.ufo = UFO(pos=(-5.00410667, 6.616383286, -2.503472)).autoretain()
bs.timer(7000*0.001, lambda: self.ufo.move()) bs.timer(7000*0.001, lambda: self.ufo.move())
for t in self.players: for t in self.players:
@ -262,7 +302,7 @@ class UFOAttackGame(bs.TeamGameActivity[Player, Team]):
if self.has_begun(): if self.has_begun():
bs.broadcastmessage( bs.broadcastmessage(
babase.Lstr(resource='playerDelayedJoinText', babase.Lstr(resource='playerDelayedJoinText',
subs=[('${PLAYER}', player.getname(full=True))]), subs=[('${PLAYER}', player.getname(full=True))]),
color=(0, 1, 0), color=(0, 1, 0),
) )
assert self._timer is not None assert self._timer is not None
@ -278,9 +318,10 @@ class UFOAttackGame(bs.TeamGameActivity[Player, Team]):
for a in bs.getnodes(): for a in bs.getnodes():
g = a.getdelegate(object) g = a.getdelegate(object)
if a.getnodetype() == 'prop' and isinstance(g, TileFloor): if a.getnodetype() == 'prop' and isinstance(g, TileFloor):
dis.append(g.node) dis.append(g.node)
r = random.randint(0, len(dis)-1) r = random.randint(0, len(dis)-1)
spaz = self.spawn_player_spaz(player, position=(dis[r].position[0], dis[r].position[1]+1.005958, dis[r].position[2])) spaz = self.spawn_player_spaz(player, position=(
dis[r].position[0], dis[r].position[1]+1.005958, dis[r].position[2]))
spaz.connect_controls_to_player(enable_punch=False, spaz.connect_controls_to_player(enable_punch=False,
enable_bomb=False, enable_bomb=False,
enable_run=self.bool1, enable_run=self.bool1,
@ -288,6 +329,7 @@ class UFOAttackGame(bs.TeamGameActivity[Player, Team]):
enable_pickup=False) enable_pickup=False)
spaz.play_big_death_sound = True spaz.play_big_death_sound = True
return spaz return spaz
def handlemessage(self, msg: Any) -> Any: def handlemessage(self, msg: Any) -> Any:
if isinstance(msg, bs.PlayerDiedMessage): if isinstance(msg, bs.PlayerDiedMessage):
super().handlemessage(msg) super().handlemessage(msg)
@ -308,7 +350,7 @@ class UFOAttackGame(bs.TeamGameActivity[Player, Team]):
living_team_count += 1 living_team_count += 1
break break
if living_team_count <= 1: if living_team_count <= 1:
self.end_game() self.end_game()
def end_game(self) -> None: def end_game(self) -> None:
self.ufo.handlemessage(bs.DieMessage()) self.ufo.handlemessage(bs.DieMessage())
@ -337,4 +379,4 @@ class UFOAttackGame(bs.TeamGameActivity[Player, Team]):
# Submit the score value in milliseconds. # Submit the score value in milliseconds.
results.set_team_score(team, int(longest_life)) results.set_team_score(team, int(longest_life))
self.end(results=results) self.end(results=results)

View file

@ -176,6 +176,7 @@ class Team(bs.Team[Player]):
self.survival_seconds: Optional[int] = None self.survival_seconds: Optional[int] = None
self.spawn_order: List[Player] = [] self.spawn_order: List[Player] = []
lang = bs.app.lang.language lang = bs.app.lang.language
if lang == 'Spanish': if lang == 'Spanish':
description = 'Mantente en la zona segura.' description = 'Mantente en la zona segura.'
@ -187,6 +188,8 @@ else:
kill_timer = 'Kill timer: ' kill_timer = 'Kill timer: '
# ba_meta export bascenev1.GameActivity # ba_meta export bascenev1.GameActivity
class SafeZoneGame(bs.TeamGameActivity[Player, Team]): class SafeZoneGame(bs.TeamGameActivity[Player, Team]):
"""Game type where last player(s) left alive win.""" """Game type where last player(s) left alive win."""
@ -244,7 +247,7 @@ class SafeZoneGame(bs.TeamGameActivity[Player, Team]):
@classmethod @classmethod
def get_supported_maps(cls, sessiontype: Type[bs.Session]) -> List[str]: def get_supported_maps(cls, sessiontype: Type[bs.Session]) -> List[str]:
return ['Football Stadium','Hockey Stadium'] return ['Football Stadium', 'Hockey Stadium']
def __init__(self, settings: dict): def __init__(self, settings: dict):
super().__init__(settings) super().__init__(settings)
@ -263,7 +266,7 @@ class SafeZoneGame(bs.TeamGameActivity[Player, Team]):
self.slow_motion = self._epic_mode self.slow_motion = self._epic_mode
self.default_music = (bs.MusicType.EPIC self.default_music = (bs.MusicType.EPIC
if self._epic_mode else bs.MusicType.SURVIVAL) if self._epic_mode else bs.MusicType.SURVIVAL)
self._tick_sound = bs.getsound('tick') self._tick_sound = bs.getsound('tick')
def get_instance_description(self) -> Union[str, Sequence]: def get_instance_description(self) -> Union[str, Sequence]:
@ -286,7 +289,7 @@ class SafeZoneGame(bs.TeamGameActivity[Player, Team]):
player.team.survival_seconds = 0 player.team.survival_seconds = 0
bs.broadcastmessage( bs.broadcastmessage(
babase.Lstr(resource='playerDelayedJoinText', babase.Lstr(resource='playerDelayedJoinText',
subs=[('${PLAYER}', player.getname(full=True))]), subs=[('${PLAYER}', player.getname(full=True))]),
color=(0, 1, 0), color=(0, 1, 0),
) )
return return
@ -305,21 +308,21 @@ class SafeZoneGame(bs.TeamGameActivity[Player, Team]):
# Don't waste time doing this until begin. # Don't waste time doing this until begin.
if self.has_begun(): if self.has_begun():
self._update_icons() self._update_icons()
def on_begin(self) -> None: def on_begin(self) -> None:
super().on_begin() super().on_begin()
self._start_time = bs.time() self._start_time = bs.time()
self.setup_standard_time_limit(self._time_limit) self.setup_standard_time_limit(self._time_limit)
#self.setup_standard_powerup_drops() # self.setup_standard_powerup_drops()
bs.timer(5,self.spawn_zone) bs.timer(5, self.spawn_zone)
self._bots = stdbot.SpazBotSet() self._bots = stdbot.SpazBotSet()
bs.timer(3,babase.Call(self.add_bot,'left')) bs.timer(3, babase.Call(self.add_bot, 'left'))
bs.timer(3,babase.Call(self.add_bot,'right')) bs.timer(3, babase.Call(self.add_bot, 'right'))
if len(self.initialplayerinfos) > 4: if len(self.initialplayerinfos) > 4:
bs.timer(5,babase.Call(self.add_bot,'right')) bs.timer(5, babase.Call(self.add_bot, 'right'))
bs.timer(5,babase.Call(self.add_bot,'left')) bs.timer(5, babase.Call(self.add_bot, 'left'))
if self._solo_mode: if self._solo_mode:
self._vs_text = bs.NodeActor( self._vs_text = bs.NodeActor(
bs.newnode('text', bs.newnode('text',
@ -359,78 +362,88 @@ class SafeZoneGame(bs.TeamGameActivity[Player, Team]):
# We could check game-over conditions at explicit trigger points, # We could check game-over conditions at explicit trigger points,
# but lets just do the simple thing and poll it. # but lets just do the simple thing and poll it.
bs.timer(1.0, self._update, repeat=True) bs.timer(1.0, self._update, repeat=True)
def spawn_zone(self): def spawn_zone(self):
self.zone_pos = (random.randrange(-10,10),0.05,random.randrange(-5,5)) self.zone_pos = (random.randrange(-10, 10), 0.05, random.randrange(-5, 5))
self.zone = bs.newnode('locator',attrs={'shape':'circle','position':self.zone_pos,'color':(1, 1, 0),'opacity':0.8,'draw_beauty':True,'additive':False,'drawShadow':False}) self.zone = bs.newnode('locator', attrs={'shape': 'circle', 'position': self.zone_pos, 'color': (
self.zone_limit = bs.newnode('locator',attrs={'shape':'circleOutline','position':self.zone_pos,'color':(1, 0.2, 0.2),'opacity':0.8,'draw_beauty':True,'additive':False,'drawShadow':False}) 1, 1, 0), 'opacity': 0.8, 'draw_beauty': True, 'additive': False, 'drawShadow': False})
bs.animate_array(self.zone, 'size', 1,{0:[0], 0.3:[self.get_players_count()*0.85], 0.35:[self.get_players_count()*0.8]}) self.zone_limit = bs.newnode('locator', attrs={'shape': 'circleOutline', 'position': self.zone_pos, 'color': (
bs.animate_array(self.zone_limit, 'size', 1,{0:[0], 0.3:[self.get_players_count()*1.2], 0.35:[self.get_players_count()*0.95]}) 1, 0.2, 0.2), 'opacity': 0.8, 'draw_beauty': True, 'additive': False, 'drawShadow': False})
bs.animate_array(self.zone, 'size', 1, {0: [0], 0.3: [
self.get_players_count()*0.85], 0.35: [self.get_players_count()*0.8]})
bs.animate_array(self.zone_limit, 'size', 1, {0: [0], 0.3: [
self.get_players_count()*1.2], 0.35: [self.get_players_count()*0.95]})
self.last_players_count = self.get_players_count() self.last_players_count = self.get_players_count()
bs.getsound('laserReverse').play() bs.getsound('laserReverse').play()
self.start_timer() self.start_timer()
self.move_zone() self.move_zone()
def delete_zone(self): def delete_zone(self):
self.zone.delete() self.zone.delete()
self.zone = None self.zone = None
self.zone_limit.delete() self.zone_limit.delete()
self.zone_limit = None self.zone_limit = None
bs.getsound('shieldDown').play() bs.getsound('shieldDown').play()
bs.timer(1,self.spawn_zone) bs.timer(1, self.spawn_zone)
def move_zone(self): def move_zone(self):
if self.zone_pos[0] > 0: x = random.randrange(0,10) if self.zone_pos[0] > 0:
else: x = random.randrange(-10,0) x = random.randrange(0, 10)
else:
if self.zone_pos[2] > 0: y = random.randrange(0,5) x = random.randrange(-10, 0)
else: y = random.randrange(-5,0)
if self.zone_pos[2] > 0:
new_pos = (x,0.05,y) y = random.randrange(0, 5)
bs.animate_array(self.zone, 'position', 3,{0:self.zone.position, 8:new_pos}) else:
bs.animate_array(self.zone_limit, 'position', 3,{0:self.zone_limit.position,8:new_pos}) y = random.randrange(-5, 0)
new_pos = (x, 0.05, y)
bs.animate_array(self.zone, 'position', 3, {0: self.zone.position, 8: new_pos})
bs.animate_array(self.zone_limit, 'position', 3, {0: self.zone_limit.position, 8: new_pos})
def start_timer(self): def start_timer(self):
count = self.get_players_count() count = self.get_players_count()
self._time_remaining = 10 if count > 9 else count-1 if count > 6 else count if count > 2 else count*2 self._time_remaining = 10 if count > 9 else count-1 if count > 6 else count if count > 2 else count*2
self._timer_x = bs.Timer(1.0,bs.WeakCall(self.tick),repeat=True) self._timer_x = bs.Timer(1.0, bs.WeakCall(self.tick), repeat=True)
# gnode = bs.getactivity().globalsnode # gnode = bs.getactivity().globalsnode
# tint = gnode.tint # tint = gnode.tint
# bs.animate_array(gnode,'tint',3,{0:tint,self._time_remaining*1.5:(1.0,0.5,0.5),self._time_remaining*1.55:tint}) # bs.animate_array(gnode,'tint',3,{0:tint,self._time_remaining*1.5:(1.0,0.5,0.5),self._time_remaining*1.55:tint})
def stop_timer(self): def stop_timer(self):
self._time = None self._time = None
self._timer_x = None self._timer_x = None
def tick(self): def tick(self):
self.check_players() self.check_players()
self._time = bs.NodeActor(bs.newnode('text', self._time = bs.NodeActor(bs.newnode('text',
attrs={'v_attach':'top','h_attach':'center', attrs={'v_attach': 'top', 'h_attach': 'center',
'text':kill_timer+str(self._time_remaining)+'s', 'text': kill_timer+str(self._time_remaining)+'s',
'opacity':0.8,'maxwidth':100,'h_align':'center', 'opacity': 0.8, 'maxwidth': 100, 'h_align': 'center',
'v_align':'center','shadow':1.0,'flatness':1.0, 'v_align': 'center', 'shadow': 1.0, 'flatness': 1.0,
'color':(1,1,1),'scale':1.5,'position':(0,-50)} 'color': (1, 1, 1), 'scale': 1.5, 'position': (0, -50)}
) )
) )
self._time_remaining -= 1 self._time_remaining -= 1
self._tick_sound.play() self._tick_sound.play()
def check_players(self): def check_players(self):
if self._time_remaining <= 0: if self._time_remaining <= 0:
self.stop_timer() self.stop_timer()
bs.animate_array(self.zone, 'size', 1,{0:[self.last_players_count*0.8], 1.4:[self.last_players_count*0.8],1.5:[0]}) bs.animate_array(self.zone, 'size', 1, {
bs.animate_array(self.zone_limit, 'size', 1,{0:[self.last_players_count*0.95], 1.45:[self.last_players_count*0.95],1.5:[0]}) 0: [self.last_players_count*0.8], 1.4: [self.last_players_count*0.8], 1.5: [0]})
bs.timer(1.5,self.delete_zone) bs.animate_array(self.zone_limit, 'size', 1, {
0: [self.last_players_count*0.95], 1.45: [self.last_players_count*0.95], 1.5: [0]})
bs.timer(1.5, self.delete_zone)
for player in self.players: for player in self.players:
if not player.actor is None: if not player.actor is None:
if player.actor.is_alive(): if player.actor.is_alive():
p1 = player.actor.node.position p1 = player.actor.node.position
p2 = self.zone.position p2 = self.zone.position
diff = (babase.Vec3(p1[0]-p2[0],0.0,p1[2]-p2[2])) diff = (babase.Vec3(p1[0]-p2[0], 0.0, p1[2]-p2[2]))
dist = (diff.length()) dist = (diff.length())
if dist > (self.get_players_count()*0.7): if dist > (self.get_players_count()*0.7):
player.actor.handlemessage(bs.DieMessage()) player.actor.handlemessage(bs.DieMessage())
def get_players_count(self): def get_players_count(self):
count = 0 count = 0
for player in self.players: for player in self.players:
@ -438,7 +451,7 @@ class SafeZoneGame(bs.TeamGameActivity[Player, Team]):
if player.actor.is_alive(): if player.actor.is_alive():
count += 1 count += 1
return count return count
def _update_solo_mode(self) -> None: def _update_solo_mode(self) -> None:
# For both teams, find the first player on the spawn order list with # For both teams, find the first player on the spawn order list with
# lives remaining and spawn them if they're not alive. # lives remaining and spawn them if they're not alive.
@ -558,9 +571,9 @@ class SafeZoneGame(bs.TeamGameActivity[Player, Team]):
# spaz but *without* the ability to attack or pick stuff up. # spaz but *without* the ability to attack or pick stuff up.
actor.connect_controls_to_player(enable_punch=False, actor.connect_controls_to_player(enable_punch=False,
enable_bomb=False, enable_bomb=False,
enable_pickup=False) enable_pickup=False)
# If we have any icons, update their state. # If we have any icons, update their state.
for icon in player.icons: for icon in player.icons:
icon.handle_player_spawned() icon.handle_player_spawned()
@ -642,38 +655,42 @@ class SafeZoneGame(bs.TeamGameActivity[Player, Team]):
if self._solo_mode: if self._solo_mode:
player.team.spawn_order.remove(player) player.team.spawn_order.remove(player)
player.team.spawn_order.append(player) player.team.spawn_order.append(player)
elif isinstance(msg,stdbot.SpazBotDiedMessage): elif isinstance(msg, stdbot.SpazBotDiedMessage):
self._on_spaz_bot_died(msg) self._on_spaz_bot_died(msg)
def _on_spaz_bot_died(self,die_msg): def _on_spaz_bot_died(self, die_msg):
bs.timer(1,babase.Call(self.add_bot,die_msg.spazbot.node.position)) bs.timer(1, babase.Call(self.add_bot, die_msg.spazbot.node.position))
def _on_bot_spawn(self,spaz): def _on_bot_spawn(self, spaz):
spaz.update_callback = self.move_bot spaz.update_callback = self.move_bot
spaz_type = type(spaz) spaz_type = type(spaz)
spaz._charge_speed = self._get_bot_speed(spaz_type) spaz._charge_speed = self._get_bot_speed(spaz_type)
def add_bot(self,pos=None): def add_bot(self, pos=None):
if pos == 'left': position = (-11,0,random.randrange(-5,5)) if pos == 'left':
elif pos == 'right': position = (11,0,random.randrange(-5,5)) position = (-11, 0, random.randrange(-5, 5))
else: position = pos elif pos == 'right':
self._bots.spawn_bot(self.get_random_bot(),pos=position,spawn_time=1,on_spawn_call=babase.Call(self._on_bot_spawn)) position = (11, 0, random.randrange(-5, 5))
else:
position = pos
self._bots.spawn_bot(self.get_random_bot(), pos=position, spawn_time=1,
on_spawn_call=babase.Call(self._on_bot_spawn))
def move_bot(self,bot): def move_bot(self, bot):
p = bot.node.position p = bot.node.position
speed = -bot._charge_speed if(p[0]>=-11 and p[0]<0) else bot._charge_speed speed = -bot._charge_speed if (p[0] >= -11 and p[0] < 0) else bot._charge_speed
if (p[0]>=-11) and (p[0]<=11): if (p[0] >= -11) and (p[0] <= 11):
bot.node.move_left_right = speed bot.node.move_left_right = speed
bot.node.move_up_down = 0.0 bot.node.move_up_down = 0.0
bot.node.run = 0.0 bot.node.run = 0.0
return True return True
return False return False
def get_random_bot(self): def get_random_bot(self):
bots = [stdbot.BomberBotStatic, stdbot.TriggerBotStatic] bots = [stdbot.BomberBotStatic, stdbot.TriggerBotStatic]
return (random.choice(bots)) return (random.choice(bots))
def _get_bot_speed(self, bot_type): def _get_bot_speed(self, bot_type):
if bot_type == stdbot.BomberBotStatic: if bot_type == stdbot.BomberBotStatic:
return 0.48 return 0.48
@ -681,7 +698,7 @@ class SafeZoneGame(bs.TeamGameActivity[Player, Team]):
return 0.73 return 0.73
else: else:
raise Exception('Invalid bot type to _getBotSpeed(): '+str(bot_type)) raise Exception('Invalid bot type to _getBotSpeed(): '+str(bot_type))
def _update(self) -> None: def _update(self) -> None:
if self._solo_mode: if self._solo_mode:
# For both teams, find the first player on the spawn order # For both teams, find the first player on the spawn order

View file

@ -18,6 +18,8 @@ if TYPE_CHECKING:
Spaz._old_init = Spaz.__init__ Spaz._old_init = Spaz.__init__
def __init__(self, def __init__(self,
color: Sequence[float] = (1.0, 1.0, 1.0), color: Sequence[float] = (1.0, 1.0, 1.0),
highlight: Sequence[float] = (0.5, 0.5, 0.5), highlight: Sequence[float] = (0.5, 0.5, 0.5),
@ -27,10 +29,11 @@ def __init__(self,
can_accept_powerups: bool = True, can_accept_powerups: bool = True,
powerups_expire: bool = False, powerups_expire: bool = False,
demo_mode: bool = False): demo_mode: bool = False):
self._old_init(color,highlight,character,source_player,start_invincible, self._old_init(color, highlight, character, source_player, start_invincible,
can_accept_powerups,powerups_expire,demo_mode) can_accept_powerups, powerups_expire, demo_mode)
if self.source_player: if self.source_player:
self.equip_shields() self.equip_shields()
def animate_shield(): def animate_shield():
if not self.shield: if not self.shield:
return return
@ -41,6 +44,7 @@ def __init__(self,
bs.timer(0.2, animate_shield, repeat=True) bs.timer(0.2, animate_shield, repeat=True)
self.impact_scale = 0 self.impact_scale = 0
def equip_shields(self, decay: bool = False) -> None: def equip_shields(self, decay: bool = False) -> None:
""" """
Give this spaz a nice energy shield. Give this spaz a nice energy shield.

View file

@ -29,7 +29,7 @@ from typing import (
Tuple, Tuple,
Optional, Optional,
Sequence, Sequence,
Union, Union,
Callable, Callable,
Any, Any,
List, List,
@ -52,18 +52,22 @@ Configs = {
} }
# Useful global fucntions # Useful global fucntions
def setconfigs() -> None: def setconfigs() -> None:
""" """
Set required defualt configs for mod Set required defualt configs for mod
""" """
cnfg = babase.app.config cnfg = babase.app.config
profiles = cnfg['Player Profiles'] profiles = cnfg['Player Profiles']
if not "TagConf" in cnfg: cnfg["TagConf"] = {} if not "TagConf" in cnfg:
cnfg["TagConf"] = {}
for p in profiles: for p in profiles:
if not p in cnfg["TagConf"]: if not p in cnfg["TagConf"]:
cnfg["TagConf"][str(p)] = Configs cnfg["TagConf"][str(p)] = Configs
babase.app.config.apply_and_commit() babase.app.config.apply_and_commit()
def getanimcolor(name: str) -> dict: def getanimcolor(name: str) -> dict:
""" """
Returns dictnary of colors with prefective time -> {seconds: (r, g, b)} Returns dictnary of colors with prefective time -> {seconds: (r, g, b)}
@ -72,14 +76,15 @@ def getanimcolor(name: str) -> dict:
s1 = 0.0 s1 = 0.0
s2 = s1 + freq s2 = s1 + freq
s3 = s2 + freq s3 = s2 + freq
animcolor = { animcolor = {
s1: (1,0,0), s1: (1, 0, 0),
s2: (0,1,0), s2: (0, 1, 0),
s3: (0,0,1) s3: (0, 0, 1)
} }
return animcolor return animcolor
def gethostname() -> str: def gethostname() -> str:
""" """
Return player name, by using -1 only host can use tags. Return player name, by using -1 only host can use tags.
@ -94,17 +99,20 @@ def gethostname() -> str:
return '__account__' return '__account__'
return name return name
# Dummy functions for extend functionality for class object # Dummy functions for extend functionality for class object
PlayerSpaz.init = PlayerSpaz.__init__ PlayerSpaz.init = PlayerSpaz.__init__
EditProfileWindow.init = EditProfileWindow.__init__ EditProfileWindow.init = EditProfileWindow.__init__
# PlayerSpaz object at -> bascenev1lib.actor.playerspaz # PlayerSpaz object at -> bascenev1lib.actor.playerspaz
def NewPlayerSzapInit(self, def NewPlayerSzapInit(self,
player: bs.Player, player: bs.Player,
color: Sequence[float] = (1.0, 1.0, 1.0), color: Sequence[float] = (1.0, 1.0, 1.0),
highlight: Sequence[float] = (0.5, 0.5, 0.5), highlight: Sequence[float] = (0.5, 0.5, 0.5),
character: str = 'Spaz', character: str = 'Spaz',
powerups_expire: bool = True) -> None: powerups_expire: bool = True) -> None:
self.init(player, color, highlight, character, powerups_expire) self.init(player, color, highlight, character, powerups_expire)
self.curname = gethostname() self.curname = gethostname()
@ -112,7 +120,8 @@ def NewPlayerSzapInit(self,
cnfg = babase.app.config["TagConf"] cnfg = babase.app.config["TagConf"]
if cnfg[str(self.curname)]["enabletag"]: if cnfg[str(self.curname)]["enabletag"]:
# Tag node # Tag node
self.mnode = bs.newnode('math', owner=self.node, attrs={'input1': (0, 1.5, 0),'operation': 'add'}) self.mnode = bs.newnode('math', owner=self.node, attrs={
'input1': (0, 1.5, 0), 'operation': 'add'})
self.node.connectattr('torso_position', self.mnode, 'input2') self.node.connectattr('torso_position', self.mnode, 'input2')
tagtext = cnfg[str(self.curname)]["tag"] tagtext = cnfg[str(self.curname)]["tag"]
@ -120,7 +129,7 @@ def NewPlayerSzapInit(self,
shadow = cnfg[str(self.curname)]["shadow"] shadow = cnfg[str(self.curname)]["shadow"]
sl = cnfg[str(self.curname)]["scale"] sl = cnfg[str(self.curname)]["scale"]
scale = 0.01 if sl == 'mediam' else 0.009 if not sl == 'large' else 0.02 scale = 0.01 if sl == 'mediam' else 0.009 if not sl == 'large' else 0.02
self.Tag = bs.newnode( self.Tag = bs.newnode(
type='text', type='text',
owner=self.node, owner=self.node,
@ -128,7 +137,7 @@ def NewPlayerSzapInit(self,
'text': str(tagtext), 'text': str(tagtext),
'in_world': True, 'in_world': True,
'shadow': shadow, 'shadow': shadow,
'color': (0,0,0), 'color': (0, 0, 0),
'scale': scale, 'scale': scale,
'opacity': opacity, 'opacity': opacity,
'flatness': 1.0, 'flatness': 1.0,
@ -138,13 +147,14 @@ def NewPlayerSzapInit(self,
if cnfg[str(self.curname)]["animtag"]: if cnfg[str(self.curname)]["animtag"]:
kys = getanimcolor(self.curname) kys = getanimcolor(self.curname)
bs.animate_array(node=self.Tag, attr='color', size=3, keys=kys, loop=True) bs.animate_array(node=self.Tag, attr='color', size=3, keys=kys, loop=True)
except Exception: pass except Exception:
pass
def NewEditProfileWindowInit(self, def NewEditProfileWindowInit(self,
existing_profile: Optional[str], existing_profile: Optional[str],
in_main_menu: bool, in_main_menu: bool,
transition: str = 'in_right') -> None: transition: str = 'in_right') -> None:
""" """
New boilerplate for editprofilewindow, addeds button to call TagSettings window New boilerplate for editprofilewindow, addeds button to call TagSettings window
""" """
@ -156,17 +166,18 @@ def NewEditProfileWindowInit(self,
x_inset = self._x_inset x_inset = self._x_inset
b_width = 50 b_width = 50
b_height = 30 b_height = 30
self.tagwinbtn = bui.buttonwidget( self.tagwinbtn = bui.buttonwidget(
parent=self._root_widget, parent=self._root_widget,
autoselect=True, autoselect=True,
position=(505 + x_inset, v - 38 - 15), position=(505 + x_inset, v - 38 - 15),
size=(b_width, b_height), size=(b_width, b_height),
color=(0.6, 0.5, 0.6), color=(0.6, 0.5, 0.6),
label='Tag', label='Tag',
button_type='square', button_type='square',
text_scale=1.2, text_scale=1.2,
on_activate_call=babase.Call(_on_tagwinbtn_press, self)) on_activate_call=babase.Call(_on_tagwinbtn_press, self))
def _on_tagwinbtn_press(self): def _on_tagwinbtn_press(self):
""" """
@ -174,10 +185,10 @@ def _on_tagwinbtn_press(self):
""" """
bui.containerwidget(edit=self._root_widget, transition='out_scale') bui.containerwidget(edit=self._root_widget, transition='out_scale')
bui.app.ui_v1.set_main_menu_window( bui.app.ui_v1.set_main_menu_window(
TagWindow(self.existing_profile, TagWindow(self.existing_profile,
self.in_main_menu, self.in_main_menu,
self._name, self._name,
transition='in_right').get_root_widget(), from_window=self._root_widget) transition='in_right').get_root_widget(), from_window=self._root_widget)
# ba_meta require api 8 # ba_meta require api 8
@ -188,10 +199,10 @@ class Tag(babase.Plugin):
Tag above actor player head, replacing PlayerSpaz class for getting actor, Tag above actor player head, replacing PlayerSpaz class for getting actor,
using EditProfileWindow for UI. using EditProfileWindow for UI.
""" """
if _babase.env().get("build_number",0) >= 20327: if _babase.env().get("build_number", 0) >= 20327:
setconfigs() setconfigs()
self.Replace() self.Replace()
def Replace(self) -> None: def Replace(self) -> None:
""" """
Replacing bolierplates no harm to relative funtionality only extending Replacing bolierplates no harm to relative funtionality only extending
@ -203,10 +214,10 @@ class Tag(babase.Plugin):
class TagWindow(bui.Window): class TagWindow(bui.Window):
def __init__(self, def __init__(self,
existing_profile: Optional[str], existing_profile: Optional[str],
in_main_menu: bool, in_main_menu: bool,
profilename: str, profilename: str,
transition: Optional[str] = 'in_right'): transition: Optional[str] = 'in_right'):
self.existing_profile = existing_profile self.existing_profile = existing_profile
self.in_main_menu = in_main_menu self.in_main_menu = in_main_menu
self.profilename = profilename self.profilename = profilename
@ -220,205 +231,205 @@ class TagWindow(bui.Window):
top_extra = 20 if uiscale is babase.UIScale.SMALL else 0 top_extra = 20 if uiscale is babase.UIScale.SMALL else 0
super().__init__( super().__init__(
root_widget=bui.containerwidget( root_widget=bui.containerwidget(
size=(self._width, self._height), size=(self._width, self._height),
transition=transition, transition=transition,
scale=(2.06 if uiscale is babase.UIScale.SMALL else scale=(2.06 if uiscale is babase.UIScale.SMALL else
1.4 if uiscale is babase.UIScale.MEDIUM else 1.0))) 1.4 if uiscale is babase.UIScale.MEDIUM else 1.0)))
self._back_button = bui.buttonwidget( self._back_button = bui.buttonwidget(
parent=self._root_widget, parent=self._root_widget,
autoselect=True, autoselect=True,
selectable=False, # FIXME: when press a in text field it selets to button selectable=False, # FIXME: when press a in text field it selets to button
position=(52 + self.extra_x, self._height - 60), position=(52 + self.extra_x, self._height - 60),
size=(60, 60), size=(60, 60),
scale=0.8, scale=0.8,
label=babase.charstr(babase.SpecialChar.BACK), label=babase.charstr(babase.SpecialChar.BACK),
button_type='backSmall', button_type='backSmall',
on_activate_call=self._back) on_activate_call=self._back)
bui.containerwidget(edit=self._root_widget, cancel_button=self._back_button) bui.containerwidget(edit=self._root_widget, cancel_button=self._back_button)
self._save_button = bui.buttonwidget( self._save_button = bui.buttonwidget(
parent=self._root_widget, parent=self._root_widget,
position=(self._width - (177 + extra_x), position=(self._width - (177 + extra_x),
self._height - 60), self._height - 60),
size=(155, 60), size=(155, 60),
color=(0, 0.7, 0.5), color=(0, 0.7, 0.5),
autoselect=True, autoselect=True,
selectable=False, # FIXME: when press a in text field it selets to button selectable=False, # FIXME: when press a in text field it selets to button
scale=0.8, scale=0.8,
label=babase.Lstr(resource='saveText'), label=babase.Lstr(resource='saveText'),
on_activate_call=self.on_save) on_activate_call=self.on_save)
bui.widget(edit=self._save_button, left_widget=self._back_button) bui.widget(edit=self._save_button, left_widget=self._back_button)
bui.widget(edit=self._back_button, right_widget=self._save_button) bui.widget(edit=self._back_button, right_widget=self._save_button)
bui.containerwidget(edit=self._root_widget, start_button=self._save_button) bui.containerwidget(edit=self._root_widget, start_button=self._save_button)
self._title_text = bui.textwidget( self._title_text = bui.textwidget(
parent=self._root_widget, parent=self._root_widget,
position=(0, self._height - 52 - top_extra), position=(0, self._height - 52 - top_extra),
size=(self._width, 25), size=(self._width, 25),
text='Tag', text='Tag',
color=bui.app.ui_v1.title_color, color=bui.app.ui_v1.title_color,
scale=1.5, scale=1.5,
h_align='center', h_align='center',
v_align='top') v_align='top')
self._scroll_width = self._width - (100 + 2 * extra_x) self._scroll_width = self._width - (100 + 2 * extra_x)
self._scroll_height = self._height - 115.0 self._scroll_height = self._height - 115.0
self._sub_width = self._scroll_width * 0.95 self._sub_width = self._scroll_width * 0.95
self._sub_height = 724.0 self._sub_height = 724.0
self._spacing = 32 self._spacing = 32
self._extra_button_spacing = self._spacing * 2.5 self._extra_button_spacing = self._spacing * 2.5
self._scrollwidget = bui.scrollwidget( self._scrollwidget = bui.scrollwidget(
parent=self._root_widget, parent=self._root_widget,
position=(50 + extra_x, 50), position=(50 + extra_x, 50),
simple_culling_v=20.0, simple_culling_v=20.0,
highlight=False, highlight=False,
size=(self._scroll_width, size=(self._scroll_width,
self._scroll_height), self._scroll_height),
selection_loops_to_parent=True) selection_loops_to_parent=True)
bui.widget(edit=self._scrollwidget, right_widget=self._scrollwidget) bui.widget(edit=self._scrollwidget, right_widget=self._scrollwidget)
self._subcontainer = bui.containerwidget( self._subcontainer = bui.containerwidget(
parent=self._scrollwidget, parent=self._scrollwidget,
size=(self._sub_width, size=(self._sub_width,
self._sub_height), self._sub_height),
background=False, background=False,
selection_loops_to_parent=True) selection_loops_to_parent=True)
v = self._sub_height - 35 v = self._sub_height - 35
v -= self._spacing * 1.2 v -= self._spacing * 1.2
self._prof = babase.app.config["TagConf"][self.profilename] self._prof = babase.app.config["TagConf"][self.profilename]
self.enabletagcb = bui.checkboxwidget( self.enabletagcb = bui.checkboxwidget(
parent=self._subcontainer, parent=self._subcontainer,
autoselect=False, autoselect=False,
position=(10.0, v + 30), position=(10.0, v + 30),
size=(10, 10), size=(10, 10),
text='Enable Tag', text='Enable Tag',
textcolor=(0.8, 0.8, 0.8), textcolor=(0.8, 0.8, 0.8),
value=self._prof['enabletag'], value=self._prof['enabletag'],
on_value_change_call=babase.Call(self.change_val, [f'{self.profilename}', 'enabletag']), on_value_change_call=babase.Call(self.change_val, [f'{self.profilename}', 'enabletag']),
scale=1.1 if uiscale is babase.UIScale.SMALL else 1.5, scale=1.1 if uiscale is babase.UIScale.SMALL else 1.5,
maxwidth=430) maxwidth=430)
self.tag_text = bui.textwidget( self.tag_text = bui.textwidget(
parent=self._subcontainer, parent=self._subcontainer,
text='Tag', text='Tag',
position=(25.0, v - 30), position=(25.0, v - 30),
flatness=1.0, flatness=1.0,
scale=1.55, scale=1.55,
maxwidth=430, maxwidth=430,
h_align='center', h_align='center',
v_align='center', v_align='center',
color=(0.8, 0.8, 0.8)) color=(0.8, 0.8, 0.8))
self.tagtextfield = bui.textwidget( self.tagtextfield = bui.textwidget(
parent=self._subcontainer, parent=self._subcontainer,
position=(100.0, v - 45), position=(100.0, v - 45),
size=(350, 50), size=(350, 50),
text=self._prof["tag"], text=self._prof["tag"],
h_align='center', h_align='center',
v_align='center', v_align='center',
max_chars=16, max_chars=16,
autoselect=True, autoselect=True,
editable=True, editable=True,
padding=4, padding=4,
color=(0.9, 0.9, 0.9, 1.0)) color=(0.9, 0.9, 0.9, 1.0))
self.tag_color_text = bui.textwidget( self.tag_color_text = bui.textwidget(
parent=self._subcontainer, parent=self._subcontainer,
text='Color', text='Color',
position=(40.0, v - 80), position=(40.0, v - 80),
flatness=1.0, flatness=1.0,
scale=1.25, scale=1.25,
maxwidth=430, maxwidth=430,
h_align='center', h_align='center',
v_align='center', v_align='center',
color=(0.8, 0.8, 0.8)) color=(0.8, 0.8, 0.8))
self.tag_scale_text = bui.textwidget( self.tag_scale_text = bui.textwidget(
parent=self._subcontainer, parent=self._subcontainer,
text='Scale', text='Scale',
position=(40.0, v - 130), position=(40.0, v - 130),
flatness=1.0, flatness=1.0,
scale=1.25, scale=1.25,
maxwidth=430, maxwidth=430,
h_align='center', h_align='center',
v_align='center', v_align='center',
color=(0.8, 0.8, 0.8)) color=(0.8, 0.8, 0.8))
self.tag_scale_button = PopupMenu( self.tag_scale_button = PopupMenu(
parent=self._subcontainer, parent=self._subcontainer,
position=(330.0, v - 145), position=(330.0, v - 145),
width=150, width=150,
autoselect=True, autoselect=True,
on_value_change_call=bs.WeakCall(self._on_menu_choice), on_value_change_call=bs.WeakCall(self._on_menu_choice),
choices=['large', 'medium', 'small'], choices=['large', 'medium', 'small'],
button_size=(150, 50), button_size=(150, 50),
#choices_display=('large', 'medium', 'small'), # choices_display=('large', 'medium', 'small'),
current_choice=self._prof["scale"]) current_choice=self._prof["scale"])
CustomConfigNumberEdit( CustomConfigNumberEdit(
parent=self._subcontainer, parent=self._subcontainer,
position=(40.0, v - 180), position=(40.0, v - 180),
xoffset=65, xoffset=65,
displayname='Opacity', displayname='Opacity',
configkey=['TagConf', f'{self.profilename}', 'opacity'], configkey=['TagConf', f'{self.profilename}', 'opacity'],
changesound=False, changesound=False,
minval=0.5, minval=0.5,
maxval=2.0, maxval=2.0,
increment=0.1, increment=0.1,
textscale=1.25) textscale=1.25)
CustomConfigNumberEdit( CustomConfigNumberEdit(
parent=self._subcontainer, parent=self._subcontainer,
position=(40.0, v - 230), position=(40.0, v - 230),
xoffset=65, xoffset=65,
displayname='Shadow', displayname='Shadow',
configkey=['TagConf', f'{self.profilename}', 'shadow'], configkey=['TagConf', f'{self.profilename}', 'shadow'],
changesound=False, changesound=False,
minval=0.0, minval=0.0,
maxval=2.0, maxval=2.0,
increment=0.1, increment=0.1,
textscale=1.25) textscale=1.25)
self.enabletaganim = bui.checkboxwidget( self.enabletaganim = bui.checkboxwidget(
parent=self._subcontainer, parent=self._subcontainer,
autoselect=True, autoselect=True,
position=(10.0, v - 280), position=(10.0, v - 280),
size=(10, 10), size=(10, 10),
text='Animate tag', text='Animate tag',
textcolor=(0.8, 0.8, 0.8), textcolor=(0.8, 0.8, 0.8),
value=self._prof['enabletag'], value=self._prof['enabletag'],
on_value_change_call=babase.Call(self.change_val, [f'{self.profilename}', 'animtag']), on_value_change_call=babase.Call(self.change_val, [f'{self.profilename}', 'animtag']),
scale=1.1 if uiscale is babase.UIScale.SMALL else 1.5, scale=1.1 if uiscale is babase.UIScale.SMALL else 1.5,
maxwidth=430) maxwidth=430)
CustomConfigNumberEdit( CustomConfigNumberEdit(
parent=self._subcontainer, parent=self._subcontainer,
position=(40.0, v - 330), position=(40.0, v - 330),
xoffset=65, xoffset=65,
displayname='Frequency', displayname='Frequency',
configkey=['TagConf', f'{self.profilename}', 'frequency'], configkey=['TagConf', f'{self.profilename}', 'frequency'],
changesound=False, changesound=False,
minval=0.1, minval=0.1,
maxval=5.0, maxval=5.0,
increment=0.1, increment=0.1,
textscale=1.25) textscale=1.25)
def _back(self) -> None: def _back(self) -> None:
""" """
transit window into back window transit window into back window
""" """
bui.containerwidget(edit=self._root_widget, bui.containerwidget(edit=self._root_widget,
transition='out_scale') transition='out_scale')
bui.app.ui_v1.set_main_menu_window(EditProfileWindow( bui.app.ui_v1.set_main_menu_window(EditProfileWindow(
self.existing_profile, self.existing_profile,
self.in_main_menu, self.in_main_menu,
transition='in_left').get_root_widget(), from_window=self._root_widget) transition='in_left').get_root_widget(), from_window=self._root_widget)
def change_val(self, config: List[str], val: bool) -> None: def change_val(self, config: List[str], val: bool) -> None:
""" """
chamges the value of check boxes chamges the value of check boxes
@ -428,10 +439,10 @@ class TagWindow(bui.Window):
cnfg[config[0]][config[1]] = val cnfg[config[0]][config[1]] = val
bui.getsound('gunCocking').play() bui.getsound('gunCocking').play()
except Exception: except Exception:
bui.screenmessage("error", color=(1,0,0)) bui.screenmessage("error", color=(1, 0, 0))
bui.getsound('error').play() bui.getsound('error').play()
babase.app.config.apply_and_commit() babase.app.config.apply_and_commit()
def _on_menu_choice(self, choice: str): def _on_menu_choice(self, choice: str):
""" """
Changes the given choice in configs Changes the given choice in configs
@ -439,7 +450,7 @@ class TagWindow(bui.Window):
cnfg = babase.app.config["TagConf"][self.profilename] cnfg = babase.app.config["TagConf"][self.profilename]
cnfg["scale"] = choice cnfg["scale"] = choice
babase.app.config.apply_and_commit() babase.app.config.apply_and_commit()
def on_save(self): def on_save(self):
""" """
Gets the text in text field of tag and then save it Gets the text in text field of tag and then save it
@ -451,15 +462,15 @@ class TagWindow(bui.Window):
babase.app.config.apply_and_commit() babase.app.config.apply_and_commit()
bui.getsound('gunCocking').play() bui.getsound('gunCocking').play()
else: else:
bui.screenmessage(f"please define tag", color=(1,0,0)) bui.screenmessage(f"please define tag", color=(1, 0, 0))
bui.getsound('error').play() bui.getsound('error').play()
bui.containerwidget(edit=self._root_widget, bui.containerwidget(edit=self._root_widget,
transition='out_scale') transition='out_scale')
bui.app.ui_v1.set_main_menu_window(EditProfileWindow( bui.app.ui_v1.set_main_menu_window(EditProfileWindow(
self.existing_profile, self.existing_profile,
self.in_main_menu, self.in_main_menu,
transition='in_left').get_root_widget(), from_window=self._root_widget) transition='in_left').get_root_widget(), from_window=self._root_widget)
class CustomConfigNumberEdit: class CustomConfigNumberEdit:
@ -503,46 +514,46 @@ class CustomConfigNumberEdit:
self._value = babase.app.config[configkey[0]][configkey[1]][configkey[2]] self._value = babase.app.config[configkey[0]][configkey[1]][configkey[2]]
self.nametext = bui.textwidget( self.nametext = bui.textwidget(
parent=parent, parent=parent,
position=position, position=position,
size=(100, 30), size=(100, 30),
text=displayname, text=displayname,
maxwidth=160 + xoffset, maxwidth=160 + xoffset,
color=(0.8, 0.8, 0.8, 1.0), color=(0.8, 0.8, 0.8, 1.0),
h_align='left', h_align='left',
v_align='center', v_align='center',
scale=textscale) scale=textscale)
self.valuetext = bui.textwidget( self.valuetext = bui.textwidget(
parent=parent, parent=parent,
position=(246 + xoffset, position[1]), position=(246 + xoffset, position[1]),
size=(60, 28), size=(60, 28),
editable=False, editable=False,
color=(0.3, 1.0, 0.3, 1.0), color=(0.3, 1.0, 0.3, 1.0),
h_align='right', h_align='right',
v_align='center', v_align='center',
text=str(self._value), text=str(self._value),
padding=2) padding=2)
self.minusbutton = bui.buttonwidget( self.minusbutton = bui.buttonwidget(
parent=parent, parent=parent,
position=(330 + xoffset, position[1]), position=(330 + xoffset, position[1]),
size=(28, 28), size=(28, 28),
label='-', label='-',
autoselect=True, autoselect=True,
on_activate_call=babase.Call(self._down), on_activate_call=babase.Call(self._down),
repeat=True, repeat=True,
enable_sound=changesound) enable_sound=changesound)
self.plusbutton = bui.buttonwidget(parent=parent, self.plusbutton = bui.buttonwidget(parent=parent,
position=(380 + xoffset, position[1]), position=(380 + xoffset, position[1]),
size=(28, 28), size=(28, 28),
label='+', label='+',
autoselect=True, autoselect=True,
on_activate_call=babase.Call(self._up), on_activate_call=babase.Call(self._up),
repeat=True, repeat=True,
enable_sound=changesound) enable_sound=changesound)
bui.uicleanupcheck(self, self.nametext) bui.uicleanupcheck(self, self.nametext)
self._update_display() self._update_display()
@ -558,8 +569,9 @@ class CustomConfigNumberEdit:
self._update_display() self._update_display()
if self._callback: if self._callback:
self._callback(self._value) self._callback(self._value)
babase.app.config[self._configkey[0]][self._configkey[1]][self._configkey[2]] = float(str(f'{self._value:.1f}')) babase.app.config[self._configkey[0]][self._configkey[1]
][self._configkey[2]] = float(str(f'{self._value:.1f}'))
babase.app.config.apply_and_commit() babase.app.config.apply_and_commit()
def _update_display(self) -> None: def _update_display(self) -> None:
bui.textwidget(edit=self.valuetext, text=f'{self._value:.1f}') bui.textwidget(edit=self.valuetext, text=f'{self._value:.1f}')

View file

@ -12,85 +12,89 @@ from bascenev1lib.gameutils import SharedObjects
if TYPE_CHECKING: if TYPE_CHECKING:
pass pass
class BombPickupMessage: class BombPickupMessage:
""" message says that someone pick up the dropped bomb """ """ message says that someone pick up the dropped bomb """
# for bs.FreezeMessage # for bs.FreezeMessage
freeze: bool = True freeze: bool = True
# ba_meta export plugin # ba_meta export plugin
class Plugin(babase.Plugin): class Plugin(babase.Plugin):
# there are two ways to ignore our team player hits # there are two ways to ignore our team player hits
# either change playerspaz handlemessage or change spaz handlemessage # either change playerspaz handlemessage or change spaz handlemessage
def playerspaz_new_handlemessage(func: fuction) -> fuction: def playerspaz_new_handlemessage(func: fuction) -> fuction:
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
global freeze global freeze
# only run if session is dual team # only run if session is dual team
if isinstance(args[0].activity.session, bs.DualTeamSession): if isinstance(args[0].activity.session, bs.DualTeamSession):
# when spaz got hurt by any reason this statement is runs. # when spaz got hurt by any reason this statement is runs.
if isinstance(args[1], bs.HitMessage): if isinstance(args[1], bs.HitMessage):
our_team_players: list[type(args[0]._player)] our_team_players: list[type(args[0]._player)]
# source_player # source_player
attacker = args[1].get_source_player(type(args[0]._player)) attacker = args[1].get_source_player(type(args[0]._player))
# our team payers # our team payers
our_team_players = args[0]._player.team.players.copy() our_team_players = args[0]._player.team.players.copy()
if len(our_team_players) > 0: if len(our_team_players) > 0:
# removing our self # removing our self
our_team_players.remove(args[0]._player) our_team_players.remove(args[0]._player)
# if we honding teammate or if we have a shield, do hit. # if we honding teammate or if we have a shield, do hit.
for player in our_team_players: for player in our_team_players:
if player.actor.exists() and args[0]._player.actor.exists(): if player.actor.exists() and args[0]._player.actor.exists():
if args[0]._player.actor.node.hold_node == player.actor.node or args[0]._player.actor.shield: if args[0]._player.actor.node.hold_node == player.actor.node or args[0]._player.actor.shield:
our_team_players.remove(player) our_team_players.remove(player)
break break
if attacker in our_team_players: if attacker in our_team_players:
freeze = False freeze = False
return None return None
else: else:
freeze = True freeze = True
# if ice_bomb blast hits any spaz this statement runs. # if ice_bomb blast hits any spaz this statement runs.
elif isinstance(args[1], bs.FreezeMessage): elif isinstance(args[1], bs.FreezeMessage):
if not freeze: if not freeze:
freeze = True # use it and reset it freeze = True # use it and reset it
return None return None
# orignal unchanged code goes here # orignal unchanged code goes here
func(*args, **kwargs) func(*args, **kwargs)
return wrapper return wrapper
# replace original fuction to modified function # replace original fuction to modified function
bascenev1lib.actor.playerspaz.PlayerSpaz.handlemessage = playerspaz_new_handlemessage( bascenev1lib.actor.playerspaz.PlayerSpaz.handlemessage = playerspaz_new_handlemessage(
bascenev1lib.actor.playerspaz.PlayerSpaz.handlemessage) bascenev1lib.actor.playerspaz.PlayerSpaz.handlemessage)
# let's add a message when bomb is pick by player # let's add a message when bomb is pick by player
def bombfact_new_init(func: function) -> function: def bombfact_new_init(func: function) -> function:
def wrapper(*args): def wrapper(*args):
func(*args) # original code func(*args) # original code
args[0].bomb_material.add_actions( args[0].bomb_material.add_actions(
conditions=('they_have_material', SharedObjects.get().pickup_material), conditions=('they_have_material', SharedObjects.get().pickup_material),
actions=('message', 'our_node', 'at_connect', BombPickupMessage()), actions=('message', 'our_node', 'at_connect', BombPickupMessage()),
) )
return wrapper return wrapper
# you get the idea # you get the idea
bascenev1lib.actor.bomb.BombFactory.__init__ = bombfact_new_init( bascenev1lib.actor.bomb.BombFactory.__init__ = bombfact_new_init(
bascenev1lib.actor.bomb.BombFactory.__init__) bascenev1lib.actor.bomb.BombFactory.__init__)
def bomb_new_handlemessage(func: function) -> function: def bomb_new_handlemessage(func: function) -> function:
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
# only run if session is dual team # only run if session is dual team
if isinstance(args[0].activity.session, bs.DualTeamSession): if isinstance(args[0].activity.session, bs.DualTeamSession):
if isinstance(args[1], BombPickupMessage): if isinstance(args[1], BombPickupMessage):
# get the pickuper and assign the pickuper to the source_player(attacker) of bomb blast # get the pickuper and assign the pickuper to the source_player(attacker) of bomb blast
@ -99,10 +103,10 @@ class Plugin(babase.Plugin):
if player.actor.node.hold_node == args[0].node: if player.actor.node.hold_node == args[0].node:
args[0]._source_player = player args[0]._source_player = player
break break
func(*args, **kwargs) # original func(*args, **kwargs) # original
return wrapper return wrapper
bascenev1lib.actor.bomb.Bomb.handlemessage = bomb_new_handlemessage( bascenev1lib.actor.bomb.Bomb.handlemessage = bomb_new_handlemessage(
bascenev1lib.actor.bomb.Bomb.handlemessage) bascenev1lib.actor.bomb.Bomb.handlemessage)