Tidying up last pull request now that ba.Vec3.length() is fixed

This commit is contained in:
Eric Froemling 2020-04-08 19:20:47 -07:00
parent 327880d1e7
commit c7b2315c8b
6 changed files with 43 additions and 54 deletions

View File

@ -69,7 +69,7 @@ from ba._appdelegate import AppDelegate
from ba._apputils import is_browser_likely_available from ba._apputils import is_browser_likely_available
from ba._campaign import Campaign from ba._campaign import Campaign
from ba._gameutils import (animate, animate_array, show_damage_count, from ba._gameutils import (animate, animate_array, show_damage_count,
sharedobj, timestring, cameraflash, distance) sharedobj, timestring, cameraflash)
from ba._general import WeakCall, Call from ba._general import WeakCall, Call
from ba._level import Level from ba._level import Level
from ba._lobby import Lobby, Chooser from ba._lobby import Lobby, Chooser

View File

@ -22,13 +22,12 @@
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
import math
import _ba import _ba
from ba._enums import TimeType, TimeFormat, SpecialChar from ba._enums import TimeType, TimeFormat, SpecialChar
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Any, Dict, Sequence, Tuple from typing import Any, Dict, Sequence
import ba import ba
TROPHY_CHARS = { TROPHY_CHARS = {
@ -47,14 +46,6 @@ def get_trophy_string(trophy_id: str) -> str:
return _ba.charstr(TROPHY_CHARS[trophy_id]) return _ba.charstr(TROPHY_CHARS[trophy_id])
return '?' return '?'
def distance(vec1: Tuple[float, float, float],
vec2: Tuple[float, float, float]) -> float:
"""Find distance between two positions"""
xlen = vec1[0] - vec2[0]
ylen = vec1[1] - vec2[1]
zlen = vec1[2] - vec2[2]
xylen = math.sqrt(xlen**2 + ylen**2)
return math.sqrt(xylen**2 + zlen**2)
def sharedobj(name: str) -> Any: def sharedobj(name: str) -> Any:
"""Return a predefined object for the current Activity, creating if needed. """Return a predefined object for the current Activity, creating if needed.

View File

@ -126,21 +126,19 @@ class PlayerSpaz(Spaz):
def player(self) -> ba.Player: def player(self) -> ba.Player:
"""The ba.Player associated with this Spaz. """The ba.Player associated with this Spaz.
If the player no longer exists, raises an Exception. If the player no longer exists, raises an ba.PlayerNotFoundError.
""" """
player = self._player if not self._player:
if not player: raise ba.PlayerNotFoundError()
raise Exception("player no longer exists") return self._player
return player
def getplayer(self) -> Optional[ba.Player]: def getplayer(self) -> Optional[ba.Player]:
"""Get the ba.Player associated with this Spaz. """Get the ba.Player associated with this Spaz.
Note that this may return None or an invalidated ba.Player, Note that this may return None if the player has left.
so always test it with 'if playerval' before using it to
cover both cases.
""" """
return self._player # Convert invalid references to None.
return self._player if self._player else None
def connect_controls_to_player(self, def connect_controls_to_player(self,
enable_jump: bool = True, enable_jump: bool = True,

View File

@ -28,7 +28,6 @@ import weakref
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
import ba import ba
from ba import distance
from bastd.actor import spaz as basespaz from bastd.actor import spaz as basespaz
if TYPE_CHECKING: if TYPE_CHECKING:
@ -42,6 +41,7 @@ DEFAULT_BOT_HIGHLIGHT = (0.1, 0.3, 0.1)
PRO_BOT_COLOR = (1.0, 0.2, 0.1) PRO_BOT_COLOR = (1.0, 0.2, 0.1)
PRO_BOT_HIGHLIGHT = (0.6, 0.1, 0.05) PRO_BOT_HIGHLIGHT = (0.6, 0.1, 0.05)
class SpazBotPunchedMessage: class SpazBotPunchedMessage:
"""A message saying a ba.SpazBot got punched. """A message saying a ba.SpazBot got punched.
@ -192,9 +192,8 @@ class SpazBot(basespaz.Spaz):
closest = None closest = None
assert self._player_pts is not None assert self._player_pts is not None
for plpt, plvel in self._player_pts: for plpt, plvel in self._player_pts:
dist = distance( dist = (plpt - botpt).length()
(plpt.x, plpt.y, plpt.z),
(botpt.x, botpt.y, botpt.z))
# Ignore player-points that are significantly below the bot # Ignore player-points that are significantly below the bot
# (keeps bots from following players off cliffs). # (keeps bots from following players off cliffs).
if (closest_dist is None if (closest_dist is None
@ -256,10 +255,8 @@ class SpazBot(basespaz.Spaz):
assert self.target_flag.node assert self.target_flag.node
target_pt_raw = ba.Vec3(*self.target_flag.node.position) target_pt_raw = ba.Vec3(*self.target_flag.node.position)
diff = (target_pt_raw - our_pos) diff = (target_pt_raw - our_pos)
diff = ba.Vec3(diff[0], 0, diff[2]) # don't care about y diff = ba.Vec3(diff[0], 0, diff[2]) # Don't care about y.
dist = distance( dist = diff.length()
(target_pt_raw.x, 0, target_pt_raw.z),
(our_pos.x, 0, our_pos.z))
to_target = diff.normalized() to_target = diff.normalized()
# If we're holding some non-flag item, drop it. # If we're holding some non-flag item, drop it.
@ -327,9 +324,7 @@ class SpazBot(basespaz.Spaz):
target_vel * dist_raw * 0.3 * self._lead_amount) target_vel * dist_raw * 0.3 * self._lead_amount)
diff = (target_pt - our_pos) diff = (target_pt - our_pos)
dist = distance( dist = diff.length()
(target_pt.x, target_pt.y, target_pt.z),
(our_pos.x, our_pos.y, our_pos.z))
to_target = diff.normalized() to_target = diff.normalized()
if self._mode == 'throw': if self._mode == 'throw':

View File

@ -150,7 +150,7 @@ class AssaultGame(ba.TeamGameActivity):
def handlemessage(self, msg: Any) -> Any: def handlemessage(self, msg: Any) -> Any:
if isinstance(msg, playerspaz.PlayerSpazDeathMessage): if isinstance(msg, playerspaz.PlayerSpazDeathMessage):
super().handlemessage(msg) # augment standard super().handlemessage(msg) # Augment standard.
self.respawn_player(msg.spaz.player) self.respawn_player(msg.spaz.player)
else: else:
super().handlemessage(msg) super().handlemessage(msg)
@ -167,11 +167,14 @@ class AssaultGame(ba.TeamGameActivity):
ba.timer(length, light.delete) ba.timer(length, light.delete)
def _handle_base_collide(self, team: ba.Team) -> None: def _handle_base_collide(self, team: ba.Team) -> None:
cval = ba.get_collision_info('opposing_node')
try: # Attempt to pull a living ba.Player from what we hit.
player = cval.getdelegate().getplayer() cnode = ba.get_collision_info('opposing_node')
except Exception: assert isinstance(cnode, ba.Node)
actor = cnode.getdelegate()
if not isinstance(actor, playerspaz.PlayerSpaz):
return return
player = actor.getplayer()
if not player or not player.is_alive(): if not player or not player.is_alive():
return return
@ -190,20 +193,21 @@ class AssaultGame(ba.TeamGameActivity):
# and add flashes of light so its noticeable. # and add flashes of light so its noticeable.
for player in player_team.players: for player in player_team.players:
if player.is_alive(): if player.is_alive():
pos = player.actor.node.position if player.node:
light = ba.newnode('light', pos = player.node.position
attrs={ light = ba.newnode('light',
'position': pos, attrs={
'color': player_team.color, 'position': pos,
'height_attenuated': False, 'color': player_team.color,
'radius': 0.4 'height_attenuated': False,
}) 'radius': 0.4
ba.timer(0.5, light.delete) })
ba.animate(light, 'intensity', { ba.timer(0.5, light.delete)
0: 0, ba.animate(light, 'intensity', {
0.1: 1.0, 0: 0,
0.5: 0 0.1: 1.0,
}) 0.5: 0
})
new_pos = (self.map.get_start_position( new_pos = (self.map.get_start_position(
player_team.get_id())) player_team.get_id()))
@ -220,8 +224,10 @@ class AssaultGame(ba.TeamGameActivity):
0.1: 1.0, 0.1: 1.0,
0.5: 0 0.5: 0
}) })
player.actor.handlemessage( if player.actor:
ba.StandMessage(new_pos, random.uniform(0, 360))) player.actor.handlemessage(
ba.StandMessage(new_pos,
random.uniform(0, 360)))
# Have teammates celebrate. # Have teammates celebrate.
for player in player_team.players: for player in player_team.players:

View File

@ -487,8 +487,7 @@ class CaptureTheFlagGame(ba.TeamGameActivity):
self.respawn_player(msg.spaz.player) self.respawn_player(msg.spaz.player)
elif isinstance(msg, stdflag.FlagDeathMessage): elif isinstance(msg, stdflag.FlagDeathMessage):
assert isinstance(msg.flag, CTFFlag) assert isinstance(msg.flag, CTFFlag)
ba.timer(0.1, ba.timer(0.1, ba.Call(self._spawn_flag_for_team, msg.flag.team))
ba.Call(self._spawn_flag_for_team, msg.flag.team))
elif isinstance(msg, stdflag.FlagPickedUpMessage): elif isinstance(msg, stdflag.FlagPickedUpMessage):
# Store the last player to hold the flag for scoring purposes. # Store the last player to hold the flag for scoring purposes.
assert isinstance(msg.flag, CTFFlag) assert isinstance(msg.flag, CTFFlag)