From e0664065db6bdc2ec7ea6d93c592775fb47fdd01 Mon Sep 17 00:00:00 2001 From: Jeremy Saklad Date: Sat, 24 Aug 2024 11:14:04 -0500 Subject: [PATCH] refactor: Use stream composition when checking for previously-fired solo weapons --- .../common/actions/WeaponAttackAction.java | 35 ++++++++----------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/megamek/src/megamek/common/actions/WeaponAttackAction.java b/megamek/src/megamek/common/actions/WeaponAttackAction.java index 893c3b4594a..da8f4bd6e90 100644 --- a/megamek/src/megamek/common/actions/WeaponAttackAction.java +++ b/megamek/src/megamek/common/actions/WeaponAttackAction.java @@ -2408,26 +2408,21 @@ private static String toHitIsImpossible(Game game, Entity ae, int attackerId, Ta // Some weapons can only be fired by themselves // Check to see if another solo weapon was fired - boolean hasSoloAttack = false; - String soloWeaponName = ""; - for (EntityAction ea : game.getActionsVector()) { - if ((ea.getEntityId() == attackerId) && (ea instanceof WeaponAttackAction)) { - WeaponAttackAction otherWAA = (WeaponAttackAction) ea; - final Mounted otherWeapon = ae.getEquipment(otherWAA.getWeaponId()); - - if (!(otherWeapon.getType() instanceof WeaponType)) { - continue; - } - final WeaponType otherWtype = (WeaponType) otherWeapon.getType(); - hasSoloAttack |= (otherWtype.hasFlag(WeaponType.F_SOLO_ATTACK) && otherWAA.getWeaponId() != weaponId); - if (hasSoloAttack) { - soloWeaponName = otherWeapon.getName(); - break; - } - } - } - if (hasSoloAttack) { - return String.format(Messages.getString("WeaponAttackAction.CantFireWithOtherWeapons"), soloWeaponName); + + // The name of a solo weapon that has already been fired, if one exists. + Optional soloWeaponName = game.getActionsVector().stream() + .filter(prevAttack -> prevAttack.getEntityId() == attackerId) + .filter(WeaponAttackAction.class::isInstance) + .map(WeaponAttackAction.class::cast) + .map(WeaponAttackAction::getWeaponId) + .filter(otherWAAId -> otherWAAId != weaponId) + .map(otherWAAId -> ae.getEquipment(otherWAAId)) + .filter(otherWeapon -> otherWeapon.getType().hasFlag(WeaponType.F_SOLO_ATTACK)) + .map(Mounted::getName) + .findAny(); + + if (soloWeaponName.isPresent()) { + return String.format(Messages.getString("WeaponAttackAction.CantFireWithOtherWeapons"), soloWeaponName.orElseThrow()); } // Handle solo attack weapons.