bombsquad-plugin-manager/plugins/minigames/soccer.py

383 lines
14 KiB
Python
Raw Normal View History

2022-11-02 15:09:34 +05:30
# Released under the MIT License. See LICENSE for details.
# BY Stary_Agent
"""Hockey game and support classes."""
2025-07-26 03:55:26 +03:00
plugman = dict(
plugin_name="soccer",
description="Shoot the ball in left or right edge of the map to score",
external_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
authors=[{"name": "mr.sample", "email": "sample@sample.com", "discord": "sample"}],
2025-07-26 04:00:53 +03:00
version="2.1.0"
2025-07-26 03:55:26 +03:00
)
2022-11-02 15:09:34 +05:30
2025-07-26 04:00:53 +03:00
# ba_meta require api 8
# (see https://ballistica.net/wiki/meta-tag-system)
from __future__ import annotations
from bascenev1lib.gameutils import SharedObjects
from bascenev1lib.actor.powerupbox import PowerupBoxFactory
from bascenev1lib.actor.scoreboard import Scoreboard
from bascenev1lib.actor.playerspaz import PlayerSpaz
import bascenev1 as bs
import bauiv1 as bui
import babase
from typing import TYPE_CHECKING
2022-11-02 15:09:34 +05:30
if TYPE_CHECKING:
from typing import Any, Sequence, Dict, Type, List, Optional, Union
2023-07-20 16:56:57 +00:00
2022-11-02 15:09:34 +05:30
class PuckDiedMessage:
"""Inform something that a puck has died."""
def __init__(self, puck: Puck):
self.puck = puck
2023-07-20 22:19:02 +05:30
class Puck(bs.Actor):
2022-11-02 15:09:34 +05:30
"""A lovely giant hockey puck."""
def __init__(self, position: Sequence[float] = (0.0, 1.0, 0.0)):
super().__init__()
shared = SharedObjects.get()
activity = self.getactivity()
# Spawn just above the provided point.
self._spawn_pos = (position[0], position[1] + 1.0, position[2])
self.last_players_to_touch: Dict[int, Player] = {}
self.scored = False
assert activity is not None
assert isinstance(activity, HockeyGame)
pmats = [shared.object_material, activity.puck_material]
2023-07-20 22:19:02 +05:30
self.node = bs.newnode('prop',
2022-11-02 15:09:34 +05:30
delegate=self,
attrs={
2023-07-20 22:19:02 +05:30
'mesh': activity.puck_model,
2022-11-02 15:09:34 +05:30
'color_texture': activity.puck_tex,
'body': 'sphere',
'reflection': 'soft',
'reflection_scale': [0.2],
'shadow_size': 0.5,
'is_area_of_interest': True,
'position': self._spawn_pos,
'materials': pmats
})
2023-07-20 22:19:02 +05:30
bs.animate(self.node, 'mesh_scale', {0: 0, 0.2: 1.3, 0.26: 1})
2022-11-02 15:09:34 +05:30
def handlemessage(self, msg: Any) -> Any:
2023-07-20 22:19:02 +05:30
if isinstance(msg, bs.DieMessage):
2022-11-02 15:09:34 +05:30
assert self.node
self.node.delete()
activity = self._activity()
if activity and not msg.immediate:
activity.handlemessage(PuckDiedMessage(self))
# If we go out of bounds, move back to where we started.
2023-07-20 22:19:02 +05:30
elif isinstance(msg, bs.OutOfBoundsMessage):
2022-11-02 15:09:34 +05:30
assert self.node
self.node.position = self._spawn_pos
2023-07-20 22:19:02 +05:30
elif isinstance(msg, bs.HitMessage):
2022-11-02 15:09:34 +05:30
assert self.node
assert msg.force_direction is not None
self.node.handlemessage(
'impulse', msg.pos[0], msg.pos[1], msg.pos[2], msg.velocity[0],
msg.velocity[1], msg.velocity[2], 1.0 * msg.magnitude,
1.0 * msg.velocity_magnitude, msg.radius, 0,
msg.force_direction[0], msg.force_direction[1],
msg.force_direction[2])
# If this hit came from a player, log them as the last to touch us.
s_player = msg.get_source_player(Player)
if s_player is not None:
activity = self._activity()
if activity:
if s_player in activity.players:
self.last_players_to_touch[s_player.team.id] = s_player
else:
super().handlemessage(msg)
2023-07-20 22:19:02 +05:30
class Player(bs.Player['Team']):
2022-11-02 15:09:34 +05:30
"""Our player type for this game."""
2023-07-20 22:19:02 +05:30
class Team(bs.Team[Player]):
2022-11-02 15:09:34 +05:30
"""Our team type for this game."""
def __init__(self) -> None:
self.score = 0
2023-07-20 22:19:02 +05:30
# ba_meta export bascenev1.GameActivity
class HockeyGame(bs.TeamGameActivity[Player, Team]):
2022-11-02 15:09:34 +05:30
"""Ice hockey game."""
name = 'Epic Soccer'
description = 'Score some goals.'
available_settings = [
2023-07-20 22:19:02 +05:30
bs.IntSetting(
2022-11-02 15:09:34 +05:30
'Score to Win',
min_value=1,
default=1,
increment=1,
),
2023-07-20 22:19:02 +05:30
bs.IntChoiceSetting(
2022-11-02 15:09:34 +05:30
'Time Limit',
choices=[
('None', 0),
('1 Minute', 60),
('2 Minutes', 120),
('5 Minutes', 300),
('10 Minutes', 600),
('20 Minutes', 1200),
],
default=0,
),
2023-07-20 22:19:02 +05:30
bs.FloatChoiceSetting(
2022-11-02 15:09:34 +05:30
'Respawn Times',
choices=[
('Shorter', 0.1),
('Short', 0.5),
('Normal', 1.0),
('Long', 2.0),
('Longer', 4.0),
],
default=1.0,
),
]
2023-07-20 22:19:02 +05:30
default_music = bs.MusicType.HOCKEY
2022-11-02 15:09:34 +05:30
@classmethod
2023-07-20 22:19:02 +05:30
def supports_session_type(cls, sessiontype: Type[bs.Session]) -> bool:
return issubclass(sessiontype, bs.DualTeamSession)
2022-11-02 15:09:34 +05:30
@classmethod
2023-07-20 22:19:02 +05:30
def get_supported_maps(cls, sessiontype: Type[bs.Session]) -> List[str]:
assert babase.app.classic is not None
return babase.app.classic.getmaps('football')
2022-11-02 15:09:34 +05:30
def __init__(self, settings: dict):
super().__init__(settings)
shared = SharedObjects.get()
self.slow_motion = True
self._scoreboard = Scoreboard()
2023-07-20 22:19:02 +05:30
self._cheer_sound = bui.getsound('cheer')
self._chant_sound = bui.getsound('crowdChant')
self._foghorn_sound = bui.getsound('foghorn')
self._swipsound = bui.getsound('swip')
self._whistle_sound = bui.getsound('refWhistle')
self.puck_model = bs.getmesh('bomb')
self.puck_tex = bs.gettexture('landMine')
self.puck_scored_tex = bs.gettexture('landMineLit')
self._puck_sound = bs.getsound('metalHit')
self.puck_material = bs.Material()
2022-11-02 15:09:34 +05:30
self.puck_material.add_actions(actions=(('modify_part_collision',
'friction', 0.5)))
self.puck_material.add_actions(conditions=('they_have_material',
shared.pickup_material),
actions=('modify_part_collision',
'collide', True))
self.puck_material.add_actions(
conditions=(
('we_are_younger_than', 100),
'and',
('they_have_material', shared.object_material),
),
actions=('modify_node_collision', 'collide', False),
)
self.puck_material.add_actions(conditions=('they_have_material',
shared.footing_material),
actions=('impact_sound',
self._puck_sound, 0.2, 5))
# Keep track of which player last touched the puck
self.puck_material.add_actions(
conditions=('they_have_material', shared.player_material),
actions=(('call', 'at_connect',
self._handle_puck_player_collide), ))
# We want the puck to kill powerups; not get stopped by them
self.puck_material.add_actions(
conditions=('they_have_material',
PowerupBoxFactory.get().powerup_material),
actions=(('modify_part_collision', 'physical', False),
2023-07-20 22:19:02 +05:30
('message', 'their_node', 'at_connect', bs.DieMessage())))
self._score_region_material = bs.Material()
2022-11-02 15:09:34 +05:30
self._score_region_material.add_actions(
conditions=('they_have_material', self.puck_material),
actions=(('modify_part_collision', 'collide',
True), ('modify_part_collision', 'physical', False),
('call', 'at_connect', self._handle_score)))
self._puck_spawn_pos: Optional[Sequence[float]] = None
2023-07-20 22:19:02 +05:30
self._score_regions: Optional[List[bs.NodeActor]] = None
2022-11-02 15:09:34 +05:30
self._puck: Optional[Puck] = None
self._score_to_win = int(settings['Score to Win'])
self._time_limit = float(settings['Time Limit'])
def get_instance_description(self) -> Union[str, Sequence]:
if self._score_to_win == 1:
return 'Score a goal.'
return 'Score ${ARG1} goals.', self._score_to_win
def get_instance_description_short(self) -> Union[str, Sequence]:
if self._score_to_win == 1:
return 'score a goal'
return 'score ${ARG1} goals', self._score_to_win
def on_begin(self) -> None:
super().on_begin()
self.setup_standard_time_limit(self._time_limit)
self.setup_standard_powerup_drops()
self._puck_spawn_pos = self.map.get_flag_position(None)
self._spawn_puck()
# Set up the two score regions.
defs = self.map.defs
self._score_regions = []
self._score_regions.append(
2023-07-20 22:19:02 +05:30
bs.NodeActor(
bs.newnode('region',
2022-11-02 15:09:34 +05:30
attrs={
'position': defs.boxes['goal1'][0:3],
'scale': defs.boxes['goal1'][6:9],
'type': 'box',
'materials': [self._score_region_material]
})))
self._score_regions.append(
2023-07-20 22:19:02 +05:30
bs.NodeActor(
bs.newnode('region',
2022-11-02 15:09:34 +05:30
attrs={
'position': defs.boxes['goal2'][0:3],
'scale': defs.boxes['goal2'][6:9],
'type': 'box',
'materials': [self._score_region_material]
})))
self._update_scoreboard()
2023-07-20 22:19:02 +05:30
self._chant_sound.play()
2022-11-02 15:09:34 +05:30
def on_team_join(self, team: Team) -> None:
self._update_scoreboard()
def _handle_puck_player_collide(self) -> None:
2023-07-20 22:19:02 +05:30
collision = bs.getcollision()
2022-11-02 15:09:34 +05:30
try:
puck = collision.sourcenode.getdelegate(Puck, True)
player = collision.opposingnode.getdelegate(PlayerSpaz,
True).getplayer(
Player, True)
2023-07-20 22:19:02 +05:30
except bs.NotFoundError:
2022-11-02 15:09:34 +05:30
return
puck.last_players_to_touch[player.team.id] = player
def _kill_puck(self) -> None:
self._puck = None
def _handle_score(self) -> None:
"""A point has been scored."""
assert self._puck is not None
assert self._score_regions is not None
# Our puck might stick around for a second or two
# we don't want it to be able to score again.
if self._puck.scored:
return
2023-07-20 22:19:02 +05:30
region = bs.getcollision().sourcenode
2022-11-02 15:09:34 +05:30
index = 0
for index in range(len(self._score_regions)):
if region == self._score_regions[index].node:
break
for team in self.teams:
if team.id == index:
scoring_team = team
team.score += 1
# Tell all players to celebrate.
for player in team.players:
if player.actor:
2023-07-20 22:19:02 +05:30
player.actor.handlemessage(bs.CelebrateMessage(2.0))
2022-11-02 15:09:34 +05:30
# If we've got the player from the scoring team that last
# touched us, give them points.
if (scoring_team.id in self._puck.last_players_to_touch
and self._puck.last_players_to_touch[scoring_team.id]):
self.stats.player_scored(
self._puck.last_players_to_touch[scoring_team.id],
20,
big_message=True)
# End game if we won.
if team.score >= self._score_to_win:
self.end_game()
2023-07-20 22:19:02 +05:30
self._foghorn_sound.play()
self._cheer_sound.play()
2022-11-02 15:09:34 +05:30
self._puck.scored = True
# Change puck texture to something cool
self._puck.node.color_texture = self.puck_scored_tex
# Kill the puck (it'll respawn itself shortly).
2023-07-20 22:19:02 +05:30
bs.timer(1.0, self._kill_puck)
2022-11-02 15:09:34 +05:30
2023-07-20 22:19:02 +05:30
light = bs.newnode('light',
2022-11-02 15:09:34 +05:30
attrs={
2023-07-20 22:19:02 +05:30
'position': bs.getcollision().position,
2022-11-02 15:09:34 +05:30
'height_attenuated': False,
'color': (1, 0, 0)
})
2023-07-20 22:19:02 +05:30
bs.animate(light, 'intensity', {0: 0, 0.5: 1, 1.0: 0}, loop=True)
bs.timer(1.0, light.delete)
2022-11-02 15:09:34 +05:30
2023-07-20 22:19:02 +05:30
bs.cameraflash(duration=10.0)
2022-11-02 15:09:34 +05:30
self._update_scoreboard()
def end_game(self) -> None:
2023-07-20 22:19:02 +05:30
results = bs.GameResults()
2022-11-02 15:09:34 +05:30
for team in self.teams:
results.set_team_score(team, team.score)
self.end(results=results)
def _update_scoreboard(self) -> None:
winscore = self._score_to_win
for team in self.teams:
self._scoreboard.set_team_value(team, team.score, winscore)
def handlemessage(self, msg: Any) -> Any:
# Respawn dead players if they're still in the game.
2023-07-20 22:19:02 +05:30
if isinstance(msg, bs.PlayerDiedMessage):
2022-11-02 15:09:34 +05:30
# Augment standard behavior...
super().handlemessage(msg)
self.respawn_player(msg.getplayer(Player))
# Respawn dead pucks.
elif isinstance(msg, PuckDiedMessage):
if not self.has_ended():
2023-07-20 22:19:02 +05:30
bs.timer(3.0, self._spawn_puck)
2022-11-02 15:09:34 +05:30
else:
super().handlemessage(msg)
def _flash_puck_spawn(self) -> None:
2023-07-20 22:19:02 +05:30
light = bs.newnode('light',
2022-11-02 15:09:34 +05:30
attrs={
'position': self._puck_spawn_pos,
'height_attenuated': False,
'color': (1, 0, 0)
})
2023-07-20 22:19:02 +05:30
bs.animate(light, 'intensity', {0.0: 0, 0.25: 1, 0.5: 0}, loop=True)
bs.timer(1.0, light.delete)
2022-11-02 15:09:34 +05:30
def _spawn_puck(self) -> None:
2023-07-20 22:19:02 +05:30
self._swipsound.play()
self._whistle_sound.play()
2022-11-02 15:09:34 +05:30
self._flash_puck_spawn()
assert self._puck_spawn_pos is not None
self._puck = Puck(position=self._puck_spawn_pos)