Skip to content

Commit

Permalink
refactor: Use stream composition for firing BA tasers/Narcs
Browse files Browse the repository at this point in the history
This section of code specifically checks whether a BA squad has already
fired a taser or Narc at a different target.
  • Loading branch information
Saklad5 committed Aug 22, 2024
1 parent f45da84 commit e2bacbf
Showing 1 changed file with 18 additions and 16 deletions.
34 changes: 18 additions & 16 deletions megamek/src/megamek/common/actions/WeaponAttackAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -1906,23 +1906,25 @@ private static String toHitIsImpossible(Game game, Entity ae, int attackerId, Ta
&& (wtype.hasFlag(WeaponType.F_TASER) || wtype.getAmmoType() == AmmoType.T_NARC)) {
// Go through all of the current actions to see if a NARC or Taser
// has been fired
for (Enumeration<EntityAction> i = game.getActions(); i.hasMoreElements();) {
Object o = i.nextElement();
if (!(o instanceof WeaponAttackAction)) {
continue;

// A lazy stream that evaluates to the weapon types this entity has already fired at other targets.
Stream<WeaponType> diffTargetWeaponTypes = game.getActionsVector().stream()
.filter(WeaponAttackAction.class::isInstance)
.map(WeaponAttackAction.class::cast)
.filter(prevAttack ->
// Is this an attack from this entity to a different target?
prevAttack.getEntityId() == ae.getId() && prevAttack.getTargetId() != target.getId()
)
.map(prevAttack -> (WeaponType) ae.getEquipment(prevAttack.getWeaponId()).getType());

if (wtype.hasFlag(WeaponType.F_TASER)) {
if (diffTargetWeaponTypes.anyMatch(prevWtype -> prevWtype.hasFlag(WeaponType.F_TASER))) {
return Messages.getString("WeaponAttackAction.BATaserSameTarget");
}
WeaponAttackAction prevAttack = (WeaponAttackAction) o;
// Is this an attack from this entity to a different target?
if (prevAttack.getEntityId() == ae.getId() && prevAttack.getTargetId() != target.getId()) {
Mounted prevWeapon = ae.getEquipment(prevAttack.getWeaponId());
WeaponType prevWtype = (WeaponType) prevWeapon.getType();
if (prevWeapon.getType().hasFlag(WeaponType.F_TASER)
&& weapon.getType().hasFlag(WeaponType.F_TASER)) {
return Messages.getString("WeaponAttackAction.BATaserSameTarget");
}
if (prevWtype.getAmmoType() == AmmoType.T_NARC && wtype.getAmmoType() == AmmoType.T_NARC) {
return Messages.getString("WeaponAttackAction.BANarcSameTarget");
}
} else {
assert wtype.getAmmoType() == AmmoType.T_NARC;
if (diffTargetWeaponTypes.anyMatch(prevWtype -> prevWtype.getAmmoType() == AmmoType.T_NARC)) {
return Messages.getString("WeaponAttackAction.BANarcSameTarget");
}
}
}
Expand Down

0 comments on commit e2bacbf

Please sign in to comment.