CivilWar/src/combat_engine.cpp

src / combat_engine.cpp

src/combat_engine.cpp · 157.2 KB

#include <algorithm>
#include <array>
#include <cctype>
#include <charconv>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>

#include "combat_engine.hpp"

#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif

namespace civil_war {

constexpr int kDisobedienceThreshold = 25;
constexpr int kBmpSeats = 10;

std::string trim(std::string_view value) {
    const auto first = value.find_first_not_of(" \t\r\n");
    if (first == std::string_view::npos) {
        return {};
    }
    const auto last = value.find_last_not_of(" \t\r\n");
    return std::string(value.substr(first, last - first + 1));
}

std::string uppercase(std::string value) {
    for (char& character : value) {
        character = static_cast<char>(
            std::toupper(static_cast<unsigned char>(character)));
    }
    return value;
}

class SplitMix64 {
public:
    explicit SplitMix64(std::uint64_t seed) : state_(seed) {}

    std::uint64_t next() {
        state_ += 0x9E3779B97F4A7C15ULL;
        std::uint64_t value = state_;
        value = (value ^ (value >> 30U)) * 0xBF58476D1CE4E5B9ULL;
        value = (value ^ (value >> 27U)) * 0x94D049BB133111EBULL;
        return value ^ (value >> 31U);
    }

    int below(int upper) {
        if (upper <= 0) {
            return 0;
        }
        const auto bound = static_cast<std::uint64_t>(upper);
        const std::uint64_t limit =
            std::numeric_limits<std::uint64_t>::max() -
            (std::numeric_limits<std::uint64_t>::max() % bound);
        std::uint64_t value = next();
        while (value >= limit) {
            value = next();
        }
        return static_cast<int>(value % bound);
    }

    int inclusive(int first, int last) {
        return first + below(last - first + 1);
    }

private:
    std::uint64_t state_;
};

std::string locationName(Location location) {
    switch (location) {
    case Location::Approach:
        return "接近路";
    case Location::Roadblock:
        return "路障";
    case Location::Beyond:
        return "路障后方";
    }
    return "未知";
}

int locationIndex(Location location) {
    return static_cast<int>(location);
}

Location locationFromIndex(int index) {
    return static_cast<Location>(std::clamp(index, 0, 2));
}

std::string factionName(FactionId faction) {
    switch (faction) {
    case FactionId::ArmedCivilians: return "武装平民";
    case FactionId::Mvd: return "内务部";
    case FactionId::YeltsinSupporters: return "亲叶利钦支持者";
    case FactionId::CommitteeArmy: return "紧急状态委员会军队";
    }
    return "未知阵营";
}

std::string dispositionName(Disposition disposition) {
    return disposition == Disposition::Friendly ? "与车组协同" : "与车组敌对";
}

std::string endingName(Ending ending) {
    switch (ending) {
    case Ending::Defeat: return "车组失能(defeat)";
    case Ending::Withdrawal: return "有序撤离(withdrawal)";
    case Ending::NegotiatedPassage: return "谈判通行(negotiated_passage)";
    case Ending::RoadblockResolved: return "敌对武装退出(encounter_resolved)";
    case Ending::ForcedPassage: return "强行突破(forced_passage)";
    case Ending::Stalemate: return "对峙中止(stalemate)";
    case Ending::None: return "未结算";
    }
    return "未结算";
}

GameState::GameState() {
        friendly.push_back(
            {"C1", "车长", "车长 / 玩家控制", "AKS-74U、马卡洛夫手枪、装甲兵装备",
             100, 100, 0, Location::Approach, true, false, false, false, "", false, ""});
        friendly.push_back(
            {"G1", "炮手", "炮手 / 导弹操作员", "AKS-74U、常规装甲兵装备、BMP-2 炮塔",
             100, 100, 0, Location::Approach, true, false, false, false, "", false, ""});
        friendly.push_back(
            {"D1", "驾驶员", "驾驶员 / 车体机动", "AKS-74U、常规装甲兵装备、BMP-2 驾驶席",
             100, 100, 0, Location::Approach, true, false, false, false, "", false, ""});
        friendly.push_back(
            {"M1", "机枪手", "随车机枪手", "PKM、SSh-60、M88 野战服",
             100, 100, 0, Location::Approach, true, false, false, false, "", false, ""});

        enemies.push_back(
            {"CIV-1", "武装平民甲", UnitProfile::ArmedCivilian,
             FactionId::ArmedCivilians, Disposition::Hostile, "旧式步枪",
             100, 45, 72, 0, 0, Location::Roadblock, false, false,
             EnemyStatus::Active, false, "wooden_barricade"});
        enemies.push_back(
            {"CIV-2", "武装平民乙", UnitProfile::ArmedCivilian,
             FactionId::ArmedCivilians, Disposition::Hostile, "旧式步枪",
             100, 48, 66, 0, 0, Location::Roadblock, false, false,
             EnemyStatus::Active, false, ""});
        enemies.push_back(
            {"CIV-3", "武装平民丙", UnitProfile::ArmedCivilian,
             FactionId::ArmedCivilians, Disposition::Hostile,
             "旧式步枪、燃烧瓶", 100, 42, 75, 0, 1, Location::Roadblock,
             false, false, EnemyStatus::Active, false, ""});
        enemies.push_back(
            {"MVD-1", "内务部警察一", UnitProfile::MvdOfficer,
             FactionId::Mvd, Disposition::Hostile, "手枪",
             100, 68, 58, 0, 0, Location::Roadblock, true, false,
             EnemyStatus::Active, false, "police_car"});
        enemies.push_back(
            {"MVD-2", "内务部警察二", UnitProfile::MvdOfficer,
             FactionId::Mvd, Disposition::Hostile, "手枪",
             100, 65, 63, 0, 0, Location::Roadblock, true, false,
             EnemyStatus::Active, false, "police_car"});
}

struct ActionChoice {
    Action action;
    std::string label;
    int direction = 0;
};

struct TargetChoice {
    bool policeCar = false;
    bool woodenCover = false;
    std::size_t enemyIndex = 0;
};

enum class NameOrigin { Ukrainian, Russian, Belarusian };

std::string originName(NameOrigin origin) {
    switch (origin) {
    case NameOrigin::Ukrainian: return "乌克兰";
    case NameOrigin::Russian: return "俄罗斯";
    case NameOrigin::Belarusian: return "白俄罗斯";
    }
    return "苏联";
}

std::string generateCrewName(NameOrigin origin, SplitMix64& rng) {
    static const std::vector<std::string> ukrainianGiven = {
        "Олександр", "Андрій", "Микола", "Сергій", "Володимир", "Іван",
        "Богдан", "Олексій", "Петро", "Юрій"};
    static const std::vector<std::string> ukrainianPatronymic = {
        "Миколайович", "Андрійович", "Сергійович", "Іванович",
        "Володимирович", "Петрович", "Юрійович", "Олександрович"};
    static const std::vector<std::string> ukrainianFamily = {
        "Коваленко", "Шевченко", "Бондаренко", "Марченко", "Ткачук",
        "Мельник", "Кравченко", "Бойко", "Лисенко", "Ковальчук"};
    static const std::vector<std::string> russianGiven = {
        "Александр", "Сергей", "Михаил", "Николай", "Владимир", "Дмитрий",
        "Павел", "Игорь", "Алексей", "Виктор"};
    static const std::vector<std::string> russianPatronymic = {
        "Сергеевич", "Николаевич", "Владимирович", "Михайлович",
        "Александрович", "Иванович", "Петрович", "Дмитриевич"};
    static const std::vector<std::string> russianFamily = {
        "Морозов", "Кузнецов", "Соколов", "Орлов", "Григорьев",
        "Фёдоров", "Васильев", "Смирнов", "Зайцев", "Попов"};
    static const std::vector<std::string> belarusianGiven = {
        "Аляксей", "Мікалай", "Андрэй", "Сяргей", "Іван", "Уладзімір",
        "Павел", "Юрый", "Багдан", "Віктар"};
    static const std::vector<std::string> belarusianPatronymic = {
        "Мікалаевіч", "Андрэевіч", "Сяргеевіч", "Іванавіч",
        "Уладзіміравіч", "Пятровіч", "Юр'евіч", "Аляксандравіч"};
    static const std::vector<std::string> belarusianFamily = {
        "Кавальчук", "Сідарук", "Карпенка", "Марозаў", "Каваленка",
        "Грышка", "Бандарэнка", "Пятроў", "Сакалоў", "Шаўчэнка"};

    const auto pick = [&rng](const std::vector<std::string>& values) -> const std::string& {
        return values[static_cast<std::size_t>(rng.below(
            static_cast<int>(values.size())))];
    };
    if (origin == NameOrigin::Ukrainian) {
        return pick(ukrainianGiven) + " " + pick(ukrainianPatronymic) + " " +
               pick(ukrainianFamily);
    }
    if (origin == NameOrigin::Belarusian) {
        return pick(belarusianGiven) + " " + pick(belarusianPatronymic) + " " +
               pick(belarusianFamily);
    }
    return pick(russianGiven) + " " + pick(russianPatronymic) + " " +
           pick(russianFamily);
}

void assignCrewNames(GameState& state, std::uint64_t seed) {
    SplitMix64 nameRng(seed ^ 0x6A09E667F3BCC909ULL);
    const std::array<NameOrigin, 4> origins = {
        NameOrigin::Ukrainian,
        NameOrigin::Russian,
        nameRng.below(2) == 0 ? NameOrigin::Russian : NameOrigin::Ukrainian,
        nameRng.below(2) == 0 ? NameOrigin::Belarusian : NameOrigin::Russian};
    for (std::size_t index = 0; index < state.friendly.size(); ++index) {
        FriendlyPerson& person = state.friendly[index];
        person.name = generateCrewName(origins[index], nameRng);
        person.nationality = originName(origins[index]);
    }
}

GameState makeDefaultCheckpoint(std::uint64_t seed) {
    GameState state;
    assignCrewNames(state, seed);
    return state;
}

class Game {
public:
    Game(EncounterConfig config, std::istream& input, std::ostream& output)
        : rng_(config.seed),
          input_(input),
          output_(output),
          state_(std::move(config.state)),
          config_(std::move(config)),
          seedForDisplay_(config_.seed) {
        if (config_.roundLimit <= 0) {
            config_.roundLimit = kDefaultRoundLimit;
        }
    }

    CombatResult runLegacyEncounter() {
        if (config_.standardBriefing) {
            printIntroduction();
        } else if (!config_.encounterTitle.empty()) {
            output_ << "\n============================================================\n"
                    << "  " << config_.encounterTitle << " · 共享逐人战斗\n"
                    << "============================================================\n";
        }
        while (!state_.ended()) {
            beginRound();
            if (!runFriendlyPhase()) {
                output_ << "\n输入已结束,游戏未结算。\n";
                return {state_, state_.completedRounds, true};
            }
            resolveEnemyPhase();
            const CombatRoundResult result = finishRound();
            if (result.inputEnded) {
                return {state_, state_.completedRounds, true};
            }
        }
        return {state_, state_.completedRounds, false};
    }

    void beginRound() {
        for (FriendlyPerson& person : state_.friendly) {
            person.acted = false;
            person.reactionUsed = false;
            person.overwatch = false;
        }
        for (EnemyPerson& enemy : state_.enemies) {
            enemy.reactionUsed = false;
            enemy.acted = false;
        }
        for (FriendlyVehicle& vehicle : state_.combatVehicles) {
            vehicle.acted = false;
            vehicle.moving = false;
        }
        if (state_.policy.ending == EndingPolicy::Legacy) {
            printRoundHeader();
            printAllRosters("第 " + std::to_string(state_.round) + " 轮开始");
        }
    }

    void resolveRoundEnemyPhase() {
        if (state_.policy.ending == EndingPolicy::FreeWaves) {
            resolveSharedEnemyPhase();
        } else {
            resolveEnemyPhase();
        }
    }

    CombatRoundResult finishRound() {
        CombatRoundResult result;
        roundDefeats_.clear();
        if (state_.policy.ending == EndingPolicy::FreeWaves) {
            finishSharedRound();
        } else {
            ++state_.completedRounds;
            checkEndings();
            printAllRosters("敌方行动阶段之后");
            clampState();
            if (state_.ended()) {
                if (config_.standardEnding) {
                    printEnding();
                }
            } else {
                ++state_.round;
            }
        }
        result.completedRounds = state_.completedRounds;
        result.defeats = roundDefeats_;
        return result;
    }

    bool executeFriendlyCommand(const FriendlyCommand& command) {
        return executeSharedFriendlyCommand(command);
    }

    CombatResolution resolveAttack(const AttackRequest& request) {
        return resolveSharedAttack(request);
    }

    CombatResolution resolveAirAttack(const AttackRequest& request) {
        return resolveSharedAirAttack(request);
    }

    bool resolveAntiAir(bool friendlyAir) {
        return resolveSharedAntiAir(friendlyAir);
    }

    GameState& publicState() { return state_; }
    const GameState& publicState() const { return state_; }
    bool runLegacyFriendlyPhase() { return runFriendlyPhase(); }

private:
    void printIntroduction() {
        output_
            << "============================================================\n"
            << "  《路障前的命令》 · 逐人命令版\n"
            << "  架空历史演示 · 莫斯科 · 1991 年 8 月 19 日\n"
            << "============================================================\n\n"
            << "政变消息传遍莫斯科。你是一辆 BMP-2 的车长,出身乌克兰;\n"
            << "妻子和女儿此刻正在基辅。无线电要求你尽快打通前方路口,\n"
            << "同时避免不必要的平民伤亡。\n\n"
            << "现在由你逐人下令。车长、炮手、驾驶员和机枪手各自行动;\n"
            << "车辆与警车是独立资产,九名围观者不是战斗单位。\n"
            << "每名敌人每轮有一次反应或常规行动机会;压制会限制其反应。\n"
            << "和平通行、撤离和解除路障都不是\n"
            << "“消灭全部敌人”的同义词。\n\n"
            << "初始纪律: 85/100。纪律高于 25 时,清晰合法的命令会执行;\n"
            << "只有纪律降至 25 或以下,部分高风险命令才可能以概率被拒绝。\n"
            << "随机种子: " << seedForDisplay_ << "\n\n"
            << "控制: 输入人物 ID 后选择行动编号;输入 q 结束本轮命令阶段。\n"
            << "输入 help 可随时查看这些提示。\n";
    }

    void printRoundHeader() {
        output_ << "\n============================================================\n"
                << "【第 " << state_.round << '/' << config_.roundLimit
                << " 轮 · 玩家命令阶段】\n"
                << "============================================================\n";
        output_ << "当前目标: ";
        if (state_.withdrawalOrdered) {
            output_ << "撤离并让 BMP-2 留在" << config_.sectorLabel << "。\n";
        } else if (missionAgreementRecorded()) {
            output_ << "驶入" << config_.exitLabel
                    << ",兑现双方接受的低速通行安排。\n";
        } else if (!config_.objective.empty()) {
            output_ << config_.objective << '\n';
        } else {
            output_ << "先与一名内务部警察和一名武装平民分别谈成通行安排,"
                    << "再驶入路障后方;也可以撤离或解除武装对峙。\n";
        }
        output_ << "紧张度: " << state_.tension
                << "/100   围观者风险: " << state_.bystanderRisk
                << "/100   组纪律: " << state_.discipline << "/100\n"
                << organizationSummary() << '\n';
        if (state_.discipline > kDisobedienceThreshold) {
            output_ << "命令状态: 正常服从(不同意见可能导致后续纪律变化)。\n";
        } else {
            output_ << "命令状态: 临界纪律(仅高风险命令可能被概率拒绝)。\n";
        }
    }

    std::string organizationSummary() const {
        std::vector<FactionId> factions;
        for (const EnemyPerson& unit : state_.enemies) {
            if (std::find(factions.begin(), factions.end(), unit.faction) ==
                factions.end()) {
                factions.push_back(unit.faction);
            }
        }
        std::string summary = "阵营组织度:";
        for (FactionId faction : factions) {
            summary += " " + factionName(faction) + " " +
                       std::to_string(organizationOf(faction)) +
                       "/100(整体士气 " +
                       std::to_string(factionMoraleOf(faction)) + ")";
        }
        return summary;
    }

    static std::string healthLabel(int health) {
        if (health <= 0) {
            return "失能";
        }
        if (health <= 35) {
            return "重伤";
        }
        if (health < 100) {
            return "受伤";
        }
        return "正常";
    }

    static std::string enemyStatusLabel(const EnemyPerson& enemy) {
        switch (enemy.status) {
        case EnemyStatus::Surrendered:
            return "已投降(终止)";
        case EnemyStatus::Fled:
            return "已逃离(终止)";
        case EnemyStatus::Incapacitated:
            return "已失能(终止)";
        case EnemyStatus::Killed:
            return "已击毙(终止)";
        case EnemyStatus::Active:
            return enemy.health < 100 ? healthLabel(enemy.health) : "正常";
        }
        return "未知";
    }

    std::string coverLabel(const EnemyPerson& enemy,
                           const PoliceCar& policeCar) const {
        if (enemy.coverId == "wooden_barricade") {
            return state_.woodenCover.name + "(易燃)";
        }
        if (enemy.coverId == "police_car") {
            return policeCar.condition <= 0
                       ? policeCar.name + "(已失效)"
                       : policeCar.name + " +" +
                             std::to_string(policeCar.coverReduction()) + "%";
        }
        return "无";
    }

    void printAllRosters(std::string_view heading) {
        output_ << "\n------------------------------------------------------------\n"
                << "【" << heading << " · 人员与资产】\n"
                << "------------------------------------------------------------\n"
                << "【友方人员】\n";
        for (const FriendlyPerson& person : state_.friendly) {
            const std::string position =
                person.mounted ? "车内" : locationName(person.location);
            output_ << "  " << person.id << " " << person.name
                    << " | 生命 " << person.health << "/100("
                    << (person.killed ? "死亡" : healthLabel(person.health)) << ")"
                    << " | " << position
                    << " | " << person.nationality
                    << " | 体力 " << person.stamina
                    << " | 压制 " << person.suppression
                    << (person.coverId.empty() ? "" : " | 掩体 " + person.coverId)
                    << " | " << person.role
                    << " | " << person.equipment;
            if (person.acted) {
                output_ << " | 本轮已行动";
            }
            output_ << '\n';
        }

        const int occupied = static_cast<int>(std::count_if(
            state_.friendly.begin(), state_.friendly.end(),
            [](const FriendlyPerson& person) {
                return person.mounted && person.health > 0;
            }));
        output_ << "\n【友方载具 · 独立资产】\n"
                << "  " << state_.vehicle.name
                << " | 车况 " << state_.vehicle.condition << "/100"
                << " | 位置 " << locationName(state_.vehicle.location)
                << " | "
                << (state_.vehicle.disabled
                        ? "失能"
                        : (state_.vehicle.moving ? "移动中" : "静止"))
                << " | 乘员 " << occupied << '/' << kBmpSeats << '\n'
                << "  弹药: 30mm " << state_.ammo.cannon30mm
                << " | 并列 PKT " << state_.ammo.coaxialPkt
                << " | Konkurs " << state_.ammo.konkurs
                << "(本遭遇没有合理发射目标)\n"
                << "  班组弹药: AKS 弹匣 " << state_.ammo.aksMagazines
                << " | PKM 弹链 " << state_.ammo.pkmBelts
                << " | 马卡洛夫弹匣 " << state_.ammo.makarovMagazines
                << " | 燃烧瓶 " << state_.ammo.molotovs
                << '\n';

        output_ << "\n【战场 NPC(两派单位独立行动)】\n";
        for (const EnemyPerson& enemy : state_.enemies) {
            output_ << "  " << enemy.id << " " << enemy.name
                    << " | " << factionName(enemy.faction)
                    << " | " << dispositionName(enemy.disposition)
                    << " | 生命 " << enemy.health << "/100"
                    << " | 士气 " << enemy.morale << "/100"
                    << " | 体力 " << enemy.stamina
                    << " | 压制 " << enemy.suppression
                    << " | " << locationName(enemy.location)
                    << " | " << enemy.weapon
                    << " | 护甲 " << (enemy.bodyArmor ? "有" : "无")
                    << " | 掩护 " << coverLabel(enemy, state_.policeCar)
                    << " | " << enemyStatusLabel(enemy) << '\n';
        }

        output_ << "  " << organizationSummary() << '\n';

        output_ << "\n【战场载具 / 掩护】\n"
                << "  " << state_.policeCar.name
                << " | 状况 " << state_.policeCar.condition << "/100"
                << " | 位置 " << locationName(state_.policeCar.location)
                << " | 使用者伤害减免 +"
                << state_.policeCar.coverReduction()
                << "% | 固定掩体资产,不主动攻击\n"
                << "  " << state_.woodenCover.name
                << " | 状况 " << state_.woodenCover.condition << "/100"
                << " | 掩护效果 +" << state_.woodenCover.coverReduction()
                << "% | "
                << (state_.woodenCover.burningRounds > 0
                        ? "燃烧中"
                        : "木制、可能被燃烧瓶或机炮引燃") << '\n'
                << "\n【非战斗人员 · 围观者】\n"
                << "  " << state_.bystanders
                << " 名平民,不列入敌方名单、不可被选作目标;已有伤者 "
                << state_.bystanderInjuries << " 人。\n";
    }

    bool runFriendlyPhase() {
        while (true) {
            const bool anyAvailable = std::any_of(
                state_.friendly.begin(), state_.friendly.end(),
                [](const FriendlyPerson& person) {
                    return person.health > 0 && !person.acted;
                });
            if (!anyAvailable) {
                output_ << "\n所有可行动的友方人员都已完成本轮命令。\n";
                return true;
            }

            output_ << "\n【本轮命令】选择车组人物 ID(";
            for (std::size_t index = 0; index < state_.friendly.size(); ++index) {
                if (index != 0) {
                    output_ << '/';
                }
                output_ << state_.friendly[index].id;
            }
            output_ << "),或输入 q 结束命令阶段 > " << std::flush;
            std::string line;
            if (!std::getline(input_, line)) {
                return false;
            }
            const std::string cleaned = trim(line);
            const std::string unit = uppercase(cleaned);
            if (unit == "Q") {
                for (FriendlyPerson& person : state_.friendly) {
                    if (person.health > 0 && !person.acted) {
                        output_ << "  " << person.id
                                << " 未另令,保持位置。\n";
                        person.acted = true;
                    }
                }
                return true;
            }
            if (unit == "HELP") {
                printHelpReminder();
                continue;
            }

            const int index = friendlyIndexById(unit);
            if (index < 0) {
                output_ << "无效人物 ID: “" << cleaned
                        << "”。请从名册中选择;本次不消耗行动。\n";
                continue;
            }
            FriendlyPerson& person = state_.friendly[static_cast<std::size_t>(index)];
            if (person.health <= 0) {
                output_ << person.id << " 已失能,不能接受行动。\n";
                continue;
            }
            if (person.acted) {
                output_ << person.id
                        << " 本轮已经行动;不能重复下令。请选择其他人物。\n";
                continue;
            }
            if (!assignAction(person)) {
                return false;
            }
        }
    }

    void printHelpReminder() {
        output_ << "  命令阶段逐人行动;每个人每轮只能行动一次。\n"
                << "  q 结束本轮,未下令者保持位置;非法输入只会重新询问。\n"
                << "  玩家只直接指挥车组;名单中的两派 NPC 自动选择敌对单位。\n"
                << "  车辆移动必须由车内驾驶员下令;炮塔射击必须由车内炮手\n"
                << "  执行;PKM 射击要求机枪手已经下车。下车和移动会触发\n"
                << "  未受压制敌人的反应射击;找掩体与警戒可降低风险。\n";
    }

    int friendlyIndexById(std::string_view id) const {
        for (std::size_t index = 0; index < state_.friendly.size(); ++index) {
            if (state_.friendly[index].id == id) {
                return static_cast<int>(index);
            }
        }
        return -1;
    }

    std::vector<std::string> coverOptions(Location location) const {
        std::vector<std::string> options;
        if (state_.woodenCover.location == location &&
            state_.woodenCover.condition > 0 &&
            state_.woodenCover.burningRounds == 0 &&
            coverOccupancy("wooden_barricade") < 2) {
            options.push_back("wooden_barricade");
        }
        if (state_.policeCar.location == location &&
            state_.policeCar.condition > 0 && coverOccupancy("police_car") < 2) {
            options.push_back("police_car");
        }
        if (state_.vehicle.location == location && !state_.vehicle.moving &&
            !state_.vehicle.disabled && coverOccupancy("bmp_2") < 4) {
            options.push_back("bmp_2");
        }
        return options;
    }

    int coverOccupancy(const std::string& coverId) const {
        const int friendlyCount = static_cast<int>(std::count_if(
            state_.friendly.begin(), state_.friendly.end(),
            [&coverId](const FriendlyPerson& person) {
                return person.health > 0 && !person.mounted &&
                       person.coverId == coverId;
            }));
        const int enemyCount = static_cast<int>(std::count_if(
            state_.enemies.begin(), state_.enemies.end(),
            [&coverId](const EnemyPerson& enemy) {
                return enemy.active() && enemy.coverId == coverId;
            }));
        return friendlyCount + enemyCount;
    }

    bool hasMeleeTarget(const FriendlyPerson& person) const {
        if (person.mounted) {
            return false;
        }
        return std::any_of(state_.enemies.begin(), state_.enemies.end(),
                           [&person](const EnemyPerson& enemy) {
                               return enemy.active() &&
                                      enemy.disposition == Disposition::Hostile &&
                                      enemy.location == person.location;
                           });
    }

    bool assignAction(FriendlyPerson& person) {
        if (!person.mounted && person.coverId == "wooden_barricade" &&
            state_.woodenCover.burningRounds > 0) {
            output_ << "\n【燃烧迫使撤离】\n"
                    << person.id << " 必须离开正在燃烧的木制掩体。\n";
            resolveReactionFireOnFriendlyMove(person, "逃离燃烧掩体");
            person.coverId.clear();
            if (person.health > 0) {
                const int fireDamage = rng_.inclusive(4, 12);
                person.health = std::max(0, person.health - fireDamage);
                if (person.health > 0) {
                    output_ << person.id << " 仍受火势影响,生命 -"
                            << fireDamage << "。\n";
                }
            }
            if (person.health <= 0) {
                person.acted = true;
                return true;
            }
        }
        const std::vector<ActionChoice> actions = availableActions(person);
        output_ << "\n【" << person.id << " " << person.name
                << " 的可执行行动】\n";
        for (std::size_t index = 0; index < actions.size(); ++index) {
            output_ << "  " << index + 1 << ". " << actions[index].label << '\n';
        }

        while (true) {
            output_ << "选择行动编号 > " << std::flush;
            std::string line;
            if (!std::getline(input_, line)) {
                return false;
            }
            int choice = 0;
            if (!parseInteger(trim(line), choice) || choice < 1 ||
                choice > static_cast<int>(actions.size())) {
                output_ << "无效行动编号;请为当前人物重新选择,"
                        << "本次不消耗行动。\n";
                continue;
            }
            const ActionChoice selected =
                actions[static_cast<std::size_t>(choice - 1)];
            if (actionNeedsTarget(selected.action)) {
                const auto target = selectTarget(person, selected.action);
                if (!target) {
                    if (eof_) {
                        return false;
                    }
                    continue;
                }
                if (checkRefusal(person, selected.action, selected.direction)) {
                    resolveRefusal(person);
                    person.acted = true;
                    return true;
                }
                resolveTargetedAction(person, selected.action, *target);
            } else {
                if (checkRefusal(person, selected.action, selected.direction)) {
                    resolveRefusal(person);
                    person.acted = true;
                    return true;
                }
                resolveUntargetedAction(person, selected.action,
                                        selected.direction);
            }
            person.acted = true;
            return true;
        }
    }

    std::vector<ActionChoice> availableActions(const FriendlyPerson& person)
        const {
        std::vector<ActionChoice> actions;
        const bool able = person.health > 0;
        if (!able) {
            return actions;
        }

        if (person.id == "C1" && person.mounted) {
            actions.push_back({Action::Coordinate, "协调车组(提高纪律,缓和紧张)"});
        }
        if (person.id == "C1") {
            actions.push_back({Action::Negotiate, "与指定敌方人员交涉"});
            if (state_.vehicle.location == Location::Approach) {
                actions.push_back({Action::Withdraw, "命令车组撤离并报告无法安全通过"});
            }
        }
        if (person.id == "G1" && person.mounted &&
            state_.vehicle.location != Location::Beyond &&
            hasReachableTarget(true, state_.vehicle.location)) {
            if (state_.ammo.cannon30mm >= 3) {
                actions.push_back(
                    {Action::CannonFire, "30mm 炮射击指定目标"});
            }
            if (state_.ammo.coaxialPkt >= 60) {
                actions.push_back(
                    {Action::CoaxialFire, "并列 PKT 射击指定目标"});
            }
        }
        if (person.id == "D1" && person.mounted &&
            !state_.vehicle.disabled) {
            actions.push_back({Action::HoldVehicle, "停车并保持 BMP-2 静止"});
        }
        if (person.id == "D1" && person.mounted &&
            !state_.vehicle.disabled) {
            if (state_.vehicle.location != Location::Beyond) {
                actions.push_back(
                    {Action::MoveVehicle, "驾驶 BMP-2 前进一个位置", 1});
            }
            if (state_.vehicle.location != Location::Approach) {
                actions.push_back(
                    {Action::MoveVehicle, "倒车回到前一个位置", -1});
            }
        }
        if (person.id == "M1" && !person.mounted &&
            state_.ammo.pkmBelts > 0 &&
            hasReachableTarget(false, person.location)) {
            actions.push_back({Action::PkmFire, "PKM 射击指定敌方人员"});
        }
        if (person.id != "M1" && !person.mounted &&
            state_.ammo.aksMagazines > 0 &&
            hasReachableTarget(false, person.location)) {
            actions.push_back({Action::PersonalFire, "AKS-74U 射击指定敌方人员"});
        }
        if (person.id == "C1" && !person.mounted &&
            state_.ammo.makarovMagazines > 0 &&
            hasReachableTarget(false, person.location)) {
            actions.push_back({Action::MakarovFire, "马卡洛夫手枪射击指定敌方人员"});
        }

        if (!person.mounted) {
            if (!coverOptions(person.location).empty()) {
                actions.push_back({Action::TakeCover, "寻找当前地点可用掩体"});
            }
            actions.push_back({Action::Overwatch, "警戒并保留一次反应射击"});
            if (person.suppression > 25) {
                actions.push_back({Action::Recover, "稳住呼吸并降低压制"});
            }
            if (hasMeleeTarget(person)) {
                actions.push_back({Action::Melee, "与接敌范围内的敌人肉搏"});
            }
            if (state_.ammo.molotovs > 0) {
                actions.push_back({Action::Molotov, "向指定目标投掷燃烧瓶"});
            }
        }

        actions.push_back({Action::Hold, "保持位置并观察"});
        if (person.mounted && !state_.vehicle.moving) {
            actions.push_back({Action::Dismount, "下车(消耗本人物本轮行动)"});
        }
        if (!person.mounted &&
            person.location == state_.vehicle.location &&
            !state_.vehicle.moving && !state_.vehicle.disabled) {
            actions.push_back({Action::Remount, "返回 BMP-2 内(消耗本轮行动)"});
        }
        if (!person.mounted &&
            person.location != Location::Approach &&
            person.location != Location::Beyond) {
            actions.push_back(
                {Action::MoveOnFoot, "徒步向前移动到路障后方", 1});
            actions.push_back(
                {Action::MoveOnFoot, "徒步后退到接近路", -1});
        } else if (!person.mounted &&
                   person.location == Location::Beyond) {
            actions.push_back({Action::MoveOnFoot, "徒步退回路障", -1});
        } else if (!person.mounted &&
                   person.location == Location::Approach) {
            actions.push_back({Action::MoveOnFoot, "徒步向路障移动", 1});
        }
        return actions;
    }

    std::vector<std::size_t> activeEnemyIndices() const {
        std::vector<std::size_t> indices;
        for (std::size_t index = 0; index < state_.enemies.size(); ++index) {
            if (state_.enemies[index].active()) {
                indices.push_back(index);
            }
        }
        return indices;
    }

    bool isHostileToCrew(const EnemyPerson& unit) const {
        return unit.disposition == Disposition::Hostile;
    }

    static bool factionsOpposed(FactionId first, FactionId second) {
        return first != second;
    }

    bool hasReachableTarget(bool includePoliceCar, Location origin) const {
        for (std::size_t index = 0; index < state_.enemies.size(); ++index) {
            const EnemyPerson& enemy = state_.enemies[index];
            if (!enemy.active() || !isHostileToCrew(enemy)) {
                continue;
            }
            const int distance =
                std::abs(locationIndex(enemy.location) -
                         locationIndex(origin));
            if (distance <= 1) {
                return true;
            }
        }
        return includePoliceCar && state_.policeCar.condition > 0 &&
               std::abs(locationIndex(state_.policeCar.location) -
                        locationIndex(origin)) <= 1;
    }

    static bool actionNeedsTarget(Action action) {
        return action == Action::Negotiate || action == Action::CannonFire ||
               action == Action::CoaxialFire ||
               action == Action::PersonalFire ||
               action == Action::MakarovFire ||
               action == Action::PkmFire || action == Action::Molotov ||
               action == Action::Melee;
    }

    std::optional<TargetChoice> selectTarget(const FriendlyPerson& person,
                                             Action action) {
        struct MenuTarget {
            TargetChoice target;
            std::string label;
        };
        std::vector<MenuTarget> targets;
        const bool vehicleWeapon =
            action == Action::CannonFire || action == Action::CoaxialFire;
        const bool contactOnly = action == Action::Melee;
        const Location firingLocation =
            vehicleWeapon ? state_.vehicle.location : person.location;

        for (std::size_t index = 0; index < state_.enemies.size(); ++index) {
            const EnemyPerson& enemy = state_.enemies[index];
            if (!enemy.active() || !isHostileToCrew(enemy)) {
                continue;
            }
            if (action != Action::Negotiate) {
                const int distance =
                    std::abs(locationIndex(enemy.location) -
                             locationIndex(firingLocation));
                if ((contactOnly && distance != 0) ||
                    (!contactOnly && distance > 1)) {
                    continue;
                }
            }
            targets.push_back(
                {{false, false, index},
                 enemy.id + " " + enemy.name + "(生命 " +
                     std::to_string(enemy.health) + ",士气 " +
                     std::to_string(enemy.morale) + ")"});
        }
        if (config_.allowCoverTargets && vehicleWeapon &&
            state_.policeCar.condition > 0) {
            targets.push_back(
                {{true, false, 0},
                 state_.policeCar.name + "(掩护资产,状况 " +
                     std::to_string(state_.policeCar.condition) + ")"});
        }
        if (config_.allowCoverTargets &&
            (action == Action::Molotov || action == Action::CannonFire) &&
            state_.woodenCover.condition > 0) {
            targets.push_back(
                {{false, true, 0}, state_.woodenCover.name + "(可燃掩体)"});
        }

        if (targets.empty()) {
            output_ << "当前没有合法目标;该行动不消耗,返回行动列表。\n";
            return std::nullopt;
        }

        output_ << "\n【选择"
                << (action == Action::Negotiate
                        ? "交涉"
                        : (action == Action::Melee
                               ? "肉搏"
                               : (action == Action::Molotov ? "投掷" : "射击")))
                << "目标】\n";
        for (std::size_t index = 0; index < targets.size(); ++index) {
            output_ << "  " << index + 1 << ". " << targets[index].label << '\n';
        }
        while (true) {
            output_ << "目标编号 > " << std::flush;
            std::string line;
            if (!std::getline(input_, line)) {
                eof_ = true;
                return std::nullopt;
            }
            int choice = 0;
            if (!parseInteger(trim(line), choice) || choice < 1 ||
                choice > static_cast<int>(targets.size())) {
                output_ << "无效目标编号;请重新选择目标。\n";
                continue;
            }
            return targets[static_cast<std::size_t>(choice - 1)].target;
        }
    }

    static bool parseInteger(std::string_view text, int& result) {
        if (text.empty()) {
            return false;
        }
        const char* begin = text.data();
        const char* end = begin + text.size();
        const auto parsed = std::from_chars(begin, end, result, 10);
        return parsed.ec == std::errc{} && parsed.ptr == end;
    }

    bool isHighRisk(const FriendlyPerson& person, Action action,
                    int direction) const {
        if (action == Action::CannonFire || action == Action::CoaxialFire ||
            action == Action::PkmFire || action == Action::Molotov ||
            action == Action::Melee) {
            return true;
        }
        if (action == Action::PersonalFire && person.id != "C1") {
            return true;
        }
        if (action == Action::MoveVehicle && person.id == "D1" &&
            direction > 0 &&
            !activeEnemyIndices().empty()) {
            return true;
        }
        return false;
    }

    bool checkRefusal(const FriendlyPerson& person, Action action,
                      int direction) {
        if (state_.discipline > kDisobedienceThreshold ||
            !isHighRisk(person, action, direction)) {
            return false;
        }
        return rng_.below(100) < 35;
    }

    void resolveRefusal(const FriendlyPerson& person) {
        output_ << "\n【命令未执行】\n"
                << person.id << " " << person.name
                << " 在临界纪律下拒绝执行这项高风险命令。\n";
        if (person.id == "G1") {
            output_ << "炮手按住武器控制台:“先让我们确认对面是否真的会开火。”\n";
        } else if (person.id == "D1") {
            output_ << "驾驶员没有松开制动:“这里全是人,我不能只凭一句命令就动。”\n";
        } else {
            output_ << "机枪手没有扣下扳机:“我们还没到只能这样做的地步。”\n";
        }
        state_.discipline = std::max(0, state_.discipline - 2);
        state_.tension = std::min(100, state_.tension + 2);
    }

    void resolveUntargetedAction(FriendlyPerson& person, Action action,
                                 int direction) {
        switch (action) {
        case Action::Coordinate:
            output_ << "\n【C1 执行协调】\n"
                    << "你逐一确认炮手、驾驶员和机枪手的观察,把开火权限收回"
                    << "到自己口中。车组重新按同一套接敌条件行动。\n";
            state_.discipline = std::min(100, state_.discipline + 2);
            state_.tension = std::max(0, state_.tension - 3);
            break;
        case Action::Withdraw:
            state_.withdrawalOrdered = true;
            output_ << "\n【C1 命令撤离】\n"
                    << "你命令车组停在接近路并向指挥部报告路障无法安全排除。"
                    << "若本回合后仍至少有一名友军能动且 BMP-2 在接近路,"
                    << "遭遇将以撤离结算。\n";
            state_.discipline = std::max(0, state_.discipline - 2);
            state_.tension = std::max(0, state_.tension - 4);
            break;
        case Action::HoldVehicle:
            state_.vehicle.moving = false;
            output_ << "\n【D1 保持车体】\n"
                    << "驾驶员让 BMP-2 稳稳停在 " << locationName(state_.vehicle.location)
                    << ",为车内人员重新上下车留出条件。\n";
            state_.tension = std::max(0, state_.tension - 1);
            break;
        case Action::MoveVehicle:
            resolveVehicleMove(direction);
            break;
        case Action::Hold:
            output_ << "\n【" << person.id << " 保持位置】\n";
            if (person.mounted) {
                output_ << person.name << "留在车内继续观察,没有消耗弹药。\n";
            } else {
                output_ << person.name << "留在 " << locationName(person.location)
                        << ",没有进入敌方视线中心。\n";
            }
            break;
        case Action::TakeCover:
            resolveTakeCover(person);
            break;
        case Action::Overwatch:
            person.overwatch = true;
            output_ << "\n【" << person.id << " 进入警戒】\n"
                    << "该队员本轮保留一次反应射击,等待敌人暴露移动。\n";
            break;
        case Action::Recover:
            person.suppression = std::max(0, person.suppression - 45);
            person.stamina = std::min(100, person.stamina + 18);
            output_ << "\n【" << person.id << " 稳定状态】\n"
                    << "压制下降,体力有所恢复。\n";
            break;
        case Action::Dismount:
            person.mounted = false;
            person.location = state_.vehicle.location;
            output_ << "\n【" << person.id << " 下车】\n"
                    << person.name << "打开舱门,落到 "
                    << locationName(person.location)
                    << "。本人物本轮行动已用于下车。\n";
            resolveReactionFireOnFriendlyMove(person, "下车暴露");
            if (person.id == "M1") {
                state_.sawMachineGunnerDismount = true;
            }
            state_.tension = std::min(100, state_.tension + 2);
            break;
        case Action::Remount:
            person.mounted = true;
            person.location = state_.vehicle.location;
            output_ << "\n【" << person.id << " 返回车体】\n"
                    << person.name << "在 BMP-2 静止时返回到车内。\n";
            break;
        case Action::MoveOnFoot:
            resolveFootMove(person, direction);
            break;
        default:
            break;
        }
    }

    void resolveVehicleMove(int direction) {
        const Location origin = state_.vehicle.location;
        const Location destination = locationFromIndex(
            locationIndex(origin) + direction);
        resolveReactionFireOnVehicleMove(origin);
        output_ << "\n【D1 " << (direction > 0 ? "驾驶 BMP-2 前进】\n"
                                      : "倒车】\n")
                << "BMP-2 从 " << locationName(state_.vehicle.location)
                << " 移动到 " << locationName(destination)
                << "。车内人员随车移动,车外人员保留原位置。\n";
        state_.vehicle.location = destination;
        state_.vehicle.moving = true;
        for (FriendlyPerson& person : state_.friendly) {
            if (person.mounted) {
                person.location = destination;
            }
        }
        state_.tension = std::min(100, state_.tension + 9);
        state_.bystanderRisk = std::min(100, state_.bystanderRisk + 5);
        if (destination == Location::Roadblock ||
            destination == Location::Beyond) {
            state_.discipline = std::max(0, state_.discipline - 2);
        }
        if (destination == Location::Beyond &&
            !activeEnemyIndices().empty()) {
            output_ << "车辆已经越过路障,但武装人员仍在附近;"
                    << "只有完成本回合敌方回应后才能结算。\n";
        }
    }

    void resolveFootMove(FriendlyPerson& person, int direction) {
        const Location origin = person.location;
        person.coverId.clear();
            resolveReactionFireOnFriendlyMove(person, "徒步移动");
        person.location = locationFromIndex(locationIndex(origin) + direction);
        output_ << "\n【" << person.id << " 徒步移动】\n"
                << person.name << "从 "
                << locationName(origin)
                << " 移动到 " << locationName(person.location) << "。\n";
        if (person.location == Location::Roadblock) {
            state_.tension = std::min(100, state_.tension + 4);
        }
        if (hasMeleeTarget(person) && person.health > 0) {
            for (EnemyPerson& enemy : state_.enemies) {
                if (enemy.active() && isHostileToCrew(enemy) &&
                    enemy.location == person.location &&
                    !enemy.reactionUsed) {
                    resolvePassiveMelee(enemy, person);
                    break;
                }
            }
        }
    }

    void resolveTakeCover(FriendlyPerson& person) {
        const std::vector<std::string> options = coverOptions(person.location);
        if (options.empty()) {
            output_ << "当前地点没有可用掩体;行动未消耗,请重新选择。\n";
            person.acted = false;
            return;
        }
        output_ << "\n【" << person.id << " 寻找掩体】\n";
        for (std::size_t i = 0; i < options.size(); ++i) {
            output_ << "  " << i + 1 << ". " << coverName(options[i]) << '\n';
        }
        while (true) {
            output_ << "掩体编号 > " << std::flush;
            std::string line;
            if (!std::getline(input_, line)) {
                eof_ = true;
                return;
            }
            int choice = 0;
            if (!parseInteger(trim(line), choice) || choice < 1 ||
                choice > static_cast<int>(options.size())) {
                output_ << "无效掩体编号,请重新选择。\n";
                continue;
            }
            person.coverId.clear();
            resolveReactionFireOnFriendlyMove(person, "寻找掩体");
            if (person.health <= 0) {
                return;
            }
            person.coverId = options[static_cast<std::size_t>(choice - 1)];
            output_ << person.id << " 抵达 " << coverName(person.coverId)
                    << ",现在获得掩护。\n";
            if (person.coverId == "bmp_2") {
                output_ << "BMP-2 静止时可作为临时硬掩体。\n";
            }
            return;
        }
    }

    std::string coverName(const std::string& id) const {
        if (id == "wooden_barricade") return state_.woodenCover.name;
        if (id == "police_car") return state_.policeCar.name;
        if (id == "bmp_2") return state_.vehicle.name + " 车体";
        return "无掩体";
    }

    void resolveTargetedAction(FriendlyPerson& person, Action action,
                               const TargetChoice& target) {
        if (action == Action::Negotiate) {
            resolveNegotiation(person,
                               state_.enemies[target.enemyIndex]);
            return;
        }
        if (action == Action::Melee) {
            resolveMelee(person, state_.enemies[target.enemyIndex]);
            return;
        }
        if (action == Action::Molotov) {
            resolveMolotov(person, target);
            return;
        }
        if (target.woodenCover) {
            resolveWoodenCoverAttack(person, action);
            return;
        }
        if (target.policeCar) {
            resolvePoliceCarAttack(person, action);
            return;
        }
        resolveEnemyAttack(person, action,
                           state_.enemies[target.enemyIndex]);
    }

    void resolveNegotiation(FriendlyPerson& person, EnemyPerson& enemy) {
        output_ << "\n【" << person.id << " 与 " << enemy.id
                << " 交涉】\n";
        const int successChance =
            55 + (state_.tension <= 55 ? 10 : 0) +
            (state_.discipline > kDisobedienceThreshold ? 5 : 0);
        const bool success = rng_.below(100) < successChance;
        const int moraleLoss = rng_.inclusive(8, 14);
        enemy.morale = std::max(0, enemy.morale - moraleLoss);
        state_.tension = std::max(0, state_.tension - 6);
        state_.bystanderRisk = std::max(0, state_.bystanderRisk - 2);
        state_.discipline = std::min(100, state_.discipline + 1);
        output_ << enemy.name << " 听取条件,士气 -" << moraleLoss
                << "。\n";
        if (success) {
            enemy.negotiated = true;
            enemy.status = EnemyStatus::Surrendered;
            output_ << "对方接受了“低速通过、炮口离开人群、不追击”的安排。"
                    << "该个人放下武器并停止交战;谈判记录已写入任务状态。\n";
        } else {
            output_ << "对方仍有顾虑:有人担心让路后被报复,"
                    << "这次交涉未形成可执行的通行安排。\n";
        }
        if (enemy.morale <= 25) {
            output_ << "对方士气已降到临界;投降或逃离检查将在"
                    << "本轮敌方回应结束后进行。\n";
        }
        if (missionAgreementRecorded()) {
            output_ << "任务状态: 已分别与内务部警察和武装平民记录安排;"
                    << "现在需要将 BMP-2 开到路障后方。\n";
        }
    }

    bool missionAgreementRecorded() const {
        if (config_.negotiatedPassageFactions.empty()) {
            return false;
        }
        for (FactionId required : config_.negotiatedPassageFactions) {
            const bool recorded = std::any_of(
                state_.enemies.begin(), state_.enemies.end(),
                [required](const EnemyPerson& unit) {
                    return unit.faction == required && unit.negotiated;
                });
            if (!recorded) {
                return false;
            }
        }
        return true;
    }

    void resolvePoliceCarAttack(const FriendlyPerson& person, Action action) {
        const bool cannon = action == Action::CannonFire;
        const int ammoCost = cannon ? 3 : 60;
        if (cannon) {
            state_.ammo.cannon30mm =
                std::max(0, state_.ammo.cannon30mm - ammoCost);
        } else {
            state_.ammo.coaxialPkt =
                std::max(0, state_.ammo.coaxialPkt - ammoCost);
        }
        output_ << "\n【" << person.id << " "
                << (cannon ? "30mm 炮三发点射" : "并列 PKT")
                << "轰击警车】\n";
        const int rounds = cannon ? 3 : 1;
        std::vector<bool> splashed(state_.enemies.size(), false);
        for (int shot = 1; shot <= rounds; ++shot) {
            const int hitChance = cannon ? 78 : 56;
            if (rng_.below(100) < hitChance) {
                const int damage = cannon ? rng_.inclusive(42, 58)
                                          : rng_.inclusive(8, 15);
                state_.policeCar.condition =
                    std::max(0, state_.policeCar.condition - damage);
                output_ << (cannon ? "  第 " + std::to_string(shot) + " 发命中;" : "")
                        << "警车状况 -" << damage << ";剩余 "
                        << state_.policeCar.condition << "/100。"
                        << "它为内务部警察提供的伤害减免现在为 +"
                        << state_.policeCar.coverReduction() << "%。\n";
            } else {
                output_ << (cannon ? "  第 " + std::to_string(shot) + " 发未命中;" : "")
                        << "攻击未改变警车状况;车后的人仍在寻找掩护。\n";
            }
            if (!cannon) continue;
            for (std::size_t index = 0; index < state_.enemies.size(); ++index) {
                EnemyPerson& enemy = state_.enemies[index];
                if (!enemy.active() || splashed[index] ||
                    std::abs(locationIndex(enemy.location) - locationIndex(state_.policeCar.location)) > 1 ||
                    rng_.below(100) >= 76) continue;
                int splashDamage = rng_.inclusive(30, 48);
                if (enemy.bodyArmor) splashDamage = splashDamage * 82 / 100;
                enemy.health = std::max(0, enemy.health - splashDamage);
                const bool killed = enemy.health <= 0 && rng_.below(100) < 30;
                if (enemy.health <= 0) enemy.status = killed ? EnemyStatus::Killed
                                                              : EnemyStatus::Incapacitated;
                enemy.suppression = std::min(100, enemy.suppression + 35);
                enemy.morale = std::max(0, enemy.morale - 22);
                recordEnemyCasualty(enemy, splashDamage, killed);
                splashed[index] = true;
                output_ << "    溅射波及 " << enemy.id << ",伤害 " << splashDamage << "。\n";
            }
        }
        const int disciplineLoss = cannon ? 10 : 6;
        state_.discipline =
            std::max(0, state_.discipline - disciplineLoss);
        state_.tension = std::min(100, state_.tension + (cannon ? 20 : 13));
        state_.bystanderRisk =
            std::min(100, state_.bystanderRisk + (cannon ? 18 : 10));
        maybeInjureBystander(cannon ? 18 : 10);
    }

    void maybeInjureBystander(int chance) {
        if (state_.bystanderRisk >= 50 && rng_.below(100) < chance) {
            ++state_.bystanderInjuries;
            output_ << "围观人群中出现一名伤者;非战斗人员仍未被列入敌方名册。\n";
        }
    }

    void resolveEnemyAttack(FriendlyPerson& person, Action action,
                            EnemyPerson& enemy) {
        if (action == Action::CannonFire) {
            resolveCannonBurst(person, enemy);
            return;
        }
        int ammoCost = 0;
        int baseHitChance = 0;
        int minimumDamage = 0;
        int maximumDamage = 0;
        int disciplineLoss = 0;
        int tensionGain = 0;
        std::string attackName;

        if (action == Action::CoaxialFire) {
            ammoCost = 60;
            state_.ammo.coaxialPkt =
                std::max(0, state_.ammo.coaxialPkt - ammoCost);
            baseHitChance = 56;
            minimumDamage = 32;
            maximumDamage = 48;
            disciplineLoss = 7;
            tensionGain = 15;
            attackName = "并列 PKT";
        } else if (action == Action::PersonalFire) {
            state_.ammo.aksMagazines =
                std::max(0, state_.ammo.aksMagazines - 1);
            baseHitChance = 48;
            minimumDamage = 42;
            maximumDamage = 62;
            disciplineLoss = 4;
            tensionGain = 9;
            attackName = "AKS-74U";
        } else if (action == Action::MakarovFire) {
            state_.ammo.makarovMagazines =
                std::max(0, state_.ammo.makarovMagazines - 1);
            baseHitChance = 40;
            minimumDamage = 22;
            maximumDamage = 34;
            disciplineLoss = 2;
            tensionGain = 6;
            attackName = "马卡洛夫手枪";
        } else {
            state_.ammo.pkmBelts =
                std::max(0, state_.ammo.pkmBelts - 1);
            baseHitChance = 52;
            minimumDamage = 55;
            maximumDamage = 78;
            disciplineLoss = 5;
            tensionGain = 12;
            attackName = "PKM";
        }

        baseHitChance = std::max(10, baseHitChance -
                                         coverReduction(enemy.coverId) / 2);
        output_ << "\n【" << person.id << " 用 " << attackName
                << " 攻击 " << enemy.id << "】\n";
        if (rng_.below(100) >= baseHitChance) {
            output_ << "攻击未造成伤害;" << enemy.name
                    << " 仍在原位置或利用掩体。\n";
        } else {
            int reduction = 0;
            std::vector<std::string> protection;
            if (enemy.bodyArmor) {
                reduction += 20;
                protection.push_back("身体护甲 20%");
            }
            if (enemy.coverId == "police_car" &&
                state_.policeCar.condition > 0) {
                const int cover = state_.policeCar.coverReduction();
                reduction += cover;
                protection.push_back("警车掩护 " + std::to_string(cover) + "%");
            }
            if (enemy.coverId == "wooden_barricade") {
                const int cover = coverReduction(enemy.coverId);
                reduction += cover;
                if (cover > 0) {
                    protection.push_back("木制掩体 " + std::to_string(cover) + "%");
                }
            }
            reduction = std::min(70, reduction);
            const int rawDamage = rng_.inclusive(minimumDamage, maximumDamage);
            const int damage =
                std::max(1, rawDamage * (100 - reduction) / 100);
            enemy.health = std::max(0, enemy.health - damage);
            const int moraleLoss =
                std::max(4, damage / 2 + rng_.inclusive(0, 4));
            enemy.morale = std::max(0, enemy.morale - moraleLoss);
            const bool killed = enemy.health <= 0 && rng_.below(100) <
                (action == Action::PkmFire ? 48 : 38);
            if (enemy.health <= 0) {
                enemy.status = killed ? EnemyStatus::Killed : EnemyStatus::Incapacitated;
            }
            recordEnemyCasualty(enemy, damage, killed);
            output_ << "命中: 生命 -" << damage << "(原始 " << rawDamage;
            if (!protection.empty()) {
                output_ << ";";
                for (std::size_t index = 0; index < protection.size(); ++index) {
                    if (index != 0) {
                        output_ << "、";
                    }
                    output_ << protection[index];
                }
            }
            output_ << "),士气 -" << moraleLoss << "。剩余生命 "
                    << enemy.health << "/100,士气 " << enemy.morale
                    << "/100。\n";
            if (enemy.health <= 0) output_ << enemy.id << (killed ? " 被击毙" : " 失去行动能力") << ",状态已更新。\n";
        }

        const int suppressionAdded =
            action == Action::CannonFire ? 42
            : (action == Action::CoaxialFire || action == Action::PkmFire ? 30
                                                                          : 20);
        enemy.suppression = std::min(100, enemy.suppression + suppressionAdded);
        if (action != Action::CannonFire) adjustOrganization(enemy.faction,
                           action == Action::CoaxialFire || action == Action::PkmFire ? 4 : 2);
        if (enemy.suppression >= 60) {
            output_ << enemy.id << " 已被压制,不能进行反应射击且命中率下降。\n";
        }

        if (action == Action::CoaxialFire) {
            for (EnemyPerson& other : state_.enemies) {
                if (other.active()) {
                    other.morale = std::max(0, other.morale - 2);
                }
            }
            output_ << "重火力使附近仍能行动的人员士气 -2。\n";
        }
        state_.discipline =
            std::max(0, state_.discipline - disciplineLoss);
        state_.tension = std::min(100, state_.tension + tensionGain);
        state_.bystanderRisk =
            std::min(100, state_.bystanderRisk + tensionGain / 2);
        maybeInjureBystander(tensionGain / 2);
    }

    void resolveCannonBurst(const FriendlyPerson& person, EnemyPerson& primary) {
        constexpr int rounds = 3;
        state_.ammo.cannon30mm = std::max(0, state_.ammo.cannon30mm - rounds);
        output_ << "\n【" << person.id << " 以 30mm 机炮三发点射,主目标 "
                << primary.id << "】\n";
        int directHits = 0;
        int splashHits = 0;
        std::vector<bool> splashedThisBurst(state_.enemies.size(), false);
        for (int shot = 1; shot <= rounds; ++shot) {
            if (primary.active() && rng_.below(100) < 76) {
                int damage = rng_.inclusive(58, 82);
                if (primary.bodyArmor) damage = damage * 82 / 100;
                primary.health = std::max(0, primary.health - damage);
                const bool killed = primary.health <= 0 && rng_.below(100) < 68;
                if (primary.health <= 0) primary.status = killed ? EnemyStatus::Killed : EnemyStatus::Incapacitated;
                primary.suppression = std::min(100, primary.suppression + 32);
                primary.morale = std::max(0, primary.morale - 24);
                recordEnemyCasualty(primary, damage, killed);
                ++directHits;
                output_ << "  第 " << shot << " 发命中 " << primary.id << ",伤害 " << damage
                        << (primary.bodyArmor ? "(护甲已减伤)" : "(无视轻型掩体)") << "。\n";
                if (primary.coverId == "wooden_barricade" && rng_.below(100) < 38)
                    igniteWoodenCover("机炮冲击");
            } else {
                output_ << "  第 " << shot << " 发没有直接命中主目标。\n";
            }
            for (std::size_t index = 0; index < state_.enemies.size(); ++index) {
                EnemyPerson& nearby = state_.enemies[index];
                if (&nearby == &primary || !nearby.active() || splashedThisBurst[index] ||
                    std::abs(locationIndex(nearby.location) - locationIndex(primary.location)) > 1 ||
                    rng_.below(100) >= 76) continue;
                int damage = rng_.inclusive(30, 48);
                if (nearby.bodyArmor) damage = damage * 82 / 100;
                nearby.health = std::max(0, nearby.health - damage);
                const bool killed = nearby.health <= 0 && rng_.below(100) < 30;
                if (nearby.health <= 0) nearby.status = killed ? EnemyStatus::Killed : EnemyStatus::Incapacitated;
                nearby.suppression = std::min(100, nearby.suppression + 35);
                nearby.morale = std::max(0, nearby.morale - 22);
                recordEnemyCasualty(nearby, damage, killed);
                splashedThisBurst[index] = true;
                ++splashHits;
                output_ << "    溅射波及 " << nearby.id << ",伤害 " << damage << "(轻型掩体无效)。\n";
            }
        }
        output_ << "本次消耗 3 发;直接命中 " << directHits << " 次,邻近溅射命中 " << splashHits << " 次。\n";
        state_.discipline = std::max(0, state_.discipline - 11);
        state_.tension = std::min(100, state_.tension + 22);
        state_.bystanderRisk = std::min(100, state_.bystanderRisk + 11);
        maybeInjureBystander(11);
    }

    void resolveEnemyPhase() {
        const auto active = activeEnemyIndices();
        if (active.empty()) {
            output_ << "\n【敌方行动阶段】\n"
                    << "没有仍能行动的敌方人员,本轮不执行敌方回应。\n";
            return;
        }

        output_ << "\n【敌方行动阶段 · 按稳定 ID 顺序】\n";
        for (std::size_t enemyIndex : active) {
            EnemyPerson& enemy = state_.enemies[enemyIndex];
            if (!enemy.active() || enemy.reactionUsed) {
                continue;
            }
            makeEnemyResponse(enemy);
        }

        for (EnemyPerson& enemy : state_.enemies) {
            if (!enemy.active()) {
                continue;
            }
            const int organization = organizationOf(enemy.faction);
            if (enemy.morale > 25 && organization > 0 &&
                factionMoraleOf(enemy.faction) > 25) continue;
            const int routBonus = (organization == 0 ? 35 : 0) +
                                  (factionMoraleOf(enemy.faction) <= 25 ? 25 : 0);
            if (enemy.profile == UnitProfile::ArmedCivilian) {
                const bool flees = rng_.below(100) <
                                   std::min(95, 55 + routBonus);
                if (flees) {
                    enemy.coverId.clear();
                    triggerFriendlyOverwatch(enemy, "惊慌逃跑");
                    if (!enemy.active()) continue;
                    enemy.status = EnemyStatus::Fled;
                    adjustOrganization(enemy.faction, 12);
                    output_ << "  " << enemy.id
                            << (organization == 0 ? " 所属阵营溃散," : " 士气崩溃,")
                            << "放弃路障并逃离(终止状态)。\n";
                } else {
                    output_ << "  " << enemy.id
                            << " 状态动摇,但仍未退出战斗。\n";
                }
            } else {
                const bool surrenders = rng_.below(100) <
                                        std::min(95, 45 + routBonus);
                if (surrenders) {
                    enemy.status = EnemyStatus::Surrendered;
                    enemy.coverId.clear();
                    adjustOrganization(enemy.faction, 12);
                    output_ << "  " << enemy.id
                            << (organization == 0 ? " 所属阵营溃散," : " ")
                            << "放下武器投降(终止状态)。\n";
                } else {
                    output_ << "  " << enemy.id
                            << " 状态动摇,但仍继续维持警戒。\n";
                }
            }
        }
        tickSuppressionAndFire();
    }

    void makeEnemyResponse(EnemyPerson& enemy) {
        if (enemy.coverId == "wooden_barricade" &&
            state_.woodenCover.condition <= 0) {
            enemy.coverId.clear();
        }
        if (enemy.coverId == "police_car" &&
            state_.policeCar.condition <= 0) {
            enemy.coverId.clear();
        }
        if (enemy.coverId == "wooden_barricade" &&
            state_.woodenCover.burningRounds > 0) {
            output_ << "  " << enemy.id << " 被燃烧的木制掩体逼出掩护。";
            triggerFriendlyOverwatch(enemy, "离开燃烧掩体");
            enemy.coverId.clear();
            enemy.suppression = std::min(100, enemy.suppression + 12);
            adjustOrganization(enemy.faction, 3);
            output_ << '\n';
            if (!enemy.active()) return;
        }

        const int organization = organizationOf(enemy.faction);
        if (organization == 0 && rng_.below(100) < 45) {
            if (enemy.profile == UnitProfile::MvdOfficer) {
                enemy.status = EnemyStatus::Surrendered;
                enemy.coverId.clear();
                output_ << "  " << enemy.id << " 在溃散中放下武器投降。\n";
            } else {
                output_ << "  " << enemy.id << " 在溃散中"
                        << "准备逃离。\n";
                enemy.coverId.clear();
                triggerFriendlyOverwatch(enemy, "溃散逃跑");
                if (enemy.active()) {
                    enemy.status = EnemyStatus::Fled;
                    output_ << "  " << enemy.id << " 已逃离。\n";
                }
            }
            return;
        }
        if (enemy.suppression >= 60) {
            enemy.suppression = std::max(0, enemy.suppression - 35);
            enemy.stamina = std::max(0, enemy.stamina - 4);
            output_ << "  " << enemy.id << " 被压制,只能缩身恢复,没有有效还击。\n";
            return;
        }
        if (isHostileToCrew(enemy) && enemy.molotovs > 0 &&
            anyFriendlyUsingWoodCover()) {
            --enemy.molotovs;
            state_.woodenCover.burningRounds = 2;
            state_.woodenCover.condition =
                std::max(0, state_.woodenCover.condition - 25);
            output_ << "  " << enemy.id
                    << " 投出燃烧瓶,木制掩体起火,逼迫其中人员撤离。\n";
            adjustOrganization(enemy.faction, 4);
            return;
        }
        if (enemy.health < 55 && enemy.coverId.empty() &&
            seekEnemyCover(enemy)) return;
        if (enemy.coverId.empty() &&
            (enemy.suppression >= 25 || enemy.morale <= 35) &&
            seekEnemyCover(enemy)) return;
        if (isHostileToCrew(enemy) && hasSameLocationFriendly(enemy) &&
            rng_.below(100) < 35) {
            FriendlyPerson* target = closestDismountedFriendly(enemy);
            if (target != nullptr) {
                resolveEnemyMelee(enemy, *target);
                return;
            }
        }

        std::vector<std::size_t> ableFriendly;
        if (isHostileToCrew(enemy)) {
            for (std::size_t index = 0; index < state_.friendly.size(); ++index) {
                if (state_.friendly[index].health > 0 &&
                    !state_.friendly[index].mounted &&
                    std::abs(locationIndex(state_.friendly[index].location) -
                             locationIndex(enemy.location)) <= 1) {
                    ableFriendly.push_back(index);
                }
            }
        }

        std::vector<std::size_t> npcTargets;
        for (std::size_t index = 0; index < state_.enemies.size(); ++index) {
            const EnemyPerson& candidate = state_.enemies[index];
            if (!candidate.active() ||
                candidate.disposition == enemy.disposition ||
                !factionsOpposed(enemy.faction, candidate.faction) ||
                std::abs(locationIndex(candidate.location) -
                         locationIndex(enemy.location)) > 1) {
                continue;
            }
            npcTargets.push_back(index);
        }
        if (!npcTargets.empty() &&
            (ableFriendly.empty() || rng_.below(100) < 72)) {
            std::size_t best = npcTargets.front();
            int bestScore = std::numeric_limits<int>::min();
            for (std::size_t index : npcTargets) {
                const EnemyPerson& candidate = state_.enemies[index];
                const int score = 45 - candidate.health / 2 -
                                  candidate.suppression / 4 -
                                  coverReduction(candidate.coverId) +
                                  (candidate.faction == FactionId::CommitteeArmy
                                       ? 4
                                       : 0);
                if (score > bestScore) {
                    best = index;
                    bestScore = score;
                }
            }
            attackNpc(enemy, state_.enemies[best]);
            return;
        }
        if (ableFriendly.empty()) {
            if (enemy.coverId.empty() && seekEnemyCover(enemy)) return;
            if (!config_.standardBriefing && isHostileToCrew(enemy) &&
                !state_.vehicle.disabled) {
                attackVehicle(enemy);
                return;
            }
            output_ << "  " << enemy.id
                    << "观察到 BMP-2 装甲防护,不浪费手枪/步枪射击;继续守住位置。\n";
            return;
        }
        const std::size_t targetIndex = bestTargetIndex(enemy, ableFriendly);
        attackFriendly(enemy, state_.friendly[targetIndex]);
    }

    void attackNpc(const EnemyPerson& attacker, EnemyPerson& target) {
        const bool military =
            attacker.profile == UnitProfile::CommitteeSoldier ||
            attacker.profile == UnitProfile::MvdOfficer;
        const int hitChance =
            std::max(10, (military ? 50 : 43) -
                             target.suppression / 5 -
                             coverReduction(target.coverId));
        output_ << "  " << attacker.id << " 以 " << attacker.weapon
                << " 向敌对派 " << target.id << " " << target.name
                << " 交火。";
        if (rng_.below(100) >= hitChance) {
            target.suppression = std::min(100, target.suppression + 15);
            output_ << " 未命中,但双方持续互相压制;目标压制 "
                    << target.suppression << "/100。\n";
            return;
        }
        const int rawDamage =
            military ? rng_.inclusive(32, 58) : rng_.inclusive(24, 48);
        const int damage = target.bodyArmor
                               ? std::max(1, rawDamage * 82 / 100)
                               : rawDamage;
        target.health = std::max(0, target.health - damage);
        target.morale = std::max(0, target.morale - (9 + damage / 5));
        target.suppression = std::min(100, target.suppression + 30);
        target.stamina = std::max(0, target.stamina - 8);
        const bool killed =
            target.health <= 0 && rng_.below(100) < 36;
        if (target.health <= 0) {
            target.status = killed ? EnemyStatus::Killed
                                   : EnemyStatus::Incapacitated;
        }
        recordEnemyCasualty(target, damage, killed);
        output_ << " 命中,生命 -" << damage << "(剩余 "
                << target.health << "/100,士气 " << target.morale
                << "/100);" << enemyStatusLabel(target) << "。\n";
    }

    void attackVehicle(const EnemyPerson& enemy) {
        const int hitChance =
            enemy.profile == UnitProfile::MvdOfficer ? 42 : 32;
        output_ << "  " << enemy.id << " 以 " << enemy.weapon
                << " 回应,瞄准的是 BMP-2 这一独立载具目标。";
        if (rng_.below(100) >= hitChance) {
            output_ << " 未造成车体损伤。\n";
            return;
        }
        const int damage =
            enemy.profile == UnitProfile::MvdOfficer ? rng_.inclusive(5, 10)
                                                : rng_.inclusive(6, 13);
        state_.vehicle.condition =
            std::max(0, state_.vehicle.condition - damage);
        output_ << " 车况 -" << damage << ",剩余 "
                << state_.vehicle.condition << "/100。";
        if (state_.vehicle.condition <= 0) {
            state_.vehicle.disabled = true;
            state_.vehicle.moving = false;
            output_ << " BMP-2 已失能。";
        }
        output_ << '\n';
    }

    void attackFriendly(const EnemyPerson& enemy, FriendlyPerson& target) {
        if (target.mounted) {
            output_ << "  " << enemy.id
                    << " 的小型武器无法穿透 BMP-2 装甲,车内乘员未受伤。\n";
            return;
        }
        const int hitChance =
            std::max(8, (enemy.profile == UnitProfile::MvdOfficer ? 38 : 46) -
                            target.suppression / 5 -
                            coverReduction(target.coverId));
        output_ << "  " << enemy.id << " 以 " << enemy.weapon
                << " 回应,选择 " << target.id << " " << target.name
                << " 作为单个战斗人员目标。";
        if (rng_.below(100) >= hitChance) {
            target.suppression = std::min(100, target.suppression + 12);
            output_ << " 攻击未命中,但造成压制;压制 "
                    << target.suppression << "/100。\n";
            return;
        }
        const bool covered = coverReduction(target.coverId) > 0;
        const bool fatalHit = !covered && rng_.below(100) < 22;
        const int damage = fatalHit
                              ? target.health
                              : (covered ? rng_.inclusive(22, 46)
                                         : rng_.inclusive(48, 88));
        target.health = fatalHit ? 0 : std::max(0, target.health - damage);
        target.suppression = std::min(100, target.suppression + 28);
        target.stamina = std::max(0, target.stamina - 12);
        output_ << " " << target.id << " 生命 -" << damage
                << ",剩余 " << target.health << "/100("
                << healthLabel(target.health) << ")。";
        if (target.health <= 0) {
            target.killed = fatalHit;
            output_ << " " << target.id
                    << (fatalHit ? " 遭致命命中。" : " 立即失能,不能再接受行动。");
        } else if (!covered) {
            output_ << " 暴露命中造成重伤。";
        } else {
            output_ << " 掩体降低了伤势。";
        }
        output_ << '\n';
    }

    int coverReduction(const std::string& coverId) const {
        if (coverId == "wooden_barricade") {
            return state_.woodenCover.coverReduction();
        }
        if (coverId == "police_car") {
            return state_.policeCar.coverReduction();
        }
        if (coverId == "bmp_2") {
            return !state_.vehicle.moving && !state_.vehicle.disabled ? 35 : 0;
        }
        return 0;
    }

    int organizationOf(FactionId faction) const {
        switch (faction) {
        case FactionId::ArmedCivilians: return state_.civilianOrganization;
        case FactionId::Mvd: return state_.mvdOrganization;
        case FactionId::YeltsinSupporters:
            return state_.supporterOrganization;
        case FactionId::CommitteeArmy: return state_.committeeOrganization;
        }
        return 0;
    }

    int factionMoraleOf(FactionId faction) const {
        switch (faction) {
        case FactionId::ArmedCivilians: return state_.civilianMorale;
        case FactionId::Mvd: return state_.mvdMorale;
        case FactionId::YeltsinSupporters: return state_.supporterMorale;
        case FactionId::CommitteeArmy: return state_.committeeMorale;
        }
        return 0;
    }

    void recordEnemyCasualty(EnemyPerson& enemy, int damage, bool killed) {
        int* moraleValue = nullptr;
        switch (enemy.faction) {
        case FactionId::ArmedCivilians:
            moraleValue = &state_.civilianMorale;
            break;
        case FactionId::Mvd:
            moraleValue = &state_.mvdMorale;
            break;
        case FactionId::YeltsinSupporters:
            moraleValue = &state_.supporterMorale;
            break;
        case FactionId::CommitteeArmy:
            moraleValue = &state_.committeeMorale;
            break;
        }
        if (moraleValue == nullptr) {
            return;
        }
        const int moraleLoss = std::max(3, damage / 9) + (killed ? 18 : 0);
        const int organizationLoss = std::max(2, damage / 18) + (killed ? 10 : 0);
        *moraleValue = std::max(0, *moraleValue - moraleLoss);
        adjustOrganization(enemy.faction, organizationLoss);
        output_ << "  " << factionName(enemy.faction)
                << " 整体士气 -" << moraleLoss << "、组织度 -" << organizationLoss
                << "(当前 " << *moraleValue << "/100、"
                << organizationOf(enemy.faction) << "/100)。\n";
    }

    void adjustOrganization(FactionId faction, int loss) {
        int* value = nullptr;
        switch (faction) {
        case FactionId::ArmedCivilians:
            value = &state_.civilianOrganization;
            break;
        case FactionId::Mvd:
            value = &state_.mvdOrganization;
            break;
        case FactionId::YeltsinSupporters:
            value = &state_.supporterOrganization;
            break;
        case FactionId::CommitteeArmy:
            value = &state_.committeeOrganization;
            break;
        }
        if (value != nullptr) {
            *value = std::max(0, *value - loss);
        }
    }

    void igniteWoodenCover(std::string_view cause) {
        if (state_.woodenCover.condition <= 0) return;
        state_.woodenCover.burningRounds = 2;
        state_.woodenCover.condition =
            std::max(0, state_.woodenCover.condition - 25);
        output_ << state_.woodenCover.name << " 因" << cause
                << "起火,掩护效果暂时失效;里面的人必须撤离。\n";
        for (EnemyPerson& enemy : state_.enemies) {
            if (enemy.active() && enemy.coverId == "wooden_barricade") {
                adjustOrganization(enemy.faction, 4);
                enemy.morale = std::max(0, enemy.morale - 8);
            }
        }
    }

    void resolveMolotov(FriendlyPerson& person, const TargetChoice& target) {
        if (state_.ammo.molotovs <= 0) return;
        --state_.ammo.molotovs;
        output_ << "\n【" << person.id << " 投掷燃烧瓶】\n";
        if (target.woodenCover) {
            igniteWoodenCover("燃烧瓶");
            state_.tension = std::min(100, state_.tension + 18);
            state_.bystanderRisk = std::min(100, state_.bystanderRisk + 12);
            maybeInjureBystander(12);
            return;
        }
        EnemyPerson& enemy = state_.enemies[target.enemyIndex];
        if (rng_.below(100) >= 72) {
            enemy.suppression = std::min(100, enemy.suppression + 28);
            output_ << "燃烧瓶落在目标附近,未直接命中,但造成强烈压制。\n";
        } else {
            const int damage = rng_.inclusive(18, 32);
            enemy.health = std::max(0, enemy.health - damage);
            enemy.morale = std::max(0, enemy.morale - 16);
            enemy.suppression = std::min(100, enemy.suppression + 36);
            const bool killed = enemy.health == 0 && rng_.below(100) < 20;
            recordEnemyCasualty(enemy, damage, killed);
            output_ << "命中 " << enemy.id << ":生命 -" << damage
                    << ",压制 +36,士气 -16。\n";
            if (enemy.health == 0) enemy.status = killed ? EnemyStatus::Killed
                                                         : EnemyStatus::Incapacitated;
        }
        if (enemy.coverId == "wooden_barricade") {
            igniteWoodenCover("燃烧瓶");
        }
        state_.tension = std::min(100, state_.tension + 16);
        state_.bystanderRisk = std::min(100, state_.bystanderRisk + 14);
        maybeInjureBystander(16);
    }

    void resolveWoodenCoverAttack(const FriendlyPerson& person, Action action) {
        if (action != Action::CannonFire) return;
        state_.ammo.cannon30mm = std::max(0, state_.ammo.cannon30mm - 3);
        output_ << "\n【" << person.id << " 以 30mm 炮攻击木制掩体】\n";
        if (rng_.below(100) < 65) {
            state_.woodenCover.condition = std::max(
                0, state_.woodenCover.condition - rng_.inclusive(55, 80));
            if (rng_.below(100) < 38) igniteWoodenCover("机炮命中");
            else output_ << "木制掩体受损,但没有起火。\n";
            for (EnemyPerson& enemy : state_.enemies) {
                if (enemy.active() && enemy.coverId == "wooden_barricade") {
                    enemy.suppression = std::min(100, enemy.suppression + 35);
                    enemy.morale = std::max(0, enemy.morale - 12);
                    adjustOrganization(enemy.faction, 4);
                }
            }
        } else {
            output_ << "炮弹没有命中掩体。\n";
        }
        state_.discipline = std::max(0, state_.discipline - 10);
        state_.tension = std::min(100, state_.tension + 22);
        state_.bystanderRisk = std::min(100, state_.bystanderRisk + 20);
        maybeInjureBystander(18);
    }

    bool anyFriendlyUsingWoodCover() const {
        return std::any_of(state_.friendly.begin(), state_.friendly.end(),
                           [](const FriendlyPerson& person) {
                               return person.health > 0 && !person.mounted &&
                                      person.coverId == "wooden_barricade";
                           });
    }

    bool hasSameLocationFriendly(const EnemyPerson& enemy) const {
        return std::any_of(state_.friendly.begin(), state_.friendly.end(),
                           [&enemy](const FriendlyPerson& person) {
                               return person.health > 0 && !person.mounted &&
                                      person.location == enemy.location;
                           });
    }

    FriendlyPerson* closestDismountedFriendly(const EnemyPerson& enemy) {
        FriendlyPerson* best = nullptr;
        int bestDistance = 99;
        for (FriendlyPerson& person : state_.friendly) {
            if (person.health <= 0 || person.mounted) continue;
            const int distance = std::abs(locationIndex(person.location) -
                                          locationIndex(enemy.location));
            if (distance < bestDistance) {
                best = &person;
                bestDistance = distance;
            }
        }
        return bestDistance <= 1 ? best : nullptr;
    }

    std::size_t bestTargetIndex(const EnemyPerson& enemy,
                                const std::vector<std::size_t>& targets) const {
        std::size_t best = targets.front();
        int bestScore = std::numeric_limits<int>::min();
        for (std::size_t index : targets) {
            const FriendlyPerson& person = state_.friendly[index];
            int score = 35 - coverReduction(person.coverId) +
                        (100 - person.health) / 3 +
                        (person.id == "C1" ? 8 : 0) +
                        (person.location == enemy.location ? 10 : 0);
            if (person.suppression > 60) score -= 15;
            if (score > bestScore) {
                best = index;
                bestScore = score;
            }
        }
        return best;
    }

    bool seekEnemyCover(EnemyPerson& enemy) {
        const auto options = coverOptions(enemy.location);
        std::string selected;
        int bestProtection = 0;
        for (const std::string& option : options) {
            if (option == "bmp_2") continue;
            const int protection = coverReduction(option) +
                                   (enemy.profile == UnitProfile::MvdOfficer &&
                                            option == "police_car"
                                        ? 20
                                        : 0);
            if (protection > bestProtection) {
                selected = option;
                bestProtection = protection;
            }
        }
        if (selected.empty() || selected == enemy.coverId) return false;
        enemy.coverId.clear();
        triggerFriendlyOverwatch(enemy, "敌人转移到掩体");
        if (!enemy.active()) return true;
        enemy.coverId = selected;
        enemy.suppression = std::max(0, enemy.suppression - 8);
        enemy.stamina = std::max(0, enemy.stamina - 8);
        output_ << "  " << enemy.id << " 转移到 " << coverName(selected)
                << " 后方。\n";
        return true;
    }

    void triggerFriendlyOverwatch(EnemyPerson& enemy,
                                  std::string_view movement) {
        if (!isHostileToCrew(enemy)) {
            return;
        }
        for (FriendlyPerson& person : state_.friendly) {
            if (!person.overwatch || person.reactionUsed || person.health <= 0 ||
                person.mounted || person.suppression >= 60 ||
                std::abs(locationIndex(person.location) -
                         locationIndex(enemy.location)) > 1) {
                continue;
            }
            person.reactionUsed = true;
            person.overwatch = false;
            output_ << "  " << person.id << " 对" << movement
                    << "的 " << enemy.id << " 进行反应射击。\n";
            resolveEnemyAttack(person,
                               person.id == "M1" ? Action::PkmFire
                                                 : Action::PersonalFire,
                               enemy);
            if (!enemy.active()) return;
        }
    }

    void resolveReactionFireOnFriendlyMove(FriendlyPerson& target,
                                           std::string_view movement) {
        if (target.mounted || target.health <= 0) return;
        for (EnemyPerson& enemy : state_.enemies) {
            if (!enemy.active() || !isHostileToCrew(enemy) ||
                enemy.reactionUsed || enemy.suppression >= 25 ||
                std::abs(locationIndex(enemy.location) -
                         locationIndex(target.location)) > 1) {
                continue;
            }
            enemy.reactionUsed = true;
            output_ << "  " << enemy.id << " 抓住" << movement
                    << "时机进行反应射击。\n";
            attackFriendly(enemy, target);
            if (target.health <= 0) return;
        }
    }

    void resolveReactionFireOnVehicleMove(Location origin) {
        for (EnemyPerson& enemy : state_.enemies) {
            if (!enemy.active() || !isHostileToCrew(enemy) ||
                enemy.reactionUsed || enemy.suppression >= 25 ||
                std::abs(locationIndex(enemy.location) - locationIndex(origin)) > 1) {
                continue;
            }
            enemy.reactionUsed = true;
            output_ << "  " << enemy.id << " 对机动中的 BMP-2 进行反应射击。\n";
            attackVehicle(enemy);
        }
    }

    void resolvePassiveMelee(EnemyPerson& enemy, FriendlyPerson& person) {
        enemy.reactionUsed = true;
        output_ << "  " << enemy.id << " 在接敌时发起被动肉搏反应。\n";
        resolveEnemyMelee(enemy, person);
    }

    void resolveEnemyMelee(EnemyPerson& enemy, FriendlyPerson& person) {
        const int enemyScore = enemy.stamina - (100 - enemy.health) / 2 -
                               enemy.suppression / 3 + rng_.inclusive(0, 35);
        const int friendlyScore = person.stamina - (100 - person.health) / 2 -
                                  person.suppression / 3 + rng_.inclusive(0, 35);
        if (enemyScore >= friendlyScore) {
            const int damage = rng_.inclusive(18, 42);
            person.health = std::max(0, person.health - damage);
            person.stamina = std::max(0, person.stamina - 22);
            output_ << "  肉搏判定不利:" << person.id << " 受伤 -"
                    << damage << ",体力下降。\n";
        } else {
            enemy.stamina = std::max(0, enemy.stamina - 25);
            enemy.morale = std::max(0, enemy.morale - 12);
            adjustOrganization(enemy.faction, 4);
            output_ << "  " << person.id << " 挡开对方并拉开距离;"
                    << enemy.id << " 士气下降。\n";
        }
    }

    void resolveMelee(FriendlyPerson& person, EnemyPerson& enemy) {
        output_ << "\n【" << person.id << " 与 " << enemy.id << " 肉搏】\n";
        const int friendlyScore = person.stamina - (100 - person.health) / 2 -
                                  person.suppression / 3 + rng_.inclusive(0, 35);
        const int enemyScore = enemy.stamina - (100 - enemy.health) / 2 -
                               enemy.suppression / 3 + rng_.inclusive(0, 35);
        person.stamina = std::max(0, person.stamina - 20);
        enemy.stamina = std::max(0, enemy.stamina - 20);
        if (friendlyScore >= enemyScore) {
            const int damage = rng_.inclusive(22, 46);
            enemy.health = std::max(0, enemy.health - damage);
            enemy.morale = std::max(0, enemy.morale - 15);
            recordEnemyCasualty(enemy, damage, false);
            output_ << "判定成功:" << enemy.id << " 受伤 -" << damage
                    << ",士气下降。\n";
            if (enemy.health == 0) enemy.status = rng_.below(100) < 20
                                                      ? EnemyStatus::Killed
                                                      : EnemyStatus::Incapacitated;
        } else {
            const int damage = rng_.inclusive(12, 32);
            person.health = std::max(0, person.health - damage);
            output_ << "判定失利:" << person.id << " 受伤 -" << damage << "。\n";
        }
    }

    FriendlyPerson* sharedFriendlyById(const std::string& id) {
        const auto found = std::find_if(
            state_.friendly.begin(), state_.friendly.end(),
            [&id](const FriendlyPerson& person) { return person.id == id; });
        return found == state_.friendly.end() ? nullptr : &*found;
    }

    EnemyPerson* sharedEnemyById(const std::string& id) {
        const auto found = std::find_if(
            state_.enemies.begin(), state_.enemies.end(),
            [&id](const EnemyPerson& person) { return person.id == id; });
        return found == state_.enemies.end() ? nullptr : &*found;
    }

    FriendlyVehicle* sharedVehicleById(const std::string& id) {
        const auto found = std::find_if(
            state_.combatVehicles.begin(), state_.combatVehicles.end(),
            [&id](const FriendlyVehicle& vehicle) { return vehicle.id == id; });
        return found == state_.combatVehicles.end() ? nullptr : &*found;
    }

    const FriendlyVehicle* sharedVehicleById(const std::string& id) const {
        const auto found = std::find_if(
            state_.combatVehicles.begin(), state_.combatVehicles.end(),
            [&id](const FriendlyVehicle& vehicle) { return vehicle.id == id; });
        return found == state_.combatVehicles.end() ? nullptr : &*found;
    }

    TacticalCover* sharedCoverById(const std::string& id) {
        const auto found = std::find_if(
            state_.covers.begin(), state_.covers.end(),
            [&id](const TacticalCover& cover) { return cover.id == id; });
        return found == state_.covers.end() ? nullptr : &*found;
    }

    int sharedFriendlyPosition(const FriendlyPerson& person) const {
        if (!person.vehicleId.empty()) {
            if (const FriendlyVehicle* vehicle =
                    sharedVehicleById(person.vehicleId)) {
                return vehicle->axisPosition;
            }
        }
        return person.axisPosition >= 0 ? person.axisPosition
                                        : locationIndex(person.location);
    }

    int sharedEnemyPosition(const EnemyPerson& person) const {
        if (!person.vehicleId.empty()) {
            if (const FriendlyVehicle* vehicle =
                    sharedVehicleById(person.vehicleId)) {
                return vehicle->axisPosition;
            }
        }
        return person.axisPosition >= 0 ? person.axisPosition
                                        : locationIndex(person.location);
    }

    int sharedCoverProtection(const std::string& coverId) const {
        const auto found = std::find_if(
            state_.covers.begin(), state_.covers.end(),
            [&coverId](const TacticalCover& cover) {
                return cover.id == coverId;
            });
        if (found != state_.covers.end()) {
            if (found->durability <= 0) return 0;
            return std::min(
                40, 34 * found->durability /
                        std::max(1, found->maximumDurability));
        }
        return coverReduction(coverId);
    }

    TacticalCover* bestSharedCover(int position) {
        TacticalCover* best = nullptr;
        int bestValue = -1;
        for (TacticalCover& cover : state_.covers) {
            if (cover.position != position || cover.durability <= 0) continue;
            const int occupants = static_cast<int>(std::count_if(
                state_.friendly.begin(), state_.friendly.end(),
                [&cover](const FriendlyPerson& person) {
                    return person.health > 0 && !person.mounted &&
                           person.coverId == cover.id;
                })) + static_cast<int>(std::count_if(
                state_.enemies.begin(), state_.enemies.end(),
                [&cover](const EnemyPerson& person) {
                    return person.active() && !person.mounted &&
                           person.coverId == cover.id;
                }));
            if (occupants >= cover.capacity) continue;
            const int value =
                cover.durability * 100 / std::max(1, cover.maximumDurability) +
                cover.capacity * 3;
            if (value > bestValue) {
                best = &cover;
                bestValue = value;
            }
        }
        return best;
    }

    void damageSharedCover(const std::string& coverId, int damage) {
        TacticalCover* cover = sharedCoverById(coverId);
        if (cover == nullptr || damage <= 0) return;
        cover->durability = std::max(0, cover->durability - damage);
        output_ << "  " << cover->name << " 耐久 -" << damage << ",剩余 "
                << cover->durability << '/' << cover->maximumDurability
                << "。\n";
        if (cover->durability == 0) {
            for (FriendlyPerson& person : state_.friendly) {
                if (person.coverId == coverId) person.coverId.clear();
            }
            for (EnemyPerson& person : state_.enemies) {
                if (person.coverId == coverId) person.coverId.clear();
            }
            output_ << "  " << cover->name
                    << " 被重火力摧毁,占据者失去掩护。\n";
        }
    }

    void scoreSharedDefeat(EnemyPerson& enemy) {
        if (enemy.terminalScored) return;
        enemy.terminalScored = true;
        ++state_.score;
        state_.supportScore = state_.score;
        roundDefeats_.push_back({enemy.id, 1, false});
        output_ << "  击败结算: " << enemy.id << " +1 分,累计 "
                << state_.score << " 分(仅首次终止计分)。\n";
    }

    void scoreSharedDefeat(FriendlyVehicle& vehicle) {
        if (vehicle.terminalScored) return;
        vehicle.terminalScored = true;
        const int points =
            vehicle.kind == VehicleKind::T72 ||
                    vehicle.kind == VehicleKind::T80
                ? 5
                : 3;
        state_.score += points;
        state_.supportScore = state_.score;
        roundDefeats_.push_back({vehicle.id, points, true});
        output_ << "  载具击败结算: " << vehicle.id << " " << vehicle.name
                << " +" << points << " 分,累计 " << state_.score
                << " 分(仅首次终止计分)。\n";
    }

    void applySharedEnemyDamage(EnemyPerson& target, int rawDamage,
                                const WeaponSpec& spec) {
        int damage = rawDamage;
        const bool ignoresCover =
            spec.heavy && state_.policy.heavyWeaponsIgnoreCover;
        if (target.bodyArmor) damage = std::max(1, damage * 82 / 100);
        if (!ignoresCover) {
            const int reduction = sharedCoverProtection(target.coverId);
            damage = std::max(1, damage * (100 - reduction) / 100);
        }
        target.health = std::max(0, target.health - damage);
        target.morale = std::max(
            0, target.morale - std::max(3, damage / (spec.heavy ? 2 : 3)));
        target.suppression =
            std::min(100, target.suppression + (spec.heavy ? 38 : 22));
        output_ << "  命中 " << target.id << ",生命 -" << damage
                << ",剩余 " << target.health
                << "/100,士气 " << target.morale << "/100。";
        if (ignoresCover) {
            output_ << " 重武器绕过掩体。";
        } else if (!target.coverId.empty()) {
            output_ << " 轻武器伤害已按掩体减免。";
        }
        output_ << '\n';
        if (ignoresCover && !target.coverId.empty()) {
            damageSharedCover(target.coverId,
                              std::max(8, spec.maximumDamage / 2));
        }
        if (target.health == 0) {
            target.status = rng_.below(100) < (spec.heavy ? 62 : 36)
                                ? EnemyStatus::Killed
                                : EnemyStatus::Incapacitated;
            output_ << "  " << enemyStatusLabel(target) << "。\n";
            scoreSharedDefeat(target);
            return;
        }
        if (target.morale <= 18 && rng_.below(100) < 42) {
            target.status = rng_.below(100) < 45 ? EnemyStatus::Surrendered
                                                : EnemyStatus::Fled;
            target.coverId.clear();
            output_ << "  士气崩溃: " << enemyStatusLabel(target) << "。\n";
            scoreSharedDefeat(target);
        }
    }

    void applySharedFriendlyDamage(FriendlyPerson& target, int rawDamage,
                                   const WeaponSpec& spec) {
        int damage = rawDamage;
        const bool ignoresCover =
            spec.heavy && state_.policy.heavyWeaponsIgnoreCover;
        if (target.bodyArmor) damage = std::max(1, damage * 82 / 100);
        if (!ignoresCover) {
            const int reduction = sharedCoverProtection(target.coverId);
            damage = std::max(1, damage * (100 - reduction) / 100);
        }
        target.health = std::max(0, target.health - damage);
        target.suppression =
            std::min(100, target.suppression + (spec.heavy ? 38 : 22));
        target.stamina = std::max(0, target.stamina - damage / 4);
        target.morale = std::max(0, target.morale - std::max(2, damage / 4));
        output_ << "  友军 " << target.id << " 生命 -" << damage
                << ",剩余 " << target.health << "/100。\n";
        if (ignoresCover && !target.coverId.empty()) {
            damageSharedCover(target.coverId,
                              std::max(8, spec.maximumDamage / 2));
        }
        if (target.health == 0) {
            target.killed = spec.heavy && rng_.below(100) < 62;
            output_ << "  " << target.id
                    << (target.killed ? " 遭致命命中。" :
                                        " 失去行动能力。")
                    << '\n';
        }
    }

    void applySharedVehicleDamage(FriendlyVehicle& target, int rawDamage,
                                  bool attackerFriendly) {
        (void)attackerFriendly;
        target.condition = std::max(0, target.condition - rawDamage);
        target.suppression = std::min(100, target.suppression + 24);
        output_ << "  载具命中: " << target.id << " " << target.name
                << " 车况 -" << rawDamage << ",剩余 " << target.condition
                << '/' << target.maximumCondition << "。\n";
        if (target.condition > 0) return;
        target.disabled = true;
        target.moving = false;
        output_ << "  " << target.name << " 失去机动和火力。\n";
        if (target.hostile) scoreSharedDefeat(target);
        const auto dismountCrew = [this, &target](auto& people) {
            for (auto& person : people) {
                if (person.vehicleId != target.id || !person.mounted) continue;
                person.mounted = false;
                person.vehicleId.clear();
                person.axisPosition = target.axisPosition;
                person.coverId.clear();
                if (rng_.below(100) < 35) {
                    person.health = 0;
                    output_ << "  " << person.id
                            << " 在弃车时失去行动能力。\n";
                } else {
                    output_ << "  " << person.id
                            << " 弃车,成为独立步兵。\n";
                }
            }
        };
        if (target.hostile) {
            dismountCrew(state_.enemies);
            for (EnemyPerson& person : state_.enemies) {
                if (person.vehicleId == target.id && person.health <= 0) {
                    scoreSharedDefeat(person);
                }
            }
        } else {
            dismountCrew(state_.friendly);
        }
    }

    CombatResolution resolveSharedAttack(const AttackRequest& request) {
        CombatResolution resolution;
        WeaponSpec spec = request.airAttack
            ? WeaponSpec{"航空攻击", 5, 90, 62, 92, true, true}
            : weaponSpec(request.weapon);

        FriendlyPerson* friendlyAttacker =
            request.friendlyAttacker
                ? sharedFriendlyById(request.attackerId)
                : nullptr;
        EnemyPerson* enemyAttacker =
            request.friendlyAttacker
                ? nullptr
                : sharedEnemyById(request.attackerId);
        if ((request.friendlyAttacker && friendlyAttacker == nullptr) ||
            (!request.friendlyAttacker && enemyAttacker == nullptr)) {
            output_ << "  攻击者不存在,行动未执行。\n";
            return resolution;
        }

        int attackerPosition = request.friendlyAttacker
            ? sharedFriendlyPosition(*friendlyAttacker)
            : sharedEnemyPosition(*enemyAttacker);
        int attackerSuppression = request.friendlyAttacker
            ? friendlyAttacker->suppression
            : enemyAttacker->suppression;

        EnemyPerson* enemyTarget =
            request.friendlyAttacker ? sharedEnemyById(request.targetId)
                                     : nullptr;
        FriendlyPerson* friendlyTarget =
            request.friendlyAttacker ? nullptr
                                     : sharedFriendlyById(request.targetId);
        FriendlyVehicle* vehicleTarget =
            sharedVehicleById(request.targetId);

        const int targetPosition = enemyTarget != nullptr
            ? sharedEnemyPosition(*enemyTarget)
            : (friendlyTarget != nullptr ? sharedFriendlyPosition(*friendlyTarget)
                                        : (vehicleTarget != nullptr
                                               ? vehicleTarget->axisPosition
                                               : -1));
        if (targetPosition < 0) {
            output_ << "  目标不存在,行动未执行。\n";
            return resolution;
        }
        if (vehicleTarget != nullptr &&
            vehicleTarget->hostile != request.friendlyAttacker) {
            output_ << "  目标阵营无效,行动未执行。\n";
            return resolution;
        }
        if (enemyTarget != nullptr &&
            (enemyTarget->disposition != Disposition::Hostile ||
             !enemyTarget->active())) {
            output_ << "  目标不是可交战的敌对单位。\n";
            return resolution;
        }
        if (friendlyTarget != nullptr &&
            (friendlyTarget->health <= 0 || friendlyTarget->mounted)) {
            output_ << "  目标不是可攻击的下车人员。\n";
            return resolution;
        }

        const int distance =
            axisDistance(attackerPosition, targetPosition);
        if (distance > spec.maximumRange) {
            output_ << "  " << spec.name << " 最大有效距离 "
                    << spec.maximumRange << ",目标距离 " << distance
                    << ";不能浪费这次行动。\n";
            return resolution;
        }
        if (vehicleTarget != nullptr && !spec.canTargetVehicles) {
            const int hitChance = std::clamp(
                spec.baseHitChance - distance * 8 -
                    attackerSuppression / 5,
                8, 82);
            output_ << "  " << request.attackerId << " 用 " << spec.name
                    << " 压制 " << request.targetId << " 的车体"
                    << "(距离 " << distance << ",命中 " << hitChance
                    << "%)。\n";
            resolution.executed = true;
            if (rng_.below(100) < hitChance) {
                const int lightDamage = rng_.inclusive(2, 6);
                applySharedVehicleDamage(*vehicleTarget, lightDamage,
                                         request.friendlyAttacker);
                resolution.damage = lightDamage;
                resolution.defeated =
                    vehicleTarget->condition <= 0;
            } else {
                output_ << "  轻武器未能损伤装甲。\n";
            }
            return resolution;
        }
        if (request.weapon == WeaponKind::Konkurs &&
            vehicleTarget == nullptr) {
            output_ << "  Konkurs 只能锁定装甲载具。\n";
            return resolution;
        }

        int coverPenalty = 0;
        const std::string targetCover = enemyTarget != nullptr
            ? enemyTarget->coverId
            : (friendlyTarget != nullptr ? friendlyTarget->coverId : "");
        if (!(spec.heavy && state_.policy.heavyWeaponsIgnoreCover)) {
            coverPenalty = sharedCoverProtection(targetCover) / 2;
        }
        int moralePenalty = 0;
        if (request.friendlyAttacker && enemyTarget != nullptr &&
            enemyTarget->morale < 35) {
            moralePenalty = -5;
        } else if (!request.friendlyAttacker && friendlyTarget != nullptr &&
                   friendlyTarget->morale < 35) {
            moralePenalty = -5;
        }
        const int hitChance = std::clamp(
            spec.baseHitChance - distance * 8 -
                attackerSuppression / 5 -
                (vehicleTarget != nullptr && vehicleTarget->moving ? 10 : 0) -
                coverPenalty + moralePenalty,
            8, 94);
        output_ << "  " << request.attackerId << " 用 " << spec.name
                << " 攻击 " << request.targetId << "(距离 " << distance
                << ",命中 " << hitChance << "%)。\n";

        if (request.friendlyAttacker && friendlyAttacker != nullptr &&
            friendlyAttacker->personalAmmo > 0) {
            --friendlyAttacker->personalAmmo;
        } else if (!request.friendlyAttacker && enemyAttacker != nullptr &&
                   enemyAttacker->personalAmmo > 0) {
            --enemyAttacker->personalAmmo;
        }
        resolution.executed = true;
        if (rng_.below(100) >= hitChance) {
            if (enemyTarget != nullptr) {
                enemyTarget->suppression =
                    std::min(100, enemyTarget->suppression + 12);
                output_ << "  未命中;目标压制 " << enemyTarget->suppression
                        << "/100。\n";
            } else if (friendlyTarget != nullptr) {
                friendlyTarget->suppression =
                    std::min(100, friendlyTarget->suppression + 12);
                output_ << "  未命中;目标压制 "
                        << friendlyTarget->suppression << "/100。\n";
            } else {
                output_ << "  未命中,装甲目标仍保持机动。\n";
            }
            return resolution;
        }

        const int rawDamage = request.rawDamage > 0
            ? request.rawDamage
            : rng_.inclusive(spec.minimumDamage, spec.maximumDamage);
        resolution.damage = rawDamage;
        if (enemyTarget != nullptr) {
            applySharedEnemyDamage(*enemyTarget, rawDamage, spec);
            resolution.defeated = !enemyTarget->active();
        } else if (friendlyTarget != nullptr) {
            applySharedFriendlyDamage(*friendlyTarget, rawDamage, spec);
            resolution.defeated = friendlyTarget->health <= 0;
        } else if (vehicleTarget != nullptr) {
            applySharedVehicleDamage(*vehicleTarget, rawDamage,
                                     request.friendlyAttacker);
            resolution.defeated =
                vehicleTarget->condition <= 0;
        }
        return resolution;
    }

    CombatResolution resolveSharedAirAttack(const AttackRequest& request) {
        AttackRequest air = request;
        air.airAttack = true;
        air.weapon = WeaponKind::TankGun;
        air.rawDamage = 0;
        return resolveSharedAttack(air);
    }

    bool resolveSharedAntiAir(bool friendlyAir) {
        int strength = 0;
        if (friendlyAir) {
            strength = static_cast<int>(std::count_if(
                state_.enemies.begin(), state_.enemies.end(),
                [](const EnemyPerson& person) {
                    return person.active() && !person.mounted &&
                           (person.weaponKind ==
                                WeaponKind::AutomaticRifle ||
                            person.weaponKind ==
                                WeaponKind::MachineGun);
                }));
        } else {
            strength = static_cast<int>(std::count_if(
                state_.friendly.begin(), state_.friendly.end(),
                [](const FriendlyPerson& person) {
                    return person.health > 0 && !person.mounted &&
                           (person.weapon ==
                                WeaponKind::AutomaticRifle ||
                            person.weapon == WeaponKind::MachineGun);
                }));
        }
        const int chance = std::clamp(
            18 + strength * 7 + state_.round * 2, 18, 78);
        output_ << "  对空准备: " << strength
                << " 个下车单位组织轻武器拦阻,驱离概率 "
                << chance << "%。\n";
        return rng_.below(100) < chance;
    }

    void triggerSharedReactionFire(FriendlyPerson& target) {
        if (target.mounted || target.health <= 0) return;
        for (EnemyPerson& enemy : state_.enemies) {
            if (!enemy.active() || enemy.mounted || enemy.reactionUsed ||
                enemy.suppression >= 25) {
                continue;
            }
            const int distance =
                axisDistance(sharedEnemyPosition(enemy),
                             sharedFriendlyPosition(target));
            if (distance > weaponSpec(enemy.weaponKind).maximumRange) continue;
            enemy.reactionUsed = true;
            output_ << "  敌军 " << enemy.id << " 对移动暴露的 "
                    << target.id << " 进行反应射击。\n";
            AttackRequest request;
            request.attackerId = enemy.id;
            request.targetId = target.id;
            request.weapon = enemy.weaponKind;
            request.friendlyAttacker = false;
            (void)resolveSharedAttack(request);
            if (target.health <= 0) return;
        }
    }

    void triggerSharedOverwatch(EnemyPerson& movingEnemy) {
        for (FriendlyPerson& friendly : state_.friendly) {
            if (!friendly.overwatch || friendly.reactionUsed ||
                friendly.health <= 0 || friendly.mounted ||
                friendly.suppression >= 60) {
                continue;
            }
            const int distance =
                axisDistance(sharedFriendlyPosition(friendly),
                             sharedEnemyPosition(movingEnemy));
            if (distance > weaponSpec(friendly.weapon).maximumRange) continue;
            friendly.reactionUsed = true;
            friendly.overwatch = false;
            output_ << "  " << friendly.id << " 对移动中的 "
                    << movingEnemy.id << " 进行警戒射击。\n";
            AttackRequest request;
            request.attackerId = friendly.id;
            request.targetId = movingEnemy.id;
            request.weapon = friendly.weapon;
            request.friendlyAttacker = true;
            (void)resolveSharedAttack(request);
            if (!movingEnemy.active()) return;
        }
    }

    void resolveSharedMelee(FriendlyPerson& friendly, EnemyPerson& enemy) {
        output_ << "\n【" << friendly.id << " 与 " << enemy.id << " 肉搏】\n";
        const int friendlyScore =
            friendly.stamina - (100 - friendly.health) / 2 -
            friendly.suppression / 3 + rng_.inclusive(0, 35);
        const int enemyScore =
            enemy.stamina - (100 - enemy.health) / 2 -
            enemy.suppression / 3 + rng_.inclusive(0, 35);
        friendly.stamina = std::max(0, friendly.stamina - 20);
        enemy.stamina = std::max(0, enemy.stamina - 20);
        const WeaponSpec melee{"肉搏", 0, 60, 18, 38, false, false};
        if (friendlyScore >= enemyScore) {
            applySharedEnemyDamage(enemy, rng_.inclusive(22, 46), melee);
        } else {
            applySharedFriendlyDamage(friendly, rng_.inclusive(16, 34), melee);
        }
    }

    bool executeSharedFriendlyCommand(const FriendlyCommand& command) {
        FriendlyPerson* actor = sharedFriendlyById(command.actorId);
        if (actor == nullptr || actor->health <= 0 || actor->acted) {
            output_ << "  该人物不能接受新命令。\n";
            return false;
        }
        auto finish = [actor]() {
            actor->acted = true;
            return true;
        };

        if (command.action == Action::Hold) {
            output_ << "  " << actor->id << " 保持位置。\n";
            return finish();
        }
        if (command.action == Action::Overwatch) {
            actor->overwatch = true;
            output_ << "  " << actor->id << " 进入警戒。\n";
            return finish();
        }
        if (command.action == Action::Recover) {
            actor->suppression = std::max(0, actor->suppression - 45);
            actor->stamina = std::min(100, actor->stamina + 18);
            output_ << "  " << actor->id << " 稳定状态,压制下降。\n";
            return finish();
        }
        if (command.action == Action::MoveOnFoot) {
            if (actor->mounted) {
                output_ << "  必须下车后才能徒步移动。\n";
                return false;
            }
            const int current = sharedFriendlyPosition(*actor);
            const int destination = command.destination >= 0
                ? std::clamp(command.destination, 0,
                             state_.policy.distanceMaximum)
                : std::clamp(current + command.direction, 0,
                             state_.policy.distanceMaximum);
            actor->coverId.clear();
            triggerSharedReactionFire(*actor);
            if (actor->health <= 0) return finish();
            actor->axisPosition = destination;
            output_ << "  " << actor->id << " 徒步移动到 "
                    << positionBand(destination) << "。\n";
            return finish();
        }
        if (command.action == Action::TakeCover) {
            if (actor->mounted) {
                output_ << "  车内人员不能占据地面掩体。\n";
                return false;
            }
            TacticalCover* cover =
                bestSharedCover(sharedFriendlyPosition(*actor));
            if (cover == nullptr) {
                output_ << "  当前地点没有可用掩体。\n";
                return false;
            }
            actor->coverId.clear();
            triggerSharedReactionFire(*actor);
            if (actor->health <= 0) return finish();
            actor->coverId = cover->id;
            output_ << "  " << actor->id << " 进入 " << cover->name
                    << "。\n";
            return finish();
        }
        if (command.action == Action::Dismount) {
            FriendlyVehicle* vehicle =
                sharedVehicleById(actor->vehicleId);
            if (vehicle == nullptr || !actor->mounted || vehicle->moving ||
                vehicle->disabled) {
                output_ << "  当前不能下车。\n";
                return false;
            }
            actor->mounted = false;
            actor->axisPosition = vehicle->axisPosition;
            if (TacticalCover* cover = bestSharedCover(actor->axisPosition)) {
                actor->coverId = cover->id;
            }
            output_ << "  " << actor->id << " 下车到 "
                    << positionBand(actor->axisPosition) << "。\n";
            triggerSharedReactionFire(*actor);
            return finish();
        }
        if (command.action == Action::Remount) {
            FriendlyVehicle* vehicle =
                sharedVehicleById(command.targetId);
            if (vehicle == nullptr || vehicle->hostile ||
                vehicle->disabled || vehicle->moving ||
                sharedFriendlyPosition(*actor) != vehicle->axisPosition) {
                output_ << "  该载具当前不能上车。\n";
                return false;
            }
            actor->mounted = true;
            actor->coverId.clear();
            actor->vehicleId = vehicle->id;
            output_ << "  " << actor->id << " 返回 " << vehicle->name
                    << "。\n";
            return finish();
        }
        if (command.action == Action::MoveVehicle) {
            FriendlyVehicle* vehicle =
                sharedVehicleById(actor->vehicleId);
            if (vehicle == nullptr || vehicle->hostile || vehicle->disabled ||
                vehicle->moving || !actor->mounted) {
                output_ << "  驾驶员当前不能移动该载具。\n";
                return false;
            }
            const int origin = vehicle->axisPosition;
            for (EnemyPerson& enemy : state_.enemies) {
                if (!enemy.active() || enemy.reactionUsed ||
                    enemy.suppression >= 25) continue;
                if (!weaponSpec(enemy.weaponKind).canTargetVehicles) {
                    continue;
                }
                const int distance =
                    axisDistance(sharedEnemyPosition(enemy), origin);
                if (distance >
                    weaponSpec(enemy.weaponKind).maximumRange) continue;
                enemy.reactionUsed = true;
                AttackRequest request;
                request.attackerId = enemy.id;
                request.targetId = vehicle->id;
                request.weapon = enemy.weaponKind;
                request.friendlyAttacker = false;
                (void)resolveSharedAttack(request);
            }
            vehicle->axisPosition = std::clamp(
                origin + command.direction, 0,
                state_.policy.distanceMaximum);
            vehicle->moving = true;
            for (FriendlyPerson& crew : state_.friendly) {
                if (crew.vehicleId == vehicle->id && crew.mounted) {
                    crew.axisPosition = vehicle->axisPosition;
                }
            }
            output_ << "  " << vehicle->id << " 移动到 "
                    << positionBand(vehicle->axisPosition) << "。\n";
            return finish();
        }
        if (command.action == Action::Melee) {
            EnemyPerson* enemy = sharedEnemyById(command.targetId);
            if (enemy == nullptr || !enemy->active() || actor->mounted ||
                enemy->mounted ||
                axisDistance(sharedFriendlyPosition(*actor),
                             sharedEnemyPosition(*enemy)) != 0) {
                output_ << "  只有接触距离内的下车单位可以肉搏。\n";
                return false;
            }
            resolveSharedMelee(*actor, *enemy);
            return finish();
        }

        if (command.action == Action::PersonalFire ||
            command.action == Action::MakarovFire ||
            command.action == Action::PkmFire ||
            command.action == Action::CoaxialFire ||
            command.action == Action::CannonFire ||
            command.action == Action::Konkurs) {
            FriendlyVehicle* vehicle =
                sharedVehicleById(actor->vehicleId);
            WeaponKind weapon = command.weapon;
            if (vehicle != nullptr && actor->mounted) {
                if (command.action == Action::CannonFire) {
                    if (vehicle->cannonAmmo < 3) {
                        output_ << "  该载具弹药不足。\n";
                        return false;
                    }
                    vehicle->cannonAmmo -= 3;
                    weapon = vehicle->kind == VehicleKind::T72 ||
                                     vehicle->kind == VehicleKind::T80
                        ? WeaponKind::TankGun
                        : (vehicle->kind == VehicleKind::Btr80
                               ? WeaponKind::Autocannon30mm
                               : WeaponKind::Autocannon30mm);
                } else if (command.action == Action::Konkurs &&
                           vehicle->konkursAmmo > 0) {
                    --vehicle->konkursAmmo;
                    weapon = WeaponKind::Konkurs;
                }
            }
            AttackRequest request;
            request.attackerId = actor->id;
            request.targetId = command.targetId;
            request.weapon = weapon;
            request.friendlyAttacker = true;
            const CombatResolution result = resolveSharedAttack(request);
            if (!result.executed) return false;
            if (vehicle != nullptr && command.action == Action::CannonFire) {
                vehicle->acted = true;
            }
            return finish();
        }
        if (command.action == Action::Withdraw) {
            state_.withdrawalRequested = true;
            output_ << "  玩家命令全队撤出列宁大街。\n";
            return finish();
        }
        output_ << "  该命令在自由防御中不可用。\n";
        return false;
    }

    int nearestFriendlyPosition(int from) const {
        int best = from;
        int bestDistance = std::numeric_limits<int>::max();
        for (const FriendlyPerson& person : state_.friendly) {
            if (person.health <= 0) continue;
            const int candidate = sharedFriendlyPosition(person);
            const int distance = axisDistance(from, candidate);
            if (distance < bestDistance) {
                best = candidate;
                bestDistance = distance;
            }
        }
        for (const FriendlyVehicle& vehicle : state_.combatVehicles) {
            if (vehicle.hostile || vehicle.disabled) continue;
            const int distance = axisDistance(from, vehicle.axisPosition);
            if (distance < bestDistance) {
                best = vehicle.axisPosition;
                bestDistance = distance;
            }
        }
        return best;
    }

    void resolveSharedFriendlyVehicleTurn(FriendlyVehicle& vehicle) {
        if (vehicle.hostile || vehicle.disabled || vehicle.acted ||
            vehicle.cannonAmmo <= 0) {
            return;
        }
        const auto gunner = std::find_if(
            state_.friendly.begin(), state_.friendly.end(),
            [&vehicle](const FriendlyPerson& person) {
                return person.health > 0 && person.mounted &&
                       person.vehicleId == vehicle.id;
            });
        if (gunner == state_.friendly.end()) return;
        const WeaponKind weapon =
            vehicle.kind == VehicleKind::T72 ||
                    vehicle.kind == VehicleKind::T80
                ? WeaponKind::TankGun
                : (vehicle.kind == VehicleKind::Btr80
                       ? WeaponKind::Autocannon30mm
                       : WeaponKind::Autocannon30mm);
        const WeaponSpec spec = weaponSpec(weapon);
        for (const FriendlyVehicle& target : state_.combatVehicles) {
            if (!target.hostile || target.disabled ||
                axisDistance(vehicle.axisPosition, target.axisPosition) >
                    spec.maximumRange) {
                continue;
            }
            vehicle.cannonAmmo = std::max(0, vehicle.cannonAmmo - 3);
            AttackRequest request;
            request.attackerId = gunner->id;
            request.targetId = target.id;
            request.weapon = weapon;
            request.friendlyAttacker = true;
            (void)resolveSharedAttack(request);
            vehicle.acted = true;
            return;
        }
        for (const EnemyPerson& target : state_.enemies) {
            if (!target.active() || target.mounted ||
                axisDistance(vehicle.axisPosition,
                             sharedEnemyPosition(target)) >
                    spec.maximumRange) {
                continue;
            }
            vehicle.cannonAmmo = std::max(0, vehicle.cannonAmmo - 3);
            AttackRequest request;
            request.attackerId = gunner->id;
            request.targetId = target.id;
            request.weapon = weapon;
            request.friendlyAttacker = true;
            (void)resolveSharedAttack(request);
            vehicle.acted = true;
            return;
        }
        vehicle.acted = true;
        output_ << "  " << vehicle.id << " 没有射程内目标,保持防御位置。\n";
    }

    void resolveSharedEnemyVehicleTurn(FriendlyVehicle& vehicle) {
        if (!vehicle.hostile || vehicle.disabled || vehicle.acted) return;
        const bool carrier = vehicle.kind == VehicleKind::Btr80 ||
                             vehicle.kind == VehicleKind::Bmp2;
        const int targetPosition = nearestFriendlyPosition(vehicle.axisPosition);
        const int distance = axisDistance(vehicle.axisPosition, targetPosition);

        if (carrier &&
            (vehicle.axisPosition <= 2 ||
             (vehicle.axisPosition <= 4 &&
              rng_.below(100) < 55))) {
            bool unloaded = false;
            for (EnemyPerson& person : state_.enemies) {
                if (person.vehicleId == vehicle.id && person.mounted &&
                    person.active()) {
                    person.mounted = false;
                    person.axisPosition = vehicle.axisPosition;
                    person.coverId.clear();
                    unloaded = true;
                    output_ << "  " << vehicle.id << " 卸载 " << person.id
                            << " 到 " << positionBand(vehicle.axisPosition)
                            << "。\n";
                }
            }
            if (unloaded) {
                vehicle.acted = true;
                return;
            }
        }
        if ((vehicle.kind == VehicleKind::T72 ||
             vehicle.kind == VehicleKind::T80) &&
            distance > 2 && rng_.below(100) < 48) {
            --vehicle.axisPosition;
            vehicle.moving = true;
            output_ << "  " << vehicle.id << " 推进到 "
                    << positionBand(vehicle.axisPosition) << "。\n";
        } else if (carrier && distance > 2 && rng_.below(100) < 42) {
            --vehicle.axisPosition;
            vehicle.moving = true;
            output_ << "  " << vehicle.id << " 运兵车推进到 "
                    << positionBand(vehicle.axisPosition) << "。\n";
        }

        if (vehicle.cannonAmmo <= 0) {
            vehicle.acted = true;
            return;
        }
        const auto gunner = std::find_if(
            state_.enemies.begin(), state_.enemies.end(),
            [&vehicle](const EnemyPerson& person) {
                return person.active() && person.mounted &&
                       person.vehicleId == vehicle.id;
            });
        if (gunner == state_.enemies.end()) {
            vehicle.acted = true;
            return;
        }
        const WeaponKind weapon =
            vehicle.kind == VehicleKind::T72 ||
                    vehicle.kind == VehicleKind::T80
                ? WeaponKind::TankGun
                : WeaponKind::Autocannon30mm;
        const WeaponSpec spec = weaponSpec(weapon);
        for (const FriendlyVehicle& target : state_.combatVehicles) {
            if (target.hostile || target.disabled ||
                axisDistance(vehicle.axisPosition, target.axisPosition) >
                    spec.maximumRange) {
                continue;
            }
            vehicle.cannonAmmo = std::max(0, vehicle.cannonAmmo - 3);
            AttackRequest request;
            request.attackerId = gunner->id;
            request.targetId = target.id;
            request.weapon = weapon;
            request.friendlyAttacker = false;
            (void)resolveSharedAttack(request);
            vehicle.acted = true;
            return;
        }
        for (const FriendlyPerson& target : state_.friendly) {
            if (target.health <= 0 || target.mounted ||
                axisDistance(vehicle.axisPosition,
                             sharedFriendlyPosition(target)) >
                    spec.maximumRange) {
                continue;
            }
            vehicle.cannonAmmo = std::max(0, vehicle.cannonAmmo - 3);
            AttackRequest request;
            request.attackerId = gunner->id;
            request.targetId = target.id;
            request.weapon = weapon;
            request.friendlyAttacker = false;
            (void)resolveSharedAttack(request);
            vehicle.acted = true;
            return;
        }
        output_ << "  " << vehicle.id
                << " 没有射程内目标,保持观察而不再空耗攻击。\n";
        vehicle.acted = true;
    }

    void resolveSharedEnemyPersonTurn(EnemyPerson& enemy) {
        if (!enemy.active() || enemy.mounted || enemy.reactionUsed ||
            enemy.acted) {
            return;
        }
        enemy.acted = true;
        if (enemy.suppression >= 60) {
            enemy.suppression = std::max(0, enemy.suppression - 35);
            output_ << "  " << enemy.id << " 被压制,缩身恢复。\n";
            return;
        }
        if (enemy.health < 55 && enemy.coverId.empty()) {
            if (TacticalCover* cover =
                    bestSharedCover(sharedEnemyPosition(enemy))) {
                enemy.coverId = cover->id;
                output_ << "  " << enemy.id << " 进入 " << cover->name
                        << ",优先保存战斗力。\n";
                return;
            }
        }
        if (axisDistance(sharedEnemyPosition(enemy), 0) >= 0) {
            for (FriendlyPerson& friendly : state_.friendly) {
                if (friendly.health <= 0 || friendly.mounted) continue;
                if (axisDistance(sharedEnemyPosition(enemy),
                                 sharedFriendlyPosition(friendly)) == 0 &&
                    rng_.below(100) < 38) {
                    resolveSharedMelee(friendly, enemy);
                    return;
                }
            }
        }
        const WeaponSpec spec = weaponSpec(enemy.weaponKind);
        for (const FriendlyPerson& target : state_.friendly) {
            if (target.health <= 0 || target.mounted) continue;
            if (axisDistance(sharedEnemyPosition(enemy),
                             sharedFriendlyPosition(target)) >
                spec.maximumRange) {
                continue;
            }
            AttackRequest request;
            request.attackerId = enemy.id;
            request.targetId = target.id;
            request.weapon = enemy.weaponKind;
            request.friendlyAttacker = false;
            (void)resolveSharedAttack(request);
            return;
        }
        for (const FriendlyVehicle& vehicle : state_.combatVehicles) {
            if (vehicle.hostile || vehicle.disabled ||
                axisDistance(sharedEnemyPosition(enemy),
                             vehicle.axisPosition) >
                    spec.maximumRange) {
                continue;
            }
            AttackRequest request;
            request.attackerId = enemy.id;
            request.targetId = vehicle.id;
            request.weapon = spec.canTargetVehicles
                ? enemy.weaponKind
                : WeaponKind::MachineGun;
            request.friendlyAttacker = false;
            (void)resolveSharedAttack(request);
            return;
        }
        if (sharedEnemyPosition(enemy) > 0) {
            const int before = sharedEnemyPosition(enemy);
            enemy.axisPosition = std::max(0, before - 1);
            enemy.coverId.clear();
            output_ << "  " << enemy.id << " 推进到 "
                    << positionBand(enemy.axisPosition) << "。\n";
            triggerSharedOverwatch(enemy);
            return;
        }
        output_ << "  " << enemy.id
                << " 已在接触线但没有合法目标,保持位置。\n";
    }

    void resolveSharedEnemyPhase() {
        output_ << "\n【友军 NPC / 载具行动阶段】\n";
        for (FriendlyVehicle& vehicle : state_.combatVehicles) {
            if (!vehicle.hostile) resolveSharedFriendlyVehicleTurn(vehicle);
        }
        output_ << "\n【敌方 NPC / 载具行动阶段 · 稳定 ID 顺序】\n";
        for (FriendlyVehicle& vehicle : state_.combatVehicles) {
            if (vehicle.hostile) resolveSharedEnemyVehicleTurn(vehicle);
        }
        for (EnemyPerson& enemy : state_.enemies) {
            resolveSharedEnemyPersonTurn(enemy);
        }
    }

    void finishSharedRound() {
        for (EnemyPerson& enemy : state_.enemies) {
            if (!enemy.active() && !enemy.terminalScored) {
                scoreSharedDefeat(enemy);
            }
            enemy.suppression = std::max(0, enemy.suppression - 12);
        }
        for (FriendlyPerson& person : state_.friendly) {
            person.suppression = std::max(0, person.suppression - 12);
            person.overwatch = false;
        }
        for (FriendlyVehicle& vehicle : state_.combatVehicles) {
            vehicle.moving = false;
            vehicle.suppression =
                std::max(0, vehicle.suppression - 12);
            if (vehicle.condition <= 0) vehicle.disabled = true;
            if (vehicle.hostile && vehicle.disabled &&
                !vehicle.terminalScored) {
                scoreSharedDefeat(vehicle);
            }
        }
        for (TacticalCover& cover : state_.covers) {
            if (cover.durability > 0) continue;
            for (FriendlyPerson& person : state_.friendly) {
                if (person.coverId == cover.id) person.coverId.clear();
            }
            for (EnemyPerson& person : state_.enemies) {
                if (person.coverId == cover.id) person.coverId.clear();
            }
        }
        ++state_.completedRounds;
        const bool ableFriendly = std::any_of(
            state_.friendly.begin(), state_.friendly.end(),
            [](const FriendlyPerson& person) { return person.health > 0; });
        if (state_.withdrawalRequested) {
            state_.ending = Ending::Withdrawal;
            state_.endingRound = state_.round;
            state_.endingReason = "玩家主动撤离列宁大街";
        } else if (!ableFriendly) {
            state_.ending = Ending::Defeat;
            state_.endingRound = state_.round;
            state_.endingReason = "车组与可行动友军被击溃";
        } else {
            ++state_.round;
        }
    }

    void tickSuppressionAndFire() {
        for (FriendlyPerson& person : state_.friendly) {
            person.suppression = std::max(0, person.suppression - 12);
            if (person.health > 0) person.stamina = std::max(0, person.stamina - 2);
        }
        for (EnemyPerson& enemy : state_.enemies) {
            enemy.suppression = std::max(0, enemy.suppression - 15);
            if (enemy.active()) enemy.stamina = std::max(0, enemy.stamina - 2);
        }
        if (state_.woodenCover.burningRounds > 0) {
            --state_.woodenCover.burningRounds;
            state_.woodenCover.condition =
                std::max(0, state_.woodenCover.condition - 28);
            if (state_.woodenCover.condition == 0) {
                for (EnemyPerson& enemy : state_.enemies) {
                    if (enemy.coverId == "wooden_barricade") enemy.coverId.clear();
                }
                for (FriendlyPerson& person : state_.friendly) {
                    if (person.coverId == "wooden_barricade") person.coverId.clear();
                }
                output_ << "木制路障被烧毁,不再提供掩护。\n";
            }
        }
        if (state_.woodenCover.condition == 0) {
            for (EnemyPerson& enemy : state_.enemies) {
                if (enemy.coverId == "wooden_barricade") enemy.coverId.clear();
            }
            for (FriendlyPerson& person : state_.friendly) {
                if (person.coverId == "wooden_barricade") person.coverId.clear();
            }
        }
        if (state_.policeCar.condition == 0) {
            for (EnemyPerson& enemy : state_.enemies) {
                if (enemy.coverId == "police_car") enemy.coverId.clear();
            }
        }
    }

    int ableFriendlyCount() const {
        return static_cast<int>(std::count_if(
            state_.friendly.begin(), state_.friendly.end(),
            [](const FriendlyPerson& person) { return person.health > 0; }));
    }

    bool commanderIncapacitated() const {
        return state_.friendly.front().health <= 0;
    }

    bool allFriendlyIncapacitated() const {
        return ableFriendlyCount() == 0;
    }

    bool anyActiveEnemy() const {
        return std::any_of(
            state_.enemies.begin(), state_.enemies.end(),
            [](const EnemyPerson& enemy) {
                return enemy.active() &&
                       enemy.disposition == Disposition::Hostile;
            });
    }

    bool allEnemiesTerminal() const {
        return !anyActiveEnemy();
    }

    void checkEndings() {
        if ((commanderIncapacitated() && allFriendlyIncapacitated()) ||
            (state_.vehicle.disabled && allFriendlyIncapacitated())) {
            setEnding(Ending::Defeat);
            return;
        }
        if (state_.withdrawalOrdered &&
            state_.vehicle.location == Location::Approach &&
            ableFriendlyCount() >= 1) {
            setEnding(Ending::Withdrawal);
            return;
        }
        if (missionAgreementRecorded() &&
            state_.vehicle.location == Location::Beyond) {
            setEnding(Ending::NegotiatedPassage);
            return;
        }
        if (allEnemiesTerminal()) {
            setEnding(Ending::RoadblockResolved);
            return;
        }
        if (state_.vehicle.location == Location::Beyond &&
            anyActiveEnemy()) {
            setEnding(Ending::ForcedPassage);
            return;
        }
        if (state_.completedRounds >= config_.roundLimit) {
            setEnding(Ending::Stalemate);
        }
    }

    void setEnding(Ending ending) {
        state_.ending = ending;
        state_.endingRound = state_.round;
    }

    void clampState() {
        auto inRange = [](int& value) {
            value = std::clamp(value, 0, 100);
        };
        inRange(state_.discipline);
        inRange(state_.civilianOrganization);
        inRange(state_.mvdOrganization);
        inRange(state_.civilianMorale);
        inRange(state_.mvdMorale);
        inRange(state_.tension);
        inRange(state_.bystanderRisk);
        inRange(state_.vehicle.condition);
        inRange(state_.policeCar.condition);
        inRange(state_.bystanderInjuries);
        for (FriendlyPerson& person : state_.friendly) {
            inRange(person.health);
            inRange(person.stamina);
            inRange(person.suppression);
        }
        for (EnemyPerson& enemy : state_.enemies) {
            inRange(enemy.health);
            inRange(enemy.morale);
            inRange(enemy.stamina);
            inRange(enemy.suppression);
            if (enemy.health <= 0 && enemy.status == EnemyStatus::Active) {
                enemy.status = EnemyStatus::Incapacitated;
            }
        }
        state_.ammo.cannon30mm = std::max(0, state_.ammo.cannon30mm);
        state_.ammo.coaxialPkt = std::max(0, state_.ammo.coaxialPkt);
        state_.ammo.konkurs = std::max(0, state_.ammo.konkurs);
        state_.ammo.aksMagazines =
            std::max(0, state_.ammo.aksMagazines);
        state_.ammo.pkmBelts = std::max(0, state_.ammo.pkmBelts);
        state_.ammo.makarovMagazines =
            std::max(0, state_.ammo.makarovMagazines);
        state_.ammo.molotovs = std::max(0, state_.ammo.molotovs);
        state_.civilianOrganization =
            std::clamp(state_.civilianOrganization, 0, 100);
        state_.mvdOrganization = std::clamp(state_.mvdOrganization, 0, 100);
        state_.woodenCover.condition =
            std::clamp(state_.woodenCover.condition, 0, 100);
        state_.vehicle.suppression =
            std::clamp(state_.vehicle.suppression, 0, 100);
        state_.vehicle.disabled = state_.vehicle.condition <= 0;
        if (state_.vehicle.disabled) {
            state_.vehicle.moving = false;
        }
    }

    void printEnding() {
        output_ << "\n============================================================\n";
        switch (state_.ending) {
        case Ending::Defeat:
            output_ << "结局: 车组失去行动能力(defeat)\n"
                    << "============================================================\n"
                    << "车长已无法继续下令,路障前也没有仍能行动的车组成员。"
                    << "遭遇在枪声和无线电呼救中结束。\n";
            break;
        case Ending::Withdrawal:
            output_ << "结局: 有序撤离(withdrawal)\n"
                    << "============================================================\n"
                    << "BMP-2 留在接近路,至少一名友军仍有行动能力。"
                    << "车组带着未打通道路的报告离开,却没有把路口变成"
                    << "必须清理的战场。\n";
            break;
        case Ending::NegotiatedPassage:
            output_ << "结局: 和平通行(negotiated_passage)\n"
                    << "============================================================\n"
                    << "内务部警察与武装平民分别接受了低速通行安排。"
                    << "BMP-2 驶入路障后方,炮口离开人群,对方没有追击。"
                    << "任务通道恢复,且不要求任何人被消灭。\n";
            break;
        case Ending::RoadblockResolved:
            output_ << "结局: 路障解除(roadblock_resolved)\n"
                    << "============================================================\n"
                    << "五名武装人员现在都已投降、逃离或失能,"
                    << "没有人仍能阻止通行。和平谈判不是获得这一结局的"
                    << "唯一方式,战斗也不是唯一方式。\n";
            break;
        case Ending::ForcedPassage:
            output_ << "结局: 强行突破(forced_passage)\n"
                    << "============================================================\n"
                    << "敌方回应已经完成,BMP-2 越过了仍有武装人员活动的位置。"
                    << "车辆到达了目标一侧,但车体、人员、纪律和人群风险"
                    << "共同记录了这次突破的代价。\n";
            break;
        case Ending::Stalemate:
            output_ << "结局: 对峙暂时中止(stalemate)\n"
                    << "============================================================\n"
                    << "八个回合过去,双方都没有接受能结束对峙的条件,"
                    << "也没有一方在最后时刻越过开火线。增援仍在路上。\n";
            break;
        case Ending::None:
            output_ << "结局: 未结算\n"
                    << "============================================================\n";
            break;
        }

        output_ << "\n【最终人员状态】\n";
        for (const FriendlyPerson& person : state_.friendly) {
            output_ << "  " << person.id << " " << person.name
                    << " | 生命 " << person.health
                    << " | " << healthLabel(person.health)
                    << " | " << (person.mounted ? "车内" : locationName(person.location))
                    << '\n';
        }
        for (const EnemyPerson& enemy : state_.enemies) {
            output_ << "  " << enemy.id << " " << enemy.name
                    << " | " << factionName(enemy.faction)
                    << " | " << dispositionName(enemy.disposition)
                    << " | 生命 " << enemy.health
                    << " | 士气 " << enemy.morale
                    << " | " << enemyStatusLabel(enemy) << '\n';
        }
        output_ << "\n【结算】\n"
                << "轮次: " << state_.endingRound << '/' << config_.roundLimit
                << " | 纪律 " << state_.discipline
                << " | 紧张度 " << state_.tension
                << " | 围观者风险 " << state_.bystanderRisk << '\n'
                << "BMP-2 车况: " << state_.vehicle.condition
                << "/100 | 位置 " << locationName(state_.vehicle.location)
                << " | 警车状况 " << state_.policeCar.condition << "/100\n"
                << "围观者伤者: " << state_.bystanderInjuries
                << " | 任务协议: "
                << (missionAgreementRecorded() ? "已记录" : "未形成")
                << '\n'
                << "剩余弹药: 30mm " << state_.ammo.cannon30mm
                << " | PKT " << state_.ammo.coaxialPkt
                << " | Konkurs " << state_.ammo.konkurs
                << " | AKS 弹匣 " << state_.ammo.aksMagazines
                << " | PKM 弹链 " << state_.ammo.pkmBelts << '\n'
                << "随机种子: " << seedForDisplay_ << '\n';
    }

    SplitMix64 rng_;
    std::istream& input_;
    std::ostream& output_;
    GameState state_;
    EncounterConfig config_;
    std::uint64_t seedForDisplay_ = 0;
    bool eof_ = false;
    std::vector<DefeatEvent> roundDefeats_;
};

CombatResult runEncounter(const EncounterConfig& config, std::istream& input,
                          std::ostream& output) {
    CombatSession session(config, input, output);
    return session.runLegacyEncounter();
}

WeaponSpec weaponSpec(WeaponKind weapon) {
    switch (weapon) {
    case WeaponKind::AutomaticRifle:
        return {"AK-74", 3, 55, 24, 38, false, false};
    case WeaponKind::MachineGun:
        return {"PKM", 4, 60, 34, 48, false, false};
    case WeaponKind::CoaxialMachineGun:
        return {"并列 PKT", 4, 58, 30, 44, false, true};
    case WeaponKind::Autocannon30mm:
        return {"30mm 机关炮", 5, 73, 56, 80, true, true};
    case WeaponKind::Konkurs:
        return {"9M113 Konkurs", 5, 82, 82, 104, true, true};
    case WeaponKind::TankGun:
        return {"坦克主炮", 5, 78, 70, 96, true, true};
    }
    return {"未知武器", 0, 0, 0, 0, false, false};
}

std::string vehicleKindName(VehicleKind kind) {
    switch (kind) {
    case VehicleKind::Bmp2: return "BMP-2";
    case VehicleKind::Btr80: return "BTR-80";
    case VehicleKind::T72: return "T-72";
    case VehicleKind::T80: return "T-80";
    }
    return "未知载具";
}

std::string unitRoleName(UnitRole role) {
    switch (role) {
    case UnitRole::Crew: return "车组";
    case UnitRole::Rifleman: return "步枪兵";
    case UnitRole::VehicleCrew: return "载具车组";
    case UnitRole::ArmedMilitia: return "民兵";
    case UnitRole::OrganizedInfantry: return "组织步兵";
    case UnitRole::TankCrew: return "坦克车组";
    }
    return "未知角色";
}

int axisDistance(int firstPosition, int secondPosition) {
    return std::abs(std::clamp(firstPosition, 0, 5) -
                    std::clamp(secondPosition, 0, 5));
}

std::string positionBand(int position) {
    switch (std::clamp(position, 0, 5)) {
    case 0: return "接触";
    case 1: return "近距";
    case 2: return "中距";
    case 3: return "远距";
    case 4: return "极远";
    case 5: return "战场边缘";
    default: break;
    }
    return "未知距离";
}

struct CombatSession::Impl {
    Impl(EncounterConfig config, std::istream& input, std::ostream& output)
        : game(std::move(config), input, output) {}

    Game game;
};

CombatSession::CombatSession(EncounterConfig config, std::istream& input,
                             std::ostream& output)
    : impl_(std::make_unique<Impl>(std::move(config), input, output)) {}

CombatSession::~CombatSession() = default;
CombatSession::CombatSession(CombatSession&&) noexcept = default;
CombatSession& CombatSession::operator=(CombatSession&&) noexcept = default;

GameState& CombatSession::state() { return impl_->game.publicState(); }

const GameState& CombatSession::state() const {
    return impl_->game.publicState();
}

void CombatSession::beginRound() { impl_->game.beginRound(); }

bool CombatSession::runFriendlyPhase() {
    return impl_->game.runLegacyFriendlyPhase();
}

void CombatSession::resolveEnemyPhase() {
    impl_->game.resolveRoundEnemyPhase();
}

CombatRoundResult CombatSession::finishRound() {
    return impl_->game.finishRound();
}

bool CombatSession::executeFriendlyCommand(const FriendlyCommand& command) {
    return impl_->game.executeFriendlyCommand(command);
}

CombatResolution CombatSession::resolveAttack(const AttackRequest& request) {
    return impl_->game.resolveAttack(request);
}

CombatResolution CombatSession::resolveAirAttack(
    const AttackRequest& request) {
    return impl_->game.resolveAirAttack(request);
}

bool CombatSession::resolveAntiAir(bool friendlyAir) {
    return impl_->game.resolveAntiAir(friendlyAir);
}

CombatResult CombatSession::runLegacyEncounter() {
    return impl_->game.runLegacyEncounter();
}

} // namespace civil_war

← 返回文件树 · 在 GitHub 上查看