Skip to content

Commit 4df8c8c

Browse files
committed
refactor: Use stream composition for firing BA tasers/Narcs
This section of code specifically checks whether a BA squad has already fired a taser or Narc at a different target.
1 parent f45da84 commit 4df8c8c

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

megamek/src/megamek/common/actions/WeaponAttackAction.java

+18-16
Original file line numberDiff line numberDiff line change
@@ -1906,23 +1906,25 @@ private static String toHitIsImpossible(Game game, Entity ae, int attackerId, Ta
19061906
&& (wtype.hasFlag(WeaponType.F_TASER) || wtype.getAmmoType() == AmmoType.T_NARC)) {
19071907
// Go through all of the current actions to see if a NARC or Taser
19081908
// has been fired
1909-
for (Enumeration<EntityAction> i = game.getActions(); i.hasMoreElements();) {
1910-
Object o = i.nextElement();
1911-
if (!(o instanceof WeaponAttackAction)) {
1912-
continue;
1909+
1910+
// A lazy stream that evaluates to the weapon types this entity has already fired at other targets.
1911+
Stream<WeaponType> diffTargetWeaponTypes = game.getActionsVector().stream()
1912+
.filter(WeaponAttackAction.class::isInstance)
1913+
.map(WeaponAttackAction.class::cast)
1914+
.filter(prevAttack ->
1915+
// Is this an attack from this entity to a different target?
1916+
prevAttack.getEntityId() == ae.getId() && prevAttack.getTargetId() != target.getId()
1917+
)
1918+
.map(prevAttack -> ae.getEquipment(prevAttack.getWeaponId()).getType());
1919+
1920+
if (wtype.hasFlag(WeaponType.F_TASER)) {
1921+
if (diffTargetWeaponTypes.anyMatch(prevWtype -> prevWtype.hasFlag(WeaponType.F_TASER))) {
1922+
return Messages.getString("WeaponAttackAction.BATaserSameTarget");
19131923
}
1914-
WeaponAttackAction prevAttack = (WeaponAttackAction) o;
1915-
// Is this an attack from this entity to a different target?
1916-
if (prevAttack.getEntityId() == ae.getId() && prevAttack.getTargetId() != target.getId()) {
1917-
Mounted prevWeapon = ae.getEquipment(prevAttack.getWeaponId());
1918-
WeaponType prevWtype = (WeaponType) prevWeapon.getType();
1919-
if (prevWeapon.getType().hasFlag(WeaponType.F_TASER)
1920-
&& weapon.getType().hasFlag(WeaponType.F_TASER)) {
1921-
return Messages.getString("WeaponAttackAction.BATaserSameTarget");
1922-
}
1923-
if (prevWtype.getAmmoType() == AmmoType.T_NARC && wtype.getAmmoType() == AmmoType.T_NARC) {
1924-
return Messages.getString("WeaponAttackAction.BANarcSameTarget");
1925-
}
1924+
} else {
1925+
assert wtype.getAmmoType() == AmmoType.T_NARC;
1926+
if (diffTargetWeaponTypes.anyMatch(prevWtype -> prevWtype.getAmmoType() == AmmoType.T_NARC)) {
1927+
return Messages.getString("WeaponAttackAction.BANarcSameTarget");
19261928
}
19271929
}
19281930
}

0 commit comments

Comments
 (0)