From e2bacbf189fae3d5210811439d48d256ac2351dd Mon Sep 17 00:00:00 2001 From: Jeremy Saklad Date: Thu, 22 Aug 2024 08:48:04 -0500 Subject: [PATCH] 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. --- .../common/actions/WeaponAttackAction.java | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/megamek/src/megamek/common/actions/WeaponAttackAction.java b/megamek/src/megamek/common/actions/WeaponAttackAction.java index 655f0b2b603..e18efca9317 100644 --- a/megamek/src/megamek/common/actions/WeaponAttackAction.java +++ b/megamek/src/megamek/common/actions/WeaponAttackAction.java @@ -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 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 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"); } } }