From 332a3fd9b465324a745b46030c9cb9572dc2abbc Mon Sep 17 00:00:00 2001 From: Jeremy Saklad Date: Sat, 24 Aug 2024 13:59:54 -0500 Subject: [PATCH] refactor: Use stream composition for firing ProtoMech main/arm guns --- .../common/actions/WeaponAttackAction.java | 33 +++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/megamek/src/megamek/common/actions/WeaponAttackAction.java b/megamek/src/megamek/common/actions/WeaponAttackAction.java index 7016151439..0a9360a9c2 100644 --- a/megamek/src/megamek/common/actions/WeaponAttackAction.java +++ b/megamek/src/megamek/common/actions/WeaponAttackAction.java @@ -2437,21 +2437,28 @@ private static String toHitIsImpossible(Game game, Entity ae, int attackerId, Ta } // Protomechs cannot fire arm weapons and main gun in the same turn - if ((ae instanceof Protomech) - && ((weapon.getLocation() == Protomech.LOC_MAINGUN) - || (weapon.getLocation() == Protomech.LOC_RARM) - || (weapon.getLocation() == Protomech.LOC_LARM))) { - final boolean firingMainGun = weapon.getLocation() == Protomech.LOC_MAINGUN; - for (EntityAction ea : game.getActionsVector()) { - if ((ea.getEntityId() == attackerId) && (ea instanceof WeaponAttackAction)) { - WeaponAttackAction otherWAA = (WeaponAttackAction) ea; - final Mounted otherWeapon = ae.getEquipment(otherWAA.getWeaponId()); - if ((firingMainGun && ((otherWeapon.getLocation() == Protomech.LOC_RARM) - || (otherWeapon.getLocation() == Protomech.LOC_LARM))) - || !firingMainGun && (otherWeapon.getLocation() == Protomech.LOC_MAINGUN)) { + if (ae instanceof Protomech) { + // A lazy stream that evaluates to the locations of weapons already fired by the attacker. + IntStream firedWeaponLocations = game.getActionsVector().stream() + .filter(ea -> ea.getEntityId() == attackerId) + .filter(WeaponAttackAction.class::isInstance) + .map(WeaponAttackAction.class::cast) + .map(otherWAA -> ae.getEquipment(otherWAA.getWeaponId())) + .mapToInt(Mounted::getLocation); + + switch (weapon.getLocation()) { + case Protomech.LOC_MAINGUN: + if (firedWeaponLocations.anyMatch(otherWeaponLocation -> + otherWeaponLocation == Protomech.LOC_LARM || otherWeaponLocation == Protomech.LOC_RARM + )) { + return Messages.getString("WeaponAttackAction.CantFireArmsAndMainGun"); + } + break; + case Protomech.LOC_LARM: + case Protomech.LOC_RARM: + if (firedWeaponLocations.anyMatch(otherWeaponLocation -> otherWeaponLocation == Protomech.LOC_MAINGUN)) { return Messages.getString("WeaponAttackAction.CantFireArmsAndMainGun"); } - } } }