From c3b03f65969b456fb16fe8d444c6f5dcf0475114 Mon Sep 17 00:00:00 2001 From: Jeremy Saklad Date: Sat, 24 Aug 2024 07:33:17 -0500 Subject: [PATCH] refactor: Use stream composition for firing field guns It may be possible to optimize this further if it can be assumed that all CI attacks either have the infantry flag or are field guns, but I've settled for replicating the previous logic for now. --- .../common/actions/WeaponAttackAction.java | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/megamek/src/megamek/common/actions/WeaponAttackAction.java b/megamek/src/megamek/common/actions/WeaponAttackAction.java index e18efca931..893c3b4594 100644 --- a/megamek/src/megamek/common/actions/WeaponAttackAction.java +++ b/megamek/src/megamek/common/actions/WeaponAttackAction.java @@ -2168,21 +2168,23 @@ private static String toHitIsImpossible(Game game, Entity ae, int attackerId, Ta return Messages.getString("WeaponAttackAction.CantMoveAndFieldGun"); } // check for mixing infantry and field gun attacks - for (Enumeration i = game.getActions(); i.hasMoreElements();) { - EntityAction ea = i.nextElement(); - if (!(ea instanceof WeaponAttackAction)) { - continue; - } - final WeaponAttackAction prevAttack = (WeaponAttackAction) ea; - if (prevAttack.getEntityId() == attackerId) { - Mounted prevWeapon = ae.getEquipment(prevAttack.getWeaponId()); - if ((prevWeapon.getType().hasFlag(WeaponType.F_INFANTRY) - && (weapon.getLocation() == Infantry.LOC_FIELD_GUNS)) - || (weapon.getType().hasFlag(WeaponType.F_INFANTRY) - && (prevWeapon.getLocation() == Infantry.LOC_FIELD_GUNS))) { - return Messages.getString("WeaponAttackAction.FieldGunOrSAOnly"); - } - } + if (game.getActionsVector().stream() + .filter(WeaponAttackAction.class::isInstance) + .map(WeaponAttackAction.class::cast) + .filter(prevAttack -> prevAttack.getEntityId() == attackerId) + .map(prevAttack -> ae.getEquipment(prevAttack.getWeaponId())) + .anyMatch(prevWeapon -> + ( + prevWeapon.getType().hasFlag(WeaponType.F_INFANTRY) + && weapon.getLocation() == Infantry.LOC_FIELD_GUNS + ) + || ( + prevWeapon.getLocation() == Infantry.LOC_FIELD_GUNS + && weapon.getType().hasFlag(WeaponType.F_INFANTRY) + ) + ) + ) { + return Messages.getString("WeaponAttackAction.FieldGunOrSAOnly"); } }