Add hatch retention, automatic breakthroughs and exploration

This commit is contained in:
AttilaNet
2026-11-09 11:27:29 +08:00
parent 26be820ff2
commit 9f819d828a
32 changed files with 6207 additions and 83 deletions
+411
View File
@@ -0,0 +1,411 @@
"""Independent Qt exploration page; heavy snapshot work belongs in workers."""
from __future__ import annotations
from dataclasses import replace
import copy
from PySide6 import QtCore as C, QtWidgets as W
from .exploration import ExplorePolicy, ExploreTeamRule
from .model import duration
from .native_widgets import ComboBox, IntegerInput, RowBatch
from .table_widgets import CenteredCheckBox, set_value, table_item
def prepare_exploration_rows(engine):
"""Worker boundary: return only small plain-data DTOs, no Qt objects."""
if engine.snapshot is None:
return []
planner = engine.explore_planner
snapshot = engine.snapshot
policy = engine.explore_policy
ranch = engine.policy
rows = planner.rows(snapshot, policy, ranch)
prepared = []
for row in rows:
labels = []
for mid in row["monster_ids"]:
mon = snapshot.monsters.get(mid)
labels.append((planner.catalog.monster_label(mon) + f" Lv.{mon.get('level', 0)}") if mon else f"#{mid}")
prepared.append(dict(row, monster_labels=labels,
remaining_text=duration(row["remaining"]) if row["remaining"] is not None else "—",
cost_text=f"{row['cost_ti']} / {duration(row['cost_time'])}"))
return prepared
def prepare_exploration_members(engine, team_id):
"""Worker candidate DTOs include protected monsters with exclusion reasons."""
if engine.snapshot is None:
return []
return engine.explore_planner.member_options(engine.snapshot, int(team_id),
engine.explore_policy, engine.policy)
class ExplorationTable(W.QTableWidget):
"""Own each cell once and mutate it in place during every later render."""
cell_changed = C.Signal(str, str, object)
def __init__(self, parent=None):
super().__init__(0, 7, parent)
self.setHorizontalHeaderLabels(["启用", "队伍", "地区", "状态 / 剩余", "队员", "体力 / 时长", "说明"])
self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
self.horizontalHeader().setStretchLastSection(True)
self.verticalHeader().setDefaultSectionSize(34)
self.verticalHeader().setMinimumSectionSize(30)
self.row_batch = RowBatch(self)
self._cells = {}
self._controls = {}
self._generation = 0
self._rendering = False
@staticmethod
def _cell_widget(control):
cell = W.QWidget()
layout = W.QHBoxLayout(cell)
layout.setContentsMargins(2, 0, 2, 0)
layout.setSpacing(4)
layout.addWidget(control)
return cell
def _make_row(self, key, area_options):
enabled = CenteredCheckBox()
enabled.setToolTip("启用此探险队;完成领奖后再出发")
enabled.setFixedWidth(26)
auto = W.QPushButton("自动选三只")
auto.setToolTip("只选择未被战斗队、喂养、赠礼或突破目标占用的魔物")
area = ComboBox()
area.addItem("请选择地区", "")
for area_id, name in area_options:
area.addItem(f"{name}({area_id})", area_id)
members = []
for position in range(3):
combo = ComboBox()
combo.setMinimumContentsLength(3)
combo.setToolTip(["队长", "队员(等级不可高于队长)", "队员(等级不可高于队长)"][position])
members.append(combo)
member_cell = W.QWidget()
line = W.QHBoxLayout(member_cell)
line.setContentsMargins(2, 0, 2, 0)
line.setSpacing(3)
for combo in members:
line.addWidget(combo, 1)
line.addWidget(auto)
cells = {}
for column in range(self.columnCount()):
item = table_item("", column)
item.setFlags(item.flags() & ~C.Qt.ItemFlag.ItemIsEditable)
cells[column] = item
enabled.toggled.connect(lambda checked, key=key: self.cell_changed.emit(key, "enabled", checked))
area.currentIndexChanged.connect(lambda index, key=key: self.cell_changed.emit(key, "area", area.itemData(index) or ""))
for position, combo in enumerate(members):
combo.currentIndexChanged.connect(lambda index, key=key, position=position, combo=combo:
self.cell_changed.emit(key, "monster", (position, combo.itemData(index))))
auto.clicked.connect(lambda checked=False, key=key: self.cell_changed.emit(key, "auto", None))
return {"enabled": enabled, "area": area, "members": members, "auto": auto,
"enabled_cell": self._cell_widget(enabled), "area_cell": self._cell_widget(area),
"member_cell": member_cell, "cells": cells}
def set_rows(self, rows, policies, area_options, member_options):
self._generation += 1
generation = self._generation
self.row_batch.stop()
self._rendering = True
self.setSortingEnabled(False)
active = {str(row["team_id"]) for row in rows}
for key in set(self._controls) - active:
control = self._controls.pop(key)
for column in range(self.columnCount()):
item = self._cells[key][column]
index = self.indexFromItem(item)
if index.isValid():
self.removeCellWidget(index.row(), column)
self._cells.pop(key, None)
self.setRowCount(len(rows))
ordered = []
for index, row in enumerate(rows):
key = str(row["team_id"])
control = self._controls.get(key)
if control is None:
control = self._controls[key] = self._make_row(key, area_options)
self._cells[key] = control["cells"]
for column, item in self._cells[key].items():
# setItem is used only when this stable item is not in a table.
if item.tableWidget() is None:
self.setItem(index, column, item)
self.setCellWidget(index, 0, control["enabled_cell"])
self.setCellWidget(index, 2, control["area_cell"])
self.setCellWidget(index, 4, control["member_cell"])
ordered.append((index, row, control, policies[key], member_options.get(key, [])))
def apply(entry):
index, row, control, policy, options = entry
if generation != self._generation:
return
self._rendering = True
control["enabled"].setChecked(policy.enabled)
control["area"].setCurrentIndex(control["area"].findData(policy.area))
self._set_members(control, policy, options)
control["enabled"].setEnabled(row["state"] not in ("探索中", "可领取", "待核对"))
control["area"].setEnabled(row["state"] not in ("探索中", "可领取", "待核对"))
for combo in control["members"]:
combo.setEnabled(control["area"].isEnabled())
control["auto"].setEnabled(control["area"].isEnabled() and bool(options))
texts = {1: str(row["team_id"]),
3: row["state"] + " / " + row["remaining_text"],
5: row["cost_text"], 6: row["reason"] or ("手动指定;允许锁定 / 装备" if row["manual"] else "自动选空闲魔物")}
for column, value in texts.items():
item = self._cells[str(row["team_id"])][column]
set_value(item, column, value)
item.setToolTip(value)
self._cells[str(row["team_id"])][1].setData(C.Qt.ItemDataRole.UserRole, str(row["team_id"]))
def finish():
self._rendering = False
self.resizeColumnsToContents()
self.setColumnWidth(2, min(240, max(160, self.columnWidth(2))))
self.setColumnWidth(4, 440)
self.row_batch.start(ordered, apply, finish)
def _set_members(self, control, policy, options):
by_id = {str(option["id"]): option for option in options}
for position, combo in enumerate(control["members"]):
selected = policy.monsters[position] if policy.monsters else None
combo.clear()
combo.addItem("自动", None)
# Manual lists include locked/equipped and other automation targets.
for option in options:
reason = ";" + option["reason"] if option["reason"] else ""
combo.addItem(f"{option['label']} Lv.{option['level']}{reason}", option["id"])
if selected is not None and str(selected) not in by_id:
combo.addItem(f"#{selected}(当前快照不存在)", selected)
combo.setCurrentIndex(combo.findData(selected))
class ExplorationPages:
"""Mixin: engine.explore_planner/explore_policy/policy + tabs/submit."""
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)
self.explore_refresh_button = W.QPushButton("刷新探险状态")
tools.addWidget(self.explore_enabled)
tools.addWidget(W.QLabel("保留体力"))
tools.addWidget(self.explore_reserve_ti)
tools.addWidget(self.explore_refresh_button)
tools.addStretch()
layout.addLayout(tools)
self.exploration_summary = W.QLabel("领奖后再出发;不自动花钱开队或召回。手动队员允许锁定、装备和其他培养目标。")
self.exploration_summary.setWordWrap(True)
layout.addWidget(self.exploration_summary)
self.exploration_table = ExplorationTable(self.exploration_page)
layout.addWidget(self.exploration_table, 1)
self.exploration_detail = W.QLabel("留空任一槽位即恢复自动选人;手动选择需三只不同魔物,队员等级不高于队长。")
self.exploration_detail.setWordWrap(True)
layout.addWidget(self.exploration_detail)
self.tabs.addTab(self.exploration_page, "自动探险")
self._exploration_policy = ExplorePolicy.from_dict(getattr(self.engine, "explore_policy", ExplorePolicy()).to_dict())
self._exploration_rows = []
self._exploration_member_options = {}
self._exploration_rendering = False
self._exploration_generation = 0
self._exploration_member_queue = []
self._exploration_member_busy = False
self._exploration_drafts = {}
self._exploration_engine_identity = None
self._exploration_role_key = None
self.explore_enabled.toggled.connect(self.exploration_settings_changed)
self.explore_reserve_ti.valueChanged.connect(self.exploration_settings_changed)
self.explore_refresh_button.clicked.connect(self.refresh_exploration)
self.exploration_table.cell_changed.connect(self._exploration_cell_changed)
self._exploration_complete_member_request()
def read_explore_policy(self):
# Read the retained full configuration, never the currently visible rows.
return ExplorePolicy.from_dict(self._exploration_policy.to_dict())
def exploration_settings_changed(self, *args):
if self.closed or self.loading_config or self._exploration_rendering:
return
self._exploration_policy = replace(self._exploration_policy,
enabled=self.explore_enabled.isChecked(), reserve_ti=self.explore_reserve_ti.value())
self._save_exploration_policy()
def _save_exploration_policy(self):
# Host update_policy() serializes configuration with account jobs.
self.settings_changed()
def _exploration_cell_changed(self, key, field, value):
if self._exploration_rendering or self.exploration_table._rendering:
return
if field == "auto":
# QPushButton.clicked carries a bool, but auto is not a field on
# ExploreTeamRule; always reset the saved trio explicitly.
self._exploration_drafts.pop(key, None)
self._exploration_policy.teams[key] = replace(self._exploration_policy.teams.get(key, ExploreTeamRule()), monsters=[])
self._save_exploration_policy()
self.exploration_detail.setText("已恢复自动选人;排除原因显示在各槽位下拉列表中。")
self._set_team_members(key)
return
rule = self._exploration_policy.teams.get(key, ExploreTeamRule())
if field == "enabled":
rule = replace(rule, enabled=bool(value))
self._exploration_policy.teams[key] = rule
self._save_exploration_policy()
elif field == "area":
rule = replace(rule, area=str(value))
self._exploration_drafts.pop(key, None)
self._exploration_policy.teams[key] = rule
self._save_exploration_policy()
elif field == "monster":
position, mid = value
if not 0 <= position < 3:
return
members = self._exploration_drafts.get(key)
if members is None:
members = list(rule.monsters) if rule.monsters else [None, None, None]
members[position] = mid
self._exploration_drafts[key] = members
if all(mid is not None for mid in members):
self._exploration_policy.teams[key] = replace(rule, monsters=[int(mid) for mid in members])
self._exploration_drafts.pop(key, None)
self._save_exploration_policy()
else:
self.exploration_detail.setText("正在选择手动队员;三格选齐后保存,刷新不会清除草稿。")
return
elif field == "auto":
rule = replace(rule, monsters=[])
self._exploration_drafts.pop(key, None)
self._exploration_policy.teams[key] = rule
self._save_exploration_policy()
self._exploration_detail.setText("已恢复自动选人;排除原因显示在各槽位下拉列表中。")
if field in ("area", "auto"):
self.refresh_exploration()
def exploration_item_changed(self, item):
# Compatibility with the old mixin; the native page uses widgets.
self.exploration_settings_changed()
def refresh_exploration(self):
if self.closed:
return
if self.busy:
self.pending_refresh = self.exploration_page
return
generation = self._exploration_generation + 1
self._exploration_generation = generation
self.explore_refresh_button.setEnabled(False)
self.submit("exploration_view", lambda: prepare_exploration_rows(self.engine))
def _exploration_complete_member_request(self):
"""Drain the host's one-shot member job before scheduling the next."""
self._exploration_member_busy = False
if getattr(self, "_exploration_member_timer", None) is None:
self._exploration_member_timer = C.QTimer(self.exploration_page)
self._exploration_member_timer.setSingleShot(True)
self._exploration_member_timer.setInterval(0)
self._exploration_member_timer.timeout.connect(self._request_next_exploration_members)
self._exploration_member_timer.start()
def reset_exploration_account(self):
"""Host calls on login/switch; no candidates or drafts cross roles."""
self._exploration_generation += 1
self._exploration_member_options.clear()
self._exploration_drafts.clear()
self._exploration_member_queue.clear()
self._exploration_rows = []
self._exploration_member_busy = False
self._exploration_role_key = None
self._exploration_engine_identity = id(self.engine)
if hasattr(self, "exploration_table"):
self.exploration_table.set_rows([], {}, [], {})
def render_exploration(self, rows=None):
if not hasattr(self, "exploration_table"):
return
if rows is None:
# Explicit synchronous use in unit tests is worker-free. Host code
# must call refresh_exploration()/accept result for live snapshots.
rows = prepare_exploration_rows(self.engine)
identity = id(self.engine)
role_key = None
if self.engine.snapshot is not None:
role_key = self.engine.explore_planner.role_key(self.engine.snapshot)
if self._exploration_engine_identity not in (None, identity) or self._exploration_role_key not in (None, role_key):
self.reset_exploration_account()
self._exploration_engine_identity = identity
self._exploration_role_key = role_key
self._exploration_rows = list(rows)
self._exploration_rendering = True
try:
self.explore_enabled.setChecked(self._exploration_policy.enabled)
self.explore_reserve_ti.setValue(self._exploration_policy.reserve_ti)
keys = [str(row["team_id"]) for row in rows]
policies = copy.deepcopy(self._exploration_policy.teams)
for key in keys:
policies.setdefault(key, ExploreTeamRule())
if key in self._exploration_drafts:
# UI-only partial drafts are deliberately not a valid
# ExploreTeamRule and never enter engine configuration.
policies[key].monsters = list(self._exploration_drafts[key])
areas = [(key, row.get("name") or key) for key, row in self.engine.explore_planner.areas.items()]
self.exploration_table.set_rows(rows, policies, areas, self._exploration_member_options)
self.exploration_summary.setText(f"已有 {len(rows)} 支探险队;配置 {len(self._exploration_policy.teams)} 支;启用 {sum(rule.enabled for rule in self._exploration_policy.teams.values())} 支")
self._exploration_member_queue = [key for key in keys if key not in self._exploration_member_options]
finally:
self._exploration_rendering = False
self._request_next_exploration_members()
def _set_team_members(self, key):
control = self.exploration_table._controls.get(str(key))
if control is None:
return
self._exploration_rendering = True
self.exploration_table._rendering = True
try:
self.exploration_table._set_members(control, self._exploration_policy.teams[str(key)],
self._exploration_member_options.get(str(key), []))
finally:
self.exploration_table._rendering = False
self._exploration_rendering = False
def _request_next_exploration_members(self):
if self.closed or self._exploration_member_busy or not self._exploration_member_queue:
return
key = self._exploration_member_queue.pop(0)
if self.busy:
self._exploration_member_queue.insert(0, key)
return
self._exploration_member_busy = True
generation = self._exploration_generation
self.submit("exploration_members:" + key,
lambda key=key: (generation, key, prepare_exploration_members(self.engine, key)))
def accept_exploration_members(self, generation, key, options):
if generation == self._exploration_generation:
self._exploration_member_options[key] = options
self.render_exploration(self._exploration_rows)
self._exploration_complete_member_request()
def apply_explore_policy(self, policy):
"""Apply/import the entire policy before rendering, including hidden teams."""
if isinstance(policy, dict):
policy = ExplorePolicy.from_dict(policy)
self._exploration_policy = ExplorePolicy.from_dict(policy.to_dict())
self._exploration_rendering = True
try:
self.explore_enabled.setChecked(policy.enabled)
self.explore_reserve_ti.setValue(policy.reserve_ti)
finally:
self._exploration_rendering = False
def accept_exploration_view(self, rows):
self.explore_refresh_button.setEnabled(True)
self.render_exploration(rows)
self._exploration_complete_member_request()