Files
myrzx_bot/ranch_assistant/exploration_gui.py
T

135 lines
6.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Native Qt exploration settings; planning and refresh stay off the UI thread."""
from dataclasses import asdict
from PySide6 import QtCore as C, QtWidgets as W
from .exploration import ExplorePolicy, ExploreTeamRule
from .model import duration
from .native_widgets import ComboBox, IntegerInput
def prepare_exploration_rows(engine):
"""Worker boundary: return plain data and never construct Qt objects."""
if engine.snapshot is None:
return []
return engine.explore_planner.rows(engine.snapshot, engine.explore_policy, engine.policy)
class ExplorationPages:
def exploration_tab(self):
self.exploration_page = W.QWidget()
layout = W.QVBoxLayout(self.exploration_page)
tools = W.QHBoxLayout()
self.explore_enabled = W.QCheckBox("启用自动探险")
self.explore_reserve_ti = IntegerInput()
self.explore_reserve_ti.setRange(0, 1_000_000_000)
tools.addWidget(self.explore_enabled)
tools.addWidget(W.QLabel("保留体力"))
tools.addWidget(self.explore_reserve_ti)
refresh = W.QPushButton("刷新探险状态")
refresh.clicked.connect(self.refresh_exploration)
tools.addWidget(refresh)
tools.addStretch()
layout.addLayout(tools)
self.exploration_summary = W.QLabel("登录后显示已有探险队;不自动召回或花钱新增队伍")
self.exploration_summary.setWordWrap(True)
layout.addWidget(self.exploration_summary)
self.exploration_table = W.QTableWidget(0, 8)
self.exploration_table.setHorizontalHeaderLabels(["启用", "队伍", "地区", "状态", "剩余时间", "队员", "体力 / 时长", "说明"])
self.exploration_table.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
self.exploration_table.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
self.exploration_table.horizontalHeader().setStretchLastSection(True)
self.exploration_table.verticalHeader().setDefaultSectionSize(25)
layout.addWidget(self.exploration_table, 1)
note = W.QLabel("每队独立勾选并选择地区;先领取已完成奖励,再自动派出。队员选择遵守牧场保护规则,队员等级不高于队长。")
note.setWordWrap(True)
layout.addWidget(note)
self.tabs.addTab(self.exploration_page, "自动探险")
self._exploration_rendering = False
self._exploration_controls = {}
self.explore_enabled.toggled.connect(self.exploration_settings_changed)
self.explore_reserve_ti.valueChanged.connect(self.exploration_settings_changed)
self.exploration_table.itemChanged.connect(self.exploration_item_changed)
def read_explore_policy(self):
teams = {}
for key, controls in self._exploration_controls.items():
teams[key] = ExploreTeamRule(controls["enabled"].checkState() == C.Qt.CheckState.Checked,
str(controls["area"].currentData() or ""))
return ExplorePolicy(self.explore_enabled.isChecked(), teams, self.explore_reserve_ti.value())
def exploration_settings_changed(self, *args):
if self.closed or self.loading_config or getattr(self, "_exploration_rendering", False):
return
policy = self.read_explore_policy()
self.engine.explore_policy = policy
if hasattr(self, "pending_policy") and self.pending_policy is not None:
self.pending_policy["explore_policy"] = policy
self.settings_changed()
def exploration_item_changed(self, item):
if item.column() == 0:
self.exploration_settings_changed()
def refresh_exploration(self):
if self.closed:
return
if self.busy:
self.pending_refresh = self.exploration_page
return
self.submit("exploration_view", lambda: prepare_exploration_rows(self.engine))
def render_exploration(self, rows=None):
if not hasattr(self, "exploration_table"):
return
rows = prepare_exploration_rows(self.engine) if rows is None else rows
self._exploration_rendering = True
try:
self.exploration_table.setRowCount(len(rows))
active = set()
for index, row in enumerate(rows):
key = str(row["team_id"])
active.add(key)
controls = self._exploration_controls.get(key)
if controls is None:
enabled = W.QTableWidgetItem()
enabled.setFlags(C.Qt.ItemFlag.ItemIsEnabled | C.Qt.ItemFlag.ItemIsUserCheckable)
area = ComboBox()
for area_id, config in self.engine.explore_planner.areas.items():
area.addItem(f"{config.get('name') or area_id}({area_id})", area_id)
area.currentIndexChanged.connect(self.exploration_settings_changed)
controls = {"enabled": enabled, "area": area}
self._exploration_controls[key] = controls
enabled, area = controls["enabled"], controls["area"]
enabled.setCheckState(C.Qt.CheckState.Checked if row["enabled"] else C.Qt.CheckState.Unchecked)
enabled.setData(C.Qt.ItemDataRole.UserRole, key)
self.exploration_table.setItem(index, 0, enabled)
if area.count():
position = area.findData(row["area"])
area.setCurrentIndex(position if position >= 0 else -1)
self.exploration_table.setCellWidget(index, 2, area)
monsters = "、".join(self.catalog.monster_label(mon) for mid in row["monster_ids"]
if (mon := self.engine.snapshot.monsters.get(mid)) is not None) or "—"
values = [key, "", row["state"], duration(row["remaining"]) if row["remaining"] is not None else "—",
monsters, f"{row['cost_ti']} / {duration(row['cost_time'])}", row["reason"]]
for column, text in enumerate(values, 1):
if column == 2:
continue
cell = self.exploration_table.item(index, column) or W.QTableWidgetItem()
cell.setText(text)
cell.setToolTip(text)
self.exploration_table.setItem(index, column, cell)
for key in set(self._exploration_controls) - active:
self._exploration_controls.pop(key)
self.exploration_summary.setText(f"已有 {len(rows)} 支探险队;启用 {sum(row['enabled'] for row in rows)} 支")
finally:
self._exploration_rendering = False
def apply_explore_policy(self, policy):
"""Apply imported/saved plain configuration before rendering rows."""
if isinstance(policy, dict):
policy = ExplorePolicy.from_dict(policy)
self.explore_enabled.setChecked(policy.enabled)
self.explore_reserve_ti.setValue(policy.reserve_ti)
self.engine.explore_policy = policy