diff --git a/CMakeLists.txt b/CMakeLists.txt index b695c260..cd9a5df3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -76,6 +76,7 @@ if(AVA2_EMBED_PYTHON) src/scripting/python_chr.cpp src/scripting/python_app.cpp src/game/player_settings.cpp + src/game/auto_hunt.cpp src/scripting/python_wndmgr.cpp src/scripting/python_gameplay_modules.cpp src/scripting/python_ime.cpp @@ -229,6 +230,9 @@ if(BUILD_TESTING AND NOT ANDROID) add_test(NAME ava2.pack_assets COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/pack_assets_test.py") endif() + add_executable(auto_hunt_test tests/auto_hunt_test.cpp src/game/auto_hunt.cpp) + target_include_directories(auto_hunt_test PRIVATE src/game) + add_test(NAME ava2.auto_hunt COMMAND auto_hunt_test) add_executable(server_clock_test tests/server_clock_test.cpp) target_include_directories(server_clock_test PRIVATE src src/network) add_test(NAME ava2.server_clock COMMAND server_clock_test) diff --git a/docs/MOBILE-ARCHITECTURE.md b/docs/MOBILE-ARCHITECTURE.md index 9ff1825a..368a2d4a 100644 --- a/docs/MOBILE-ARCHITECTURE.md +++ b/docs/MOBILE-ARCHITECTURE.md @@ -122,7 +122,7 @@ Python 更新(原版脚本 + mobile HUD) | 攻击键外圈 / 底部 | 技能圈、药水栏、翻页 | 原版快捷栏(4 页) | 技能圈对应技能格,底部栏对应道具格 | | 攻击键附近 | 骑乘、拾取、锁定目标 | `player.PickCloseItem`;骑乘/锁定接口待核对 | 小按钮 | | 屏幕空白处 | 转镜头、双指缩放 | `app.RotateCamera`;镜头距离接口待核对 | C++ 手势识别 | -| 可选 | 自动战斗 | 原版没有 | 客户端新功能,最后做 | +| 技能圈旁 | 自动狩猎(AUTO 键) | 原版没有 | 客户端新功能:轻点开关、长按设置;已完成(第 6 步) | 注意事项: @@ -144,6 +144,6 @@ Python 更新(原版脚本 + mobile HUD) 3. `input/`:触摸分流、虚拟摇杆、攻击键、镜头手势——可在手机上移动和战斗。 4. `mobile/`:手机 HUD(状态面板、技能圈和快捷栏、右上角入口、小地图、左侧按钮)。 5. 界面缩放和安全区域收尾。 -6. 自动战斗等新增功能;iOS 打包与 `app_loop` 拆分。 +6. 自动战斗等新增功能(自动狩猎已完成,见 PORT-PLAN);iOS 打包与 `app_loop` 拆分。 第 3、4 步大部分可在 macOS 上开发(鼠标模拟单指,触控板测双指);多指同时操作和性能需要真机验证。 diff --git a/docs/PORT-PLAN.md b/docs/PORT-PLAN.md index d8468b70..c21946d2 100644 --- a/docs/PORT-PLAN.md +++ b/docs/PORT-PLAN.md @@ -1337,3 +1337,44 @@ real cutout insets); a window size change at runtime (split screen, foldable) keeps the logical size chosen at start; no in-game UI size option yet (only `--ui-height` / env); original PC windows (inventory etc.) are not rearranged for 600 px height. + +### 2026-10-12 Mobile step 6 — auto hunt + +Client-only feature (the original client has none; not taken from 40250). +It only drives paths that manual play already uses: walk-to (move target), +target packet, the normal attack, quickslot skills, item pick-up and +quickslot potions. Nothing new goes on the wire. + +- `src/game/auto_hunt.{h,cpp}`: engine-free state machine + (off / search / engage / loot / return / paused). Hunts the nearest living + mob within `radius` of an anchor point (metin stones optional), loots own + or unowned drops before the next mob, walks back to the anchor when the + area is empty, and gives up on a target whose distance stops shrinking for + 8 s (ignored for 30 s). Joystick / attack key / mouse movement pause it; + it resumes 3 s after the last input and re-anchors where the player + stopped. HP / SP potions (belt slots 1 / 2, quickslot 24 / 25) are checked + in every state with a 1 s gap. Death turns it off. +- `ProcessAutoHunt()` (python_gameplay_modules.cpp, called from the game loop + before `ProcessPlayerAttack`) builds the input from NetworkActorManager + (mobs bType 0/2), `CPythonItem::GetGroundItems()` (new read accessor) and + the combat wheel's current skill page, skipping skills on cooldown, active + toggles, 121-123 and guild skills. +- Python: `player.SetAutoHunt / IsAutoHunt / GetAutoHuntState / + SetAutoHuntOption / GetAutoHuntOption`; options (radius, skills, pickup, + stones, hp_percent, sp_percent, hp_slot, sp_slot) persist in + `autohunt.cfg` next to metin2.cfg. +- `ui_mobile_autohunt.py`: AUTO button on the combat wheel (tap toggles, + green while on with the state under it; 0.6 s long press opens the settings + board with range / skills / pick-up / stones / potion thresholds). + +Verified: `ava2.auto_hunt` (targeting, range stop, skill gap, busy, loot +before next mob, area and stone filter, return, chase watchdog, pause / +resume / re-anchor, potions, death), `ava2.touch_game` (AUTO is UI under the +finger, tap on/off, engage + target VID + move target, stop in reach, +joystick pauses, long press opens settings, option persistence), 54/54 +desktop tests, HUD screenshot shows AUTO above Ride. +Outstanding: not run on a device or against the server (ownership timing, +pick-up refusals, attack speed); straight-line walking only, the stuck +watchdog is the only obstacle handling; party loot rules ignored (only own / +unowned drops); no desktop hotkey (F9 is taken by the preview mode); +English labels, no locale strings; does not run in `--preview-data`. diff --git a/src/app/main.cpp b/src/app/main.cpp index bd76b543..ad699e37 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -2101,6 +2101,8 @@ const auto profileActiveStart = std::chrono::steady_clock::now(); static bool wasMoving = false; static uint32_t lastMoveSent = 0; float moveYaw = 0.0f; + // Auto hunt (mobile step 6) steers and presses attack like a player would. + ava2::ProcessAutoHunt(); // Attack input first (NEW_Attack ends walking); no movement while an attack plays. if (ava2::ProcessPlayerAttack(orbit_camera.GetYaw(), dt, wasMoving)) wasMoving = false; const bool attacking = ava2::IsPlayerAttacking(); diff --git a/src/game/auto_hunt.cpp b/src/game/auto_hunt.cpp new file mode 100644 index 00000000..9bf9210c --- /dev/null +++ b/src/game/auto_hunt.cpp @@ -0,0 +1,269 @@ +// Client-side auto hunt state machine; see auto_hunt.h. +#include "auto_hunt.h" +#include +#include + +namespace ava2 { +namespace { +float Distance(float ax, float az, float bx, float bz) { + const float dx = ax - bx, dz = az - bz; + return std::sqrt(dx * dx + dz * dz); +} +} // namespace + +const char* AutoHuntStateName(AutoHuntState state) { + switch (state) { + case AutoHuntState::Off: return "off"; + case AutoHuntState::Search: return "search"; + case AutoHuntState::Engage: return "engage"; + case AutoHuntState::Loot: return "loot"; + case AutoHuntState::Return: return "return"; + case AutoHuntState::Paused: return "paused"; + } + return "off"; +} + +void AutoHunt::Start(float x, float z) { + m_anchorX = x; + m_anchorZ = z; + m_target = 0; + m_moving = false; + m_ignoreUntil.clear(); + m_state = AutoHuntState::Search; + m_stateSince = 0; + m_lastManual = 0; +} + +void AutoHunt::Stop() { + m_state = AutoHuntState::Off; + m_target = 0; + m_moving = false; +} + +void AutoHunt::Enter(AutoHuntState state, uint32_t now) { + m_state = state; + m_stateSince = now; + m_lastProgress = now; + m_bestDistance = 1e30f; +} + +bool AutoHunt::Ignored(uint32_t vid, uint32_t now) const { + auto it = m_ignoreUntil.find(vid); + return it != m_ignoreUntil.end() && now < it->second; +} + +const AutoHuntMob* AutoHunt::FindMob(const AutoHuntInput& in, uint32_t vid) const { + for (const auto& mob : in.mobs) + if (mob.vid == vid) return &mob; + return nullptr; +} + +// Nearest living mob inside the hunt area. +const AutoHuntMob* AutoHunt::PickMob(const AutoHuntInput& in) const { + const AutoHuntMob* best = nullptr; + float bestDistance = 0; + for (const auto& mob : in.mobs) { + if (mob.stone && !options.attackStones) continue; + if (Ignored(mob.vid, in.now)) continue; + if (Distance(mob.x, mob.z, m_anchorX, m_anchorZ) > options.radius) continue; + const float d = Distance(mob.x, mob.z, in.x, in.z); + if (!best || d < bestDistance) { best = &mob; bestDistance = d; } + } + return best; +} + +const AutoHuntItem* AutoHunt::PickItem(const AutoHuntInput& in) const { + if (!options.pickUp) return nullptr; + const AutoHuntItem* best = nullptr; + float bestDistance = 0; + for (const auto& item : in.items) { + if (Ignored(item.vid, in.now)) continue; + if (Distance(item.x, item.z, m_anchorX, m_anchorZ) > options.radius) continue; + const float d = Distance(item.x, item.z, in.x, in.z); + if (!best || d < bestDistance) { best = &item; bestDistance = d; } + } + return best; +} + +void AutoHunt::GoTo(AutoHuntOutput& out, float x, float z, uint32_t now) { + if (m_moving && now - m_lastPath < kRepathGap) return; + out.move = AutoHuntOutput::Move::Go; + out.moveX = x; + out.moveZ = z; + m_moving = true; + m_lastPath = now; +} + +void AutoHunt::Halt(AutoHuntOutput& out) { + if (!m_moving) return; + out.move = AutoHuntOutput::Move::Stop; + m_moving = false; +} + +void AutoHunt::Potions(const AutoHuntInput& in, AutoHuntOutput& out) { + if (in.now - m_lastPotion < kPotionGap && m_lastPotion != 0) return; + if (options.hpPercent > 0 && in.hpPercent < options.hpPercent && in.hpSlotUsable) + out.useQuickSlot = options.hpSlot; + else if (options.spPercent > 0 && in.spPercent < options.spPercent && in.spSlotUsable) + out.useQuickSlot = options.spSlot; + if (out.useQuickSlot >= 0) m_lastPotion = in.now; +} + +AutoHuntOutput AutoHunt::Update(const AutoHuntInput& in) { + AutoHuntOutput out; + if (m_state == AutoHuntState::Off) return out; + const uint32_t now = in.now; + if (in.dead) { + Halt(out); + Stop(); + out.stopped = true; + return out; + } + Potions(in, out); + + // Manual input wins; hunting resumes where the player left off. + if (in.manual) { + m_lastManual = now; + if (m_state != AutoHuntState::Paused) { + Enter(AutoHuntState::Paused, now); + m_moving = false; // the player's own input owns the actor now + m_target = 0; + } + return out; + } + if (m_state == AutoHuntState::Paused) { + if (now - m_lastManual < kResumeDelay) return out; + m_anchorX = in.x; + m_anchorZ = in.z; + Enter(AutoHuntState::Search, now); + } + if (!in.canAct) return out; + + for (auto it = m_ignoreUntil.begin(); it != m_ignoreUntil.end();) + it = now >= it->second ? m_ignoreUntil.erase(it) : std::next(it); + + // Progress watchdog for anything we walk to: give up when the distance stops shrinking. + auto chase = [&](float distance, uint32_t vid) { + if (distance < m_bestDistance - 50.0f) { + m_bestDistance = distance; + m_lastProgress = now; + } else if (now - m_lastProgress > kChaseTimeout) { + if (vid) m_ignoreUntil[vid] = now + kIgnoreTime; + return false; + } + return true; + }; + + if (m_state == AutoHuntState::Engage) { + const AutoHuntMob* mob = FindMob(in, m_target); + if (!mob || (mob->stone && !options.attackStones)) { + // Killed (or gone): collect the drop before the next target. + m_target = 0; + const AutoHuntItem* item = PickItem(in); + if (item) { + m_target = item->vid; + Enter(AutoHuntState::Loot, now); + } else { + Enter(AutoHuntState::Search, now); + } + } else if (Distance(mob->x, mob->z, m_anchorX, m_anchorZ) > options.radius * 1.5f) { + m_target = 0; + Enter(AutoHuntState::Return, now); + } else { + const float distance = Distance(mob->x, mob->z, in.x, in.z); + if (distance <= in.attackRange + mob->radius) { + Halt(out); + out.attack = mob->vid; + m_lastProgress = now; + if (options.useSkills && !in.busy && !in.readySkillSlots.empty() && + (m_lastSkill == 0 || now - m_lastSkill >= kSkillGap)) { + out.skillSlot = in.readySkillSlots.front(); + m_lastSkill = now; + } + } else if (chase(distance, mob->vid)) { + GoTo(out, mob->x, mob->z, now); + } else { + m_target = 0; + Halt(out); + Enter(AutoHuntState::Search, now); + } + return out; + } + } + + if (m_state == AutoHuntState::Loot) { + const AutoHuntItem* item = nullptr; + for (const auto& candidate : in.items) + if (candidate.vid == m_target) item = &candidate; + if (!item || Ignored(m_target, now)) { + m_target = 0; + Enter(AutoHuntState::Search, now); + } else { + const float distance = Distance(item->x, item->z, in.x, in.z); + if (distance <= kPickRange) { + Halt(out); + if (m_lastPick == 0 || now - m_lastPick >= kPickGap) { + out.pick = item->vid; + m_lastPick = now; + } + // Inventory full / someone else's drop: the server keeps refusing. + if (now - m_stateSince > 5000) m_ignoreUntil[item->vid] = now + kIgnoreTime; + } else if (chase(distance, item->vid)) { + GoTo(out, item->x, item->z, now); + } else { + m_target = 0; + Halt(out); + Enter(AutoHuntState::Search, now); + } + return out; + } + } + + if (m_state == AutoHuntState::Return) { + if (!PickMob(in)) { + const float distance = Distance(m_anchorX, m_anchorZ, in.x, in.z); + if (distance <= kPickRange) { + Halt(out); + Enter(AutoHuntState::Search, now); + } else if (chase(distance, 0)) { + GoTo(out, m_anchorX, m_anchorZ, now); + return out; + } else { + // Cannot get back (blocked): hunt from here instead. + Halt(out); + m_anchorX = in.x; + m_anchorZ = in.z; + Enter(AutoHuntState::Search, now); + } + } else { + Enter(AutoHuntState::Search, now); + } + } + + // Search + if (const AutoHuntMob* mob = PickMob(in)) { + m_target = mob->vid; + out.target = mob->vid; + Enter(AutoHuntState::Engage, now); + const float distance = Distance(mob->x, mob->z, in.x, in.z); + m_bestDistance = distance; + if (distance <= in.attackRange + mob->radius) { + Halt(out); + out.attack = mob->vid; + } else { + GoTo(out, mob->x, mob->z, now); + } + } else if (const AutoHuntItem* item = PickItem(in)) { + m_target = item->vid; + Enter(AutoHuntState::Loot, now); + GoTo(out, item->x, item->z, now); + } else if (Distance(m_anchorX, m_anchorZ, in.x, in.z) > kPickRange * 2) { + Enter(AutoHuntState::Return, now); + GoTo(out, m_anchorX, m_anchorZ, now); + } else { + Halt(out); + } + return out; +} + +} // namespace ava2 diff --git a/src/game/auto_hunt.h b/src/game/auto_hunt.h new file mode 100644 index 00000000..197c1ed4 --- /dev/null +++ b/src/game/auto_hunt.h @@ -0,0 +1,112 @@ +// Client-side auto hunt (mobile step 6, docs/MOBILE-ARCHITECTURE.md). Not in the AVA2 client: a +// new feature written for this port, not adapted from another client. It only drives the inputs a +// player already has — walking, the attack key, quickslot skills, item pick-up and quickslot +// potions — so the server sees the same packets as manual play. +// +// Pure logic: the host (python_gameplay_modules.cpp ProcessAutoHunt) fills AutoHuntInput from the +// actor/item/skill state every frame and carries out the returned AutoHuntOutput. +#pragma once +#include +#include +#include + +namespace ava2 { + +enum class AutoHuntState : uint8_t { Off, Search, Engage, Loot, Return, Paused }; + +struct AutoHuntOptions { + float radius = 1500.0f; // hunt area around the anchor (map units, 100 = 1 m) + bool useSkills = true; // skills on the current quickslot page + bool pickUp = true; // walk to and pick up own / free drops + bool attackStones = false; // metin stones (TYPE_STONE) as targets + int hpPercent = 50; // use hpSlot below this HP %, 0 = never + int spPercent = 30; // use spSlot below this SP %, 0 = never + int hpSlot = 24; // global quickslot (mobile potion belt = 24..31) + int spSlot = 25; +}; + +struct AutoHuntMob { + uint32_t vid = 0; + float x = 0, z = 0; + float radius = 0; // defending radius, added to the attack range + bool stone = false; +}; + +struct AutoHuntItem { + uint32_t vid = 0; + float x = 0, z = 0; +}; + +struct AutoHuntInput { + uint32_t now = 0; // ms + float x = 0, z = 0; // main actor + bool dead = false; + bool canAct = true; + bool busy = false; // attack or skill motion playing + bool manual = false; // player is steering / attacking this frame + int hpPercent = 100, spPercent = 100; + float attackRange = 160.0f; // weapon reach without the victim radius + bool hpSlotUsable = false, spSlotUsable = false; + std::vector mobs; // living attackable actors + std::vector items; // ground items this player may pick up + std::vector readySkillSlots; // skill slots off cooldown and not already active +}; + +struct AutoHuntOutput { + enum class Move : uint8_t { None, Go, Stop } move = Move::None; + float moveX = 0, moveZ = 0; + uint32_t target = 0; // send a target packet (player.SetTarget) + uint32_t attack = 0; // face this vid and press attack this frame + int skillSlot = -1; // ClickSkillSlot + uint32_t pick = 0; // SendItemPickUpPacket + int useQuickSlot = -1; // global quickslot to use (potion) + bool stopped = false; // turned itself off (death) +}; + +class AutoHunt { +public: + static constexpr uint32_t kResumeDelay = 3000; // after the last manual input + static constexpr uint32_t kChaseTimeout = 8000; // no progress towards a target + static constexpr uint32_t kIgnoreTime = 30000; // a given-up target / item is skipped + static constexpr uint32_t kSkillGap = 1200; + static constexpr uint32_t kPotionGap = 1000; + static constexpr uint32_t kPickGap = 300; + static constexpr uint32_t kRepathGap = 250; + static constexpr float kPickRange = 150.0f; + + AutoHuntOptions options; + + void Start(float x, float z); + void Stop(); + bool IsOn() const { return m_state != AutoHuntState::Off; } + AutoHuntState GetState() const { return m_state; } + uint32_t GetTarget() const { return m_target; } + float GetAnchorX() const { return m_anchorX; } + float GetAnchorZ() const { return m_anchorZ; } + AutoHuntOutput Update(const AutoHuntInput& in); + +private: + void Enter(AutoHuntState state, uint32_t now); + bool Ignored(uint32_t vid, uint32_t now) const; + const AutoHuntMob* FindMob(const AutoHuntInput& in, uint32_t vid) const; + const AutoHuntMob* PickMob(const AutoHuntInput& in) const; + const AutoHuntItem* PickItem(const AutoHuntInput& in) const; + void GoTo(AutoHuntOutput& out, float x, float z, uint32_t now); + void Halt(AutoHuntOutput& out); + void Potions(const AutoHuntInput& in, AutoHuntOutput& out); + + AutoHuntState m_state = AutoHuntState::Off; + float m_anchorX = 0, m_anchorZ = 0; + uint32_t m_target = 0; // mob vid (Engage) or item vid (Loot) + uint32_t m_stateSince = 0; + uint32_t m_lastManual = 0; + uint32_t m_lastProgress = 0; + float m_bestDistance = 0; + uint32_t m_lastSkill = 0, m_lastPotion = 0, m_lastPick = 0, m_lastPath = 0; + bool m_moving = false; + std::unordered_map m_ignoreUntil; +}; + +const char* AutoHuntStateName(AutoHuntState state); + +} // namespace ava2 diff --git a/src/scripting/python_gameplay_modules.cpp b/src/scripting/python_gameplay_modules.cpp index 5fea659f..1ee8e853 100644 --- a/src/scripting/python_gameplay_modules.cpp +++ b/src/scripting/python_gameplay_modules.cpp @@ -15,6 +15,8 @@ #include "game_type.h" #include "guild_state.h" #include "skill_cooldown.h" +#include "auto_hunt.h" +#include "python_system.h" #include "eter_net/PythonNetworkStream.h" #include "eter_net/NetworkActorManager.h" #include "eter_render/TerrainHeightmap.h" @@ -37,6 +39,7 @@ #include #include #include +#include #include #include @@ -1103,6 +1106,106 @@ bool ProcessPlayerAttack(float cameraYaw, float frameDt, bool wasMoving) { return stopSent; } +// Mobile step 6 auto hunt (src/game/auto_hunt.h). Fills the logic's view of the world from the +// same state manual play uses and carries out its decisions through the manual paths: actor move +// target (main.cpp sends the move packets), PlayerNewAttack (= held attack key), ClickSkillSlot, +// the pick-up packet and quickslot use. +static AutoHunt s_autoHunt; + +static bool IsAutoHuntSkillReady(int skillSlot, float now) { + auto it = s_playerSkills.find(skillSlot); + if (it == s_playerSkills.end() || it->second.index == 0 || it->second.level <= 0) return false; + const int index = it->second.index; + if (index == 121 || index == 122 || index == 123) return false; // fishing / combo + if (GetSkillTypeById(uint32_t(index)) == 3 /* SKILL_TYPE_GUILD */) return false; + if (it->second.cooldown.cooling(now, s_coolTimeEnabled)) return false; + const auto* data = FindSkillDescription(uint32_t(index)); + const bool toggle = data && (data->attributes & (1u << 1 /* SKILL_ATTRIBUTE_TOGGLE */)); + return !(toggle && it->second.active); +} + +static bool IsAutoHuntPotionSlot(int global) { + if (global < 0 || global >= int(s_playerQuickSlots.size())) return false; + const auto& quick = s_playerQuickSlots[global]; + return quick.type == 1 /* SLOT_TYPE_INVENTORY */ && GetPlayerItemData(1, uint16_t(quick.pos)).count > 0; +} + +static int PointPercent(int cur, int max) { + auto c = s_playerPoints.find(cur), m = s_playerPoints.find(max); + if (c == s_playerPoints.end() || m == s_playerPoints.end() || m->second <= 0) return 100; + return int(c->second * 100 / m->second); +} + +void ProcessAutoHunt() { + if (!s_autoHunt.IsOn()) return; + auto& manager = NetworkActorManager::Instance(); + auto* main = manager.GetMainInstance(); + if (!main || !main->m_pActorInstance) return; + auto& inst = *main->m_pActorInstance; + + AutoHuntInput in; + in.now = GetServerMSec(); + in.x = inst.GetX(); + in.z = inst.GetZ(); + in.dead = inst.IsDead(); + in.canAct = inst.CanAct(); + in.busy = inst.IsAttacking() || inst.IsUsingSkill(); + float yaw; + in.manual = s_isAtkKey || GetPlayerMovementYaw(0.0f, yaw) || IsPlayerMouseMoving(); + in.hpPercent = PointPercent(5 /* POINT_HP */, 6 /* POINT_MAX_HP */); + in.spPercent = PointPercent(7 /* POINT_SP */, 8 /* POINT_MAX_SP */); + in.attackRange = inst.IsBowMode() ? 900.0f : 150.0f; + in.hpSlotUsable = IsAutoHuntPotionSlot(s_autoHunt.options.hpSlot); + in.spSlotUsable = IsAutoHuntPotionSlot(s_autoHunt.options.spSlot); + for (const auto& [vid, actor] : manager.GetActorDict()) { + if (vid == main->m_dwVID || !actor.m_pActorInstance) continue; + if (actor.m_bType != 0 && actor.m_bType != 2) continue; // TYPE_ENEMY / TYPE_STONE + const auto& v = *actor.m_pActorInstance; + if (v.IsDead()) continue; + in.mobs.push_back({vid, v.GetX(), v.GetZ(), v.GetDefendingRadius(), actor.m_bType == 2}); + } + for (const auto& [vid, item] : CPythonItem::Instance().GetGroundItems()) { + if (!item->stOwnership.empty() && item->stOwnership != s_playerName) continue; + in.items.push_back({vid, item->v3EndPosition.x, -item->v3EndPosition.y}); + } + // The combat wheel shows quickslot pages 1-3 (ui_mobile_combat.py); page 4 is the potion belt. + const float nowSec = CTimer::Instance().GetCurrentSecond(); + const int page = s_quickPage < 3 ? s_quickPage : 0; + for (int local = 0; local < 8; ++local) { + const auto& quick = s_playerQuickSlots[page * 8 + local]; + if (quick.type == 2 /* SLOT_TYPE_SKILL */ && IsAutoHuntSkillReady(quick.pos, nowSec)) + in.readySkillSlots.push_back(quick.pos); + } + + const AutoHuntOutput out = s_autoHunt.Update(in); + if (out.move == AutoHuntOutput::Move::Go) { + inst.SetMoveTarget(out.moveX, out.moveZ); + } else if (out.move == AutoHuntOutput::Move::Stop) { + inst.ClearMoveTarget(); + inst.StopMoving(); + } + if (out.useQuickSlot >= 0) use_global_quick_slot(out.useQuickSlot); + if (out.target && out.target != s_targetVID) { + s_targetVID = out.target; + PythonNetworkStream::Instance().SendTargetPacket(out.target); + } + if (out.attack) { + if (const auto* victim = manager.GetActorData(out.attack); victim && victim->m_pActorInstance) { + if (!inst.IsAttacking()) { + const float dx = victim->m_pActorInstance->GetX() - inst.GetX(); + const float dz = victim->m_pActorInstance->GetZ() - inst.GetZ(); + inst.SetYaw(std::fmod(std::atan2(dx, dz) * 180.0f / 3.14159265f + 360.0f, 360.0f)); + } + if (out.skillSlot >= 0) ClickSkillSlot(out.skillSlot); + else PlayerNewAttack(); + } + } + if (out.pick) PythonNetworkStream::Instance().SendItemPickUpPacket(out.pick); + if (out.stopped) player_window_call("OnAutoHuntStopped"); +} + +bool IsAutoHuntOn() { return s_autoHunt.IsOn(); } + static float s_fCmrRotSpd = 0.0f; static uint32_t s_inGuildAreaID = 0xffffffff; @@ -3524,6 +3627,93 @@ static PyObject* player_GetItemUnSealLeftTime(PyObject*, PyObject*) { return Py_BuildValue("i", 0); } +// Mobile step 6 auto hunt (ui_mobile_autohunt.py). Not in the original player module. +static void auto_hunt_load(); +static PyObject* player_SetAutoHunt(PyObject*, PyObject* args) { + int on = 0; + if (!PyArg_ParseTuple(args, "i", &on)) return nullptr; + auto_hunt_load(); + if (on && !s_autoHunt.IsOn()) { + const auto* main = NetworkActorManager::Instance().GetMainInstance(); + if (main && main->m_pActorInstance) s_autoHunt.Start(main->m_pActorInstance->GetX(), main->m_pActorInstance->GetZ()); + } else if (!on && s_autoHunt.IsOn()) { + s_autoHunt.Stop(); + if (auto* main = NetworkActorManager::Instance().GetMainInstance(); main && main->m_pActorInstance) { + main->m_pActorInstance->ClearMoveTarget(); + main->m_pActorInstance->StopMoving(); + } + } + return PyInt_FromLong(s_autoHunt.IsOn()); +} +static PyObject* player_IsAutoHunt(PyObject*, PyObject*) { return PyInt_FromLong(s_autoHunt.IsOn()); } +static PyObject* player_GetAutoHuntState(PyObject*, PyObject*) { + return Py_BuildValue("(si)", AutoHuntStateName(s_autoHunt.GetState()), int(s_autoHunt.GetTarget())); +} +static int* auto_hunt_int_option(const std::string& name) { + auto& o = s_autoHunt.options; + if (name == "hp_percent") return &o.hpPercent; + if (name == "sp_percent") return &o.spPercent; + if (name == "hp_slot") return &o.hpSlot; + if (name == "sp_slot") return &o.spSlot; + return nullptr; +} +static bool* auto_hunt_bool_option(const std::string& name) { + auto& o = s_autoHunt.options; + if (name == "skills") return &o.useSkills; + if (name == "pickup") return &o.pickUp; + if (name == "stones") return &o.attackStones; + return nullptr; +} +// autohunt.cfg next to metin2.cfg (CPythonSystem config directory), "name value" per line. +static std::string auto_hunt_config_path() { + std::string directory = CPythonSystem::GetConfigDirectory(); + if (!directory.empty() && directory.back() != '/' && directory.back() != '\\') directory += '/'; + return directory + "autohunt.cfg"; +} +static void auto_hunt_set(const std::string& name, int value) { + if (name == "radius") s_autoHunt.options.radius = float(std::clamp(value, 300, 5000)); + else if (int* i = auto_hunt_int_option(name)) *i = name == "hp_slot" || name == "sp_slot" ? std::clamp(value, 0, 31) : std::clamp(value, 0, 100); + else if (bool* b = auto_hunt_bool_option(name)) *b = value != 0; +} +static void auto_hunt_load() { + static bool loaded = false; + if (loaded) return; + loaded = true; + std::ifstream file(auto_hunt_config_path()); + std::string name; int value; + while (file >> name >> value) auto_hunt_set(name, value); +} +static void auto_hunt_save() { + const auto& o = s_autoHunt.options; + std::ofstream file(auto_hunt_config_path(), std::ios::trunc); + file << "radius " << int(o.radius) << "\nskills " << o.useSkills << "\npickup " << o.pickUp + << "\nstones " << o.attackStones << "\nhp_percent " << o.hpPercent << "\nsp_percent " << o.spPercent + << "\nhp_slot " << o.hpSlot << "\nsp_slot " << o.spSlot << "\n"; +} +static PyObject* player_SetAutoHuntOption(PyObject*, PyObject* args) { + char* name = nullptr; int value = 0; + if (!PyArg_ParseTuple(args, "si", &name, &value)) return nullptr; + const std::string key(name); + if (key != "radius" && !auto_hunt_int_option(key) && !auto_hunt_bool_option(key)) { + PyErr_Format(PyExc_KeyError, "%s", name); + return nullptr; + } + auto_hunt_load(); + auto_hunt_set(key, value); + auto_hunt_save(); + Py_RETURN_NONE; +} +static PyObject* player_GetAutoHuntOption(PyObject*, PyObject* args) { + char* name = nullptr; + if (!PyArg_ParseTuple(args, "s", &name)) return nullptr; + auto_hunt_load(); + if (std::string(name) == "radius") return PyInt_FromLong(long(s_autoHunt.options.radius)); + if (int* i = auto_hunt_int_option(name)) return PyInt_FromLong(*i); + if (bool* b = auto_hunt_bool_option(name)) return PyInt_FromLong(*b); + PyErr_Format(PyExc_KeyError, "%s", name); + return nullptr; +} + void initPlayer() { static PyMethodDef methods[] = { {"GetAutoPotionInfo", player_GetAutoPotionInfo, METH_VARARGS, nullptr}, @@ -3691,6 +3881,11 @@ void initPlayer() { {"GetGem", player_GetGem, METH_VARARGS, nullptr}, {"SetEventGame", player_SetEventGame, METH_VARARGS, nullptr}, {"GetEventGame", player_GetEventGame, METH_VARARGS, nullptr}, + {"SetAutoHunt", player_SetAutoHunt, METH_VARARGS, nullptr}, + {"IsAutoHunt", player_IsAutoHunt, METH_VARARGS, nullptr}, + {"GetAutoHuntState", player_GetAutoHuntState, METH_VARARGS, nullptr}, + {"SetAutoHuntOption", player_SetAutoHuntOption, METH_VARARGS, nullptr}, + {"GetAutoHuntOption", player_GetAutoHuntOption, METH_VARARGS, nullptr}, {nullptr, nullptr, 0, nullptr} }; NetworkActorManager::SetPartyMemberQuery(IsPartyMemberByVID); diff --git a/src/scripting/python_gameplay_modules.h b/src/scripting/python_gameplay_modules.h index f78b3947..c8f4ec1c 100644 --- a/src/scripting/python_gameplay_modules.h +++ b/src/scripting/python_gameplay_modules.h @@ -99,6 +99,10 @@ void SetPlayerAttackKey(bool pressed); bool ProcessPlayerAttack(float cameraYaw, float frameDt, bool wasMoving); // The main actor is playing an attack motion (movement input is ignored meanwhile). bool IsPlayerAttacking(); +// Mobile auto hunt (src/game/auto_hunt.h), per frame before ProcessPlayerAttack: steers the main +// actor and presses attack / skills / pick-up while player.SetAutoHunt(1) is on. +void ProcessAutoHunt(); +bool IsAutoHuntOn(); // True when handler is the window passed to player.SetGameWindow (game.GameWindow). bool IsPlayerGameWindow(const void* handler); void SetWeaponPower(uint32_t dwMinPower, uint32_t dwMaxPower, uint32_t dwMinMagicPower, uint32_t dwMaxMagicPower, uint32_t dwAddPower); diff --git a/src/scripting/python_item.h b/src/scripting/python_item.h index e7d3407d..793a8f97 100644 --- a/src/scripting/python_item.h +++ b/src/scripting/python_item.h @@ -397,6 +397,8 @@ public: void Update() {} void Render() {} + // Port addition for the auto hunt driver (python_gameplay_modules.cpp ProcessAutoHunt). + const TGroundItemInstanceMap& GetGroundItems() const { return m_GroundItemInstanceMap; } void GetInfo(std::string* pstInfo) { if (pstInfo) { pstInfo->append("Item: Inst " + std::to_string(m_GroundItemInstanceMap.size())); diff --git a/tests/auto_hunt_test.cpp b/tests/auto_hunt_test.cpp new file mode 100644 index 00000000..0f901425 --- /dev/null +++ b/tests/auto_hunt_test.cpp @@ -0,0 +1,145 @@ +// Mobile step 6 auto hunt state machine (src/game/auto_hunt.h), without the engine. +#include "auto_hunt.h" +#include +#include +#include + +using namespace ava2; + +namespace { +AutoHuntInput At(uint32_t now, float x, float z) { + AutoHuntInput in; + in.now = now; + in.x = x; + in.z = z; + return in; +} +} // namespace + +int main() { + // Off does nothing. + { + AutoHunt hunt; + auto in = At(1000, 0, 0); + in.mobs.push_back({7, 300, 0, 50, false}); + const auto out = hunt.Update(in); + assert(out.move == AutoHuntOutput::Move::None && !out.attack && !out.target); + } + // Search -> engage: target packet + walk; in range: stop + attack; skill when ready. + { + AutoHunt hunt; + hunt.Start(0, 0); + auto in = At(1000, 0, 0); + in.mobs.push_back({7, 600, 0, 50, false}); + in.mobs.push_back({8, 900, 0, 50, false}); + auto out = hunt.Update(in); + assert(hunt.GetState() == AutoHuntState::Engage && hunt.GetTarget() == 7); + assert(out.target == 7 && out.move == AutoHuntOutput::Move::Go && out.moveX == 600.0f); + in = At(2000, 450, 0); + in.mobs.push_back({7, 600, 0, 50, false}); + in.readySkillSlots = {3}; + out = hunt.Update(in); + assert(out.move == AutoHuntOutput::Move::Stop && out.attack == 7 && out.skillSlot == 3); + // Skill gap: next frame only attacks. + in.now = 2100; + out = hunt.Update(in); + assert(out.attack == 7 && out.skillSlot == -1 && out.move == AutoHuntOutput::Move::None); + // Busy (attack motion) blocks skills even after the gap. + in.now = 4000; + in.busy = true; + out = hunt.Update(in); + assert(out.attack == 7 && out.skillSlot == -1); + // Target died, own drop nearby -> loot before the next mob. + in = At(4100, 450, 0); + in.mobs.push_back({8, 900, 0, 50, false}); + in.items.push_back({100, 500, 300}); + out = hunt.Update(in); + assert(hunt.GetState() == AutoHuntState::Loot && hunt.GetTarget() == 100); + assert(out.move == AutoHuntOutput::Move::Go && out.moveX == 500.0f && out.moveZ == 300.0f); + in = At(4500, 500, 250); + in.mobs.push_back({8, 900, 0, 50, false}); + in.items.push_back({100, 500, 300}); + out = hunt.Update(in); + assert(out.pick == 100 && out.move == AutoHuntOutput::Move::Stop); + // Picked up -> next mob. + in = At(4800, 500, 250); + in.mobs.push_back({8, 900, 0, 50, false}); + out = hunt.Update(in); + assert(hunt.GetState() == AutoHuntState::Engage && out.target == 8); + } + // Area: mobs outside the radius and stones (unless enabled) are skipped; return to the anchor. + { + AutoHunt hunt; + hunt.options.radius = 1000; + hunt.Start(0, 0); + auto in = At(1000, 800, 0); + in.mobs.push_back({1, 2500, 0, 50, false}); + in.mobs.push_back({2, 700, 0, 80, true}); + auto out = hunt.Update(in); + assert(hunt.GetState() == AutoHuntState::Return && out.move == AutoHuntOutput::Move::Go && out.moveX == 0.0f); + hunt.options.attackStones = true; + out = hunt.Update(At(1100, 700, 0)); + in.now = 1200; + out = hunt.Update(in); + assert(hunt.GetState() == AutoHuntState::Engage && hunt.GetTarget() == 2 && out.attack == 2); + } + // Chase watchdog: no progress for kChaseTimeout -> target ignored for kIgnoreTime. + { + AutoHunt hunt; + hunt.Start(0, 0); + auto in = At(1000, 0, 0); + in.mobs.push_back({5, 800, 0, 50, false}); + hunt.Update(in); + in.now = 1000 + AutoHunt::kChaseTimeout + 10; + auto out = hunt.Update(in); + assert(hunt.GetState() == AutoHuntState::Search && out.move == AutoHuntOutput::Move::Stop); + in.now += 100; + out = hunt.Update(in); + assert(hunt.GetState() == AutoHuntState::Search && !out.target); + in.now += AutoHunt::kIgnoreTime; + out = hunt.Update(in); + assert(out.target == 5); + } + // Manual input pauses, resumes after kResumeDelay and re-anchors where the player stopped. + { + AutoHunt hunt; + hunt.options.radius = 500; + hunt.Start(0, 0); + auto in = At(1000, 0, 0); + in.manual = true; + auto out = hunt.Update(in); + assert(hunt.GetState() == AutoHuntState::Paused && out.move == AutoHuntOutput::Move::None); + in = At(2000, 3000, 0); + in.mobs.push_back({9, 3200, 0, 50, false}); + out = hunt.Update(in); + assert(hunt.GetState() == AutoHuntState::Paused && !out.target); + in.now = 1000 + AutoHunt::kResumeDelay; + out = hunt.Update(in); + assert(hunt.GetState() == AutoHuntState::Engage && out.target == 9); + assert(hunt.GetAnchorX() == 3000.0f); + } + // Potions run in every state with their own gap; HP first. Death turns it off. + { + AutoHunt hunt; + hunt.Start(0, 0); + auto in = At(1000, 0, 0); + in.hpPercent = 30; + in.spPercent = 10; + in.hpSlotUsable = in.spSlotUsable = true; + auto out = hunt.Update(in); + assert(out.useQuickSlot == 24); + in.now = 1500; + assert(hunt.Update(in).useQuickSlot == -1); + in.now = 2100; + in.hpPercent = 80; + assert(hunt.Update(in).useQuickSlot == 25); + in.now = 3200; + in.spSlotUsable = false; + assert(hunt.Update(in).useQuickSlot == -1); + in.dead = true; + out = hunt.Update(in); + assert(out.stopped && !hunt.IsOn()); + } + std::cout << "Auto hunt state machine passed" << std::endl; + return 0; +} diff --git a/tests/touch_game_test.cpp b/tests/touch_game_test.cpp index 48b91dc4..2070aa3f 100644 --- a/tests/touch_game_test.cpp +++ b/tests/touch_game_test.cpp @@ -8,11 +8,16 @@ #include "eter_image/GrpDevice.h" #include "test_rundir.h" #include "eter_net/PythonNetworkStream.h" +#include "eter_net/NetworkActorManager.h" +#include "python_system.h" #include #include #include #include #include +#include +#include +#include #include namespace { @@ -148,6 +153,69 @@ int main(int argc, char** argv) { "assert mm.GetGlobalPosition()[0] + mm.GetWidth() == 1024\n" "game.OnUpdate()\n"); + // Auto hunt (mobile step 6): the AUTO button sits on the combat wheel and is real UI; with a + // main actor and a mob the native driver targets, walks, stops in reach and gives up on the dead. + ava2::CPythonSystem::SetConfigDirectory(std::filesystem::temp_directory_path().string()); + std::filesystem::remove(std::filesystem::temp_directory_path() / "autohunt.cfg"); + runtime.execute("ab = hud.combat_wheel.auto_button\n" + "assert ab.IsShow() and not player.IsAutoHunt()\n" + "assert player.SetAutoHunt(1) == 0\n" // no main actor yet + "touch_tb = ab.GetGlobalPosition()\n" + "touch_tb = (touch_tb[0] + ab.GetWidth() / 2, touch_tb[1] + ab.GetHeight() / 2)\n" + "assert player.GetAutoHuntOption('radius') == 1500\n" + "player.SetAutoHuntOption('radius', 2000)\nplayer.SetAutoHuntOption('stones', 1)\n" + "assert player.GetAutoHuntOption('radius') == 2000 and player.GetAutoHuntOption('stones') == 1\n" + "player.SetAutoHuntOption('stones', 0)\n"); + tb = PyDict_GetItemString(PyModule_GetDict(main), "touch_tb"); + const float ab_x = float(PyInt_AsLong(PyTuple_GetItem(tb, 0))); + const float ab_y = float(PyInt_AsLong(PyTuple_GetItem(tb, 1))); + assert(sink.IsUiAt(ab_x, ab_y)); + { + std::ifstream cfg(std::filesystem::temp_directory_path() / "autohunt.cfg"); + std::string text((std::istreambuf_iterator(cfg)), std::istreambuf_iterator()); + assert(text.find("radius 2000\n") != std::string::npos && text.find("stones 0\n") != std::string::npos); + } + auto& actors = ava2::NetworkActorManager::Instance(); + ava2::SNetworkActorData me{}; + me.m_dwVID = 5001; me.m_bType = 6; me.m_stName = "AutoHunter"; me.m_lCurX = 10000; me.m_lCurY = 10000; + actors.AppendActor(me); + ava2::PythonNetworkStream::Instance().SetMainActorVID(5001); + ava2::SNetworkActorData mob{}; + mob.m_dwVID = 5002; mob.m_bType = 0; mob.m_dwRace = 101; mob.m_lCurX = 10800; mob.m_lCurY = 10000; + actors.AppendActor(mob); + auto hunter = actors.GetActorInstance(5001); + auto prey = actors.GetActorInstance(5002); + assert(hunter && prey); + // Tap AUTO: on (button turns green, state text shows the fight). + wm->RunMouseMove(long(ab_x), long(ab_y)); + runtime.execute("ab.OnMouseLeftButtonDown()\nab.OnMouseLeftButtonUp()\n" + "assert player.IsAutoHunt() and ab.isOn\n"); + ava2::ProcessAutoHunt(); + runtime.execute("assert player.GetAutoHuntState() == ('engage', 5002), player.GetAutoHuntState()\n" + "assert player.GetTargetVID() == 5002\n" + "ab.OnUpdate()\nassert ab.state_text.GetText() == 'Fight'\n"); + assert(hunter->HasMoveTarget()); + hunter->SetPosition(10700.0f, hunter->GetY(), 10000.0f); + ava2::ProcessAutoHunt(); + assert(!hunter->HasMoveTarget()); + // Steering pauses it; the mob dies; turning it off from the button. + ava2::SetPlayerJoystick(true, 1.0f, 0.0f); + ava2::ProcessAutoHunt(); + runtime.execute("assert player.GetAutoHuntState()[0] == 'paused'\n"); + ava2::SetPlayerJoystick(false, 0.0f, 0.0f); + prey->SetHP(0); + runtime.execute("ab.OnMouseLeftButtonDown()\nab.OnMouseLeftButtonUp()\n" + "assert not player.IsAutoHunt()\nab.OnUpdate()\nassert not ab.isOn\n" + // Long press opens the settings window instead of toggling. + "ab.OnMouseLeftButtonDown()\nab.pressTime -= 1000\nab.OnUpdate()\nab.OnMouseLeftButtonUp()\n" + "import ui_mobile_autohunt\n" + "assert not player.IsAutoHunt() and ui_mobile_autohunt._settings.IsShow()\n" + "ui_mobile_autohunt._settings.Close()\n"); + actors.RemoveActor(5002); + actors.RemoveActor(5001); + ava2::PythonNetworkStream::Instance().SetMainActorVID(0); + std::filesystem::remove(std::filesystem::temp_directory_path() / "autohunt.cfg"); + SDL_FillSurfaceRect(surface, nullptr, 0xff10141e); wm->Render(); SDL_RenderPresent(renderer); // CDisc geometry: the attack disc is dark red between the icon and the rim; empty screen is not. diff --git a/upstream/python-root/ui_mobile_autohunt.py b/upstream/python-root/ui_mobile_autohunt.py new file mode 100644 index 00000000..d648328d --- /dev/null +++ b/upstream/python-root/ui_mobile_autohunt.py @@ -0,0 +1,233 @@ +# -*- coding: utf-8 -*- +# 移动端自动狩猎(docs/MOBILE-ARCHITECTURE.md 第 6 步)。原版没有这个功能,是本客户端新增的; +# 逻辑在原生 src/game/auto_hunt.cpp,只走玩家手动操作本来就有的路径(走路、攻击键、快捷栏技能、 +# 拾取、快捷栏药水)。这里只有 HUD 上的 AUTO 键和设置窗。 +# AUTO 键:轻点开关;长按打开设置 +# 设置项保存在 metin2.cfg 同目录的 autohunt.cfg(原生 player.SetAutoHuntOption 负责读写) +import ui +import grp +import app +import player +import chat +import wndMgr +import ui_mobile_widgets as widgets + +Color = widgets.Color +STYLE_AUTO_ON = (Color(0.20, 0.45, 0.18, 0.90), Color(0.05, 0.15, 0.05, 0.90), Color(0.75, 1.0, 0.55), Color(0.20, 0.40, 0.12), 3.0) +STYLE_AUTO_ON_DOWN = (Color(0.35, 0.65, 0.30, 0.95), Color(0.10, 0.25, 0.08, 0.95), Color(0.90, 1.0, 0.70), Color(0.30, 0.50, 0.18), 3.0) + +STATE_TEXT = { + "search": "Search", + "engage": "Fight", + "loot": "Loot", + "return": "Return", + "paused": "Paused", +} + + +# 设置窗全局一个:HUD 按安全区重建时 AUTO 键会重建,设置窗不跟着重建 +_settings = None + + +def OpenSettings(): + global _settings + if not _settings: + _settings = AutoHuntSettingsWindow() + _settings.Open() + + +def Toggle(): + on = player.SetAutoHunt(0 if player.IsAutoHunt() else 1) + chat.AppendChat(chat.CHAT_TYPE_INFO, "Auto hunt ON" if on else "Auto hunt OFF") + return on + + +class AutoHuntButton(widgets.RoundButton): + """AUTO 键:轻点开关自动狩猎,长按(0.6 秒)打开设置窗。开启时绿色,下方显示当前状态。""" + LONG_PRESS = 600 + + def __init__(self, diameter): + widgets.RoundButton.__init__(self, diameter) + self.SetLabel("AUTO") + self.pressTime = 0 + self.longPressed = False + self.isOn = False + self.lastState = None + + self.state_text = ui.TextLine() + self.state_text.SetParent(self) + self.state_text.AddFlag("not_pick") + self.state_text.SetPosition(diameter / 2, diameter + 1) + self.state_text.SetHorizontalAlignCenter() + self.state_text.SetOutline() + self.state_text.SetPackedFontColor(grp.GenerateColor(0.75, 1.0, 0.55, 1.0)) + self.state_text.Show() + self.__Apply(False) + + def __del__(self): + widgets.RoundButton.__del__(self) + + def __Apply(self, on): + self.isOn = on + if on: + self.style, self.downStyle = STYLE_AUTO_ON, STYLE_AUTO_ON_DOWN + else: + self.style, self.downStyle = widgets.STYLE_FRAME, widgets.STYLE_FRAME_DOWN + self.disc.SetStyle(self.style) + if not on: + self.state_text.SetText("") + self.lastState = None + + def OnMouseLeftButtonDown(self): + self.pressTime = app.GetGlobalTime() + self.longPressed = False + return widgets.RoundButton.OnMouseLeftButtonDown(self) + + def OnMouseLeftButtonUp(self): + self.disc.SetStyle(self.style) + held = self.pressTime + self.pressTime = 0 + if self.longPressed or not self.IsIn(): + return True + if held: + self.__Apply(Toggle()) + return True + + def OnUpdate(self): + if self.pressTime and not self.longPressed and app.GetGlobalTime() - self.pressTime >= self.LONG_PRESS: + self.longPressed = True + self.disc.SetStyle(self.style) + OpenSettings() + + on = player.IsAutoHunt() + if on != self.isOn: + # 死亡等原因由原生自行关闭 + self.__Apply(on) + if on: + state = player.GetAutoHuntState()[0] + if state != self.lastState: + self.lastState = state + self.state_text.SetText(STATE_TEXT.get(state, "")) + + +class AutoHuntSettingsWindow(ui.BoardWithTitleBar): + """自动狩猎设置:范围、技能、拾取、打石头、HP/SP 药水阈值。药水用底部药水栏第 1/2 格。""" + WIDTH = 300 + ROW = 32 + RADIUS_STEP = 500 + PERCENT_STEP = 10 + + def __init__(self): + ui.BoardWithTitleBar.__init__(self) + self.SetWindowName("AutoHuntSettings") + self.AddFlag("movable") + self.AddFlag("float") + self.SetTitleName("Auto Hunt") + self.SetCloseEvent(ui.__mem_func__(self.Close)) + + rows = [ + ("radius", "Range", self.__RadiusText), + ("skills", "Use skills", None), + ("pickup", "Pick up items", None), + ("stones", "Attack metin stones", None), + ("hp_percent", "HP potion (belt 1) below", self.__PercentText), + ("sp_percent", "SP potion (belt 2) below", self.__PercentText), + ] + self.values = {} + self.parts = [] + y = 38 + for key, label, fmt in rows: + text = ui.TextLine() + text.SetParent(self) + text.SetPosition(16, y + 6) + text.SetText(label) + text.Show() + self.parts.append(text) + if fmt: + self.__AddStepper(key, y, fmt) + else: + self.__AddToggle(key, y) + y += self.ROW + + hint = ui.TextLine() + hint.SetParent(self) + hint.SetPosition(16, y + 4) + hint.SetPackedFontColor(grp.GenerateColor(0.7, 0.7, 0.7, 1.0)) + hint.SetText("Skills: current quick page. Moving pauses 3 s.") + hint.Show() + self.parts.append(hint) + + self.SetSize(self.WIDTH, y + 34) + self.SetCenterPosition() + self.Hide() + + def __del__(self): + ui.BoardWithTitleBar.__del__(self) + + def __RadiusText(self, value): + return "%d m" % (value / 100) + + def __PercentText(self, value): + return "Off" if value <= 0 else "%d%%" % value + + def __SmallButton(self, x, y, text, event): + button = ui.Button() + button.SetParent(self) + button.SetPosition(x, y) + button.SetUpVisual("d:/ymir work/ui/public/small_button_01.sub") + button.SetOverVisual("d:/ymir work/ui/public/small_button_02.sub") + button.SetDownVisual("d:/ymir work/ui/public/small_button_03.sub") + button.SetText(text) + button.SetEvent(event) + button.Show() + self.parts.append(button) + return button + + def __AddStepper(self, key, y, fmt): + value = ui.TextLine() + value.SetParent(self) + value.SetPosition(self.WIDTH - 66, y + 6) + value.SetHorizontalAlignCenter() + value.Show() + self.parts.append(value) + step = self.RADIUS_STEP if key == "radius" else self.PERCENT_STEP + self.__SmallButton(self.WIDTH - 118, y + 2, "-", lambda: self.__Step(key, -step)) + self.__SmallButton(self.WIDTH - 58, y + 2, "+", lambda: self.__Step(key, step)) + self.values[key] = (value, fmt) + + def __AddToggle(self, key, y): + button = self.__SmallButton(self.WIDTH - 72, y + 2, "", lambda: self.__Flip(key)) + self.values[key] = (button, None) + + def __Step(self, key, delta): + value = player.GetAutoHuntOption(key) + delta + if key == "radius": + value = max(500, min(5000, value)) + else: + value = max(0, min(90, value)) + player.SetAutoHuntOption(key, value) + self.Refresh() + + def __Flip(self, key): + player.SetAutoHuntOption(key, 0 if player.GetAutoHuntOption(key) else 1) + self.Refresh() + + def Refresh(self): + for key, (widget, fmt) in self.values.items(): + value = player.GetAutoHuntOption(key) + if fmt: + widget.SetText(fmt(value)) + else: + widget.SetText("On" if value else "Off") + + def Open(self): + self.Refresh() + self.Show() + self.SetTop() + + def Close(self): + self.Hide() + + def OnPressEscapeKey(self): + self.Close() + return True diff --git a/upstream/python-root/ui_mobile_combat.py b/upstream/python-root/ui_mobile_combat.py index 75f7f8f1..76905cf5 100644 --- a/upstream/python-root/ui_mobile_combat.py +++ b/upstream/python-root/ui_mobile_combat.py @@ -8,6 +8,7 @@ import wndMgr import touch import constInfo import ui_mobile_widgets as widgets +import ui_mobile_autohunt class MobileCombatWheel(ui.Window): """ @@ -17,10 +18,12 @@ class MobileCombatWheel(ui.Window): - 攻击键外两圈共 8 个快捷格 = 当前快捷页的 8 格(PC 任务栏 1-4 / F1-F4 同一份数据), 第 4 页留给底部药水栏,所以这里只在第 1-3 页间切换 - 小按钮:快捷页切换、上下马(原版 Ctrl+G 的 /ride)、拾取(原版 ` / Z 键) +- AUTO 键(第 6 步自动狩猎,ui_mobile_autohunt.py):轻点开关,长按设置 """ ATTACK_RADIUS = 60 SLOT_DIAMETER = 50 SMALL_DIAMETER = 40 + AUTO_DIAMETER = 46 # (半径, 角度):角度从 +x 逆时针,内外圈各 4 格,外圈错开半格;相邻格间距大于格子直径 SLOT_LAYOUT = [(108, 90), (108, 120), (108, 150), (108, 180), (172, 97.5), (172, 122.5), (172, 147.5), (172, 172.5)] @@ -87,6 +90,10 @@ class MobileCombatWheel(ui.Window): self.mount_button.SetLabel("Ride") self.pickup_button = self.__MakeSmall(cx - 86 - d / 2, cy + 82 - d / 2, ui.__mem_func__(self.__OnPickUp)) self.pickup_button.SetLabel("Pick") + self.auto_button = ui_mobile_autohunt.AutoHuntButton(self.AUTO_DIAMETER) + self.auto_button.SetParent(self) + self.auto_button.SetPosition(cx + 70 - self.AUTO_DIAMETER / 2, cy - 160 - self.AUTO_DIAMETER / 2) + self.auto_button.Show() self.page = -1 self.lastRefresh = 0 @@ -135,6 +142,7 @@ class MobileCombatWheel(ui.Window): if pressed != self.attack_pressed: self.attack_pressed = pressed self.attack_disc.SetStyle(widgets.STYLE_ATTACK_DOWN if pressed else widgets.STYLE_ATTACK) + self.auto_button.OnUpdate() # 与 uitaskbar.TaskBar.OnUpdate 相同的 500 ms 刷新(冷却、数量、激活状态) if app.GetGlobalTime() - self.lastRefresh > 500: