Keep multi-account refresh responsive and batch monster feeding
This commit is contained in:
@@ -19,7 +19,7 @@ writes stop with a persisted pending record; no automatic replay occurs.
|
||||
VIP daily gifts and mail attachment claims. Refreshes remain read-only; explicit
|
||||
selection and execution are required. Null VIPs, millisecond/second timestamps,
|
||||
JSON mail rewards and stale reads are handled. New policy and budget files remain
|
||||
role-isolated. Full local suite: 101 tests passed. Live reward/sweep use is still
|
||||
role-isolated. Full local suite: 113 tests passed. Live reward/sweep use is still
|
||||
unverified; no real account or phone was operated during this work.
|
||||
|
||||
The screenshot page remains necessary for ADB real battles such as special
|
||||
@@ -199,7 +199,8 @@ method informs the configurable strategy; numeric values come from the APK.
|
||||
|
||||
## Validation and remaining inputs
|
||||
|
||||
101 unit/integration tests pass: mature incubator dispatch contract, eligible-stage sweep and daily claim workflows,
|
||||
113 unit/integration tests pass: responsive multi-account snapshots, batched feeding,
|
||||
mature incubator dispatch contract, eligible-stage sweep and daily claim workflows,
|
||||
pending writes and role/day budgets, stage tree/rule restoration and scroll
|
||||
geometry, plus local encrypted HTTP and inventory actions,
|
||||
SDK password form/headers -> two Android regions -> selected region entry ->
|
||||
@@ -300,3 +301,32 @@ while they were playing.
|
||||
The activity's standalone daily-limit field remains unidentified. Farming checks
|
||||
available tickets plus a labeled local daily attempt limit, including failures
|
||||
and interruptions. This is not claimed to query the official daily quota.
|
||||
|
||||
## Refresh performance and batch feeding
|
||||
|
||||
The reported freeze occurred after HTTP completion: hidden pages/accounts rebuilt
|
||||
all tables and thousands of stage controls on the GUI thread. The all-stage build
|
||||
alone measured about 1506ms before the fix. Repeated ResizeToContents layout work
|
||||
and formatting hidden debug JSON added avoidable GUI work.
|
||||
|
||||
Pure attribute/stage presentation is now prepared by each account's existing
|
||||
worker. Queued Qt slots own all widgets. Hidden account/page tables are deferred;
|
||||
map, monster and egg rows use bounded ~8ms batches and reuse existing controls.
|
||||
Column sizes are interactive, and closed debug windows do not format JSON.
|
||||
Background requests remain serial within one account, concurrent across accounts.
|
||||
The trace separates worker total (including HTTP), preparation and UI callbacks.
|
||||
|
||||
The local 80-monster/4000-egg plus 500-monster two-account fixture, with 700ms mock
|
||||
network waits, recorded 2.1/10.5ms UI callbacks and 30.75ms maximum event-loop gap.
|
||||
See REFRESH_PERFORMANCE.json. This is a local synthetic measurement, not a live
|
||||
server or hardware-wide guarantee. No real inventory mutations were performed.
|
||||
|
||||
NetStack.moveMonster accepts per-room arrays, allowing capacity-checked collection
|
||||
batches. NetMonster.feedMonster accepts foods arrays; MonsterSelectPanel.modeFeed
|
||||
allows multiple materials without a small fixed count. monster_level now supplies
|
||||
the cumulative experience thresholds. Automatic feeding combines eligible managed
|
||||
materials until the target stop level's required experience is met, retaining all
|
||||
per-monster protections. Continuous actions advance after fresh reads, while the
|
||||
monitor interval governs idle waiting. Logs include ID and species/nickname for
|
||||
both target and each material. Regression tests verify batches, caps, target
|
||||
priority, capacity accounting and responsive two-account GUI event processing.
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"fixture": "80 monsters and 4000 eggs; second account 500 monsters",
|
||||
"network_delay_ms": 700,
|
||||
"accounts": [
|
||||
{
|
||||
"worker_total_ms": 805.8,
|
||||
"data_prepare_ms": 36.5,
|
||||
"ui_callback_ms": 10.5
|
||||
},
|
||||
{
|
||||
"worker_total_ms": 801.2,
|
||||
"data_prepare_ms": 47.5,
|
||||
"ui_callback_ms": 2.1
|
||||
}
|
||||
],
|
||||
"max_ui_event_gap_ms": 30.75
|
||||
}
|
||||
@@ -235,7 +235,8 @@
|
||||
- 自定义表:`typeId, sell_money, sell_exp, time_total`(秒),可只提供部分
|
||||
覆盖列;中文列名“编号、派遣金币、强化经验、孵化秒数”也支持。
|
||||
- 测试:`python -m unittest discover -s ranch_assistant/tests -v`。
|
||||
- 101 项测试通过,包含培育室派遣997的加密HTTP复现与修复回归;覆盖难度列表解析、扫荡条件/请求顺序/异常暂停/跨角色每日额度、
|
||||
- 113 项测试通过,包含双账号慢网络与大量库存的界面响应、后台账号不重建表格、控件复用、
|
||||
批量喂养和培育室派遣997的加密HTTP回归;覆盖难度列表解析、扫荡条件/请求顺序/异常暂停/跨角色每日额度、
|
||||
签到与邮件JSON/空VIP/时间单位/失败不重试、树形规则恢复和截图页不重叠;以及
|
||||
加密HTTP十连→实际赠蛋→负数空坑孵化→成长结算→派遣→余额刷新、逐种优先级和补货、
|
||||
多目标喂养优先级、锁定/手动派遣/喂养、开坑与建牧场的费用复核和取消确认、金币/库存/每日额度限制、
|
||||
@@ -278,3 +279,25 @@ VIP奖励只对已有资格领取;不会购买VIP或升级礼包。邮件仅
|
||||
这些是安装包配置中的可能掉落,并非实时掉落概率保证;后续热更新新增数据需要重新提取。
|
||||
本次签到、领邮件和扫荡均由本地模拟验证,尚未在真实账号上执行验证。
|
||||
静态证据与字段规则见 `analysis/STAGES_DAILY.md`。
|
||||
|
||||
## 刷新响应与批量喂养
|
||||
|
||||
网络和属性/关卡资料计算在各账号的后台线程执行,账号之间并行;同一账号的请求与库存操作保持顺序。
|
||||
只更新当前账号正在查看的页面,其他账号保存最新快照,切过去时再显示。
|
||||
魔物、蛋和地图的大列表分成约8ms的小批次更新;未变化的控件复用,不再每轮重建整页。
|
||||
魔物表、蛋表的列宽可手动拖动,避免每次更新都扫描所有单元格计算宽度。
|
||||
调试窗关闭时不排版完整响应JSON;请求日志仍照常保存。
|
||||
|
||||
本地模拟两个账号:一个80只魔物、4000枚蛋(200类),另一个500只魔物,各有700ms网络等待。
|
||||
本次测得回包界面回调约2~11ms,界面事件最大间隔30.75ms。这个数字来自测试环境,
|
||||
不是所有电脑的耗时承诺。调试记录新增“刷新耗时”,分别记录后台总时间、资料整理时间和界面回调时间。
|
||||
|
||||
自动收取会按牧场剩余容量合并提交;自动喂养把同一目标的合格素材放入一次`foods`数组请求,
|
||||
按照喂养目标优先级执行,数字越小越优先。当前目标达到停止等级/突破上限后换下一个目标。
|
||||
批量素材按升级经验表计算,达到需要的经验后停止添加;最后一只素材可能有少量溢出。
|
||||
锁定、在队、高星、资质保护及委托保留仍参与每只素材的筛选。
|
||||
有连续动作时自动推进;设置的监控间隔用于等待新状态,不再要求每收取或喂养一只都等待完整间隔。
|
||||
每次写操作后仍重新读取状态,喂养已返回但素材仍在旧快照中时暂停核对,避免重复提交。
|
||||
|
||||
喂养日志同时列出目标和全部素材的实例ID、魔物名称、素材数量;有昵称时也会显示。
|
||||
本轮没有向真实账号执行收取、派遣或喂养。性能记录见`analysis/REFRESH_PERFORMANCE.json`。
|
||||
|
||||
@@ -39,6 +39,7 @@ class AccountsWindow(W.QMainWindow):
|
||||
note.setWordWrap(True)
|
||||
layout.addWidget(note)
|
||||
self.tabs = W.QTabWidget()
|
||||
self.tabs.currentChanged.connect(self.activate_profile)
|
||||
self.tabs.setTabsClosable(True)
|
||||
self.tabs.tabCloseRequested.connect(self.close_profile)
|
||||
layout.addWidget(self.tabs, 1)
|
||||
@@ -79,6 +80,11 @@ class AccountsWindow(W.QMainWindow):
|
||||
self.open_profile(profile)
|
||||
self.save_index()
|
||||
|
||||
def activate_profile(self, *args):
|
||||
active = self.tabs.currentWidget()
|
||||
for window in self.windows.values():
|
||||
window.set_presentation_active(window is active)
|
||||
|
||||
def choose_profile(self):
|
||||
if not self.profiles:
|
||||
return
|
||||
|
||||
@@ -3,7 +3,8 @@ from PySide6 import QtCore as C, QtWidgets as W
|
||||
|
||||
from .daily import DailyPolicy, entries
|
||||
from .maps import stages
|
||||
from .native_widgets import IntegerInput
|
||||
from .native_widgets import IntegerInput, RowBatch
|
||||
from .presentation import map_source
|
||||
from .sweeping import SweepPolicy
|
||||
|
||||
|
||||
@@ -112,64 +113,95 @@ class ActivityPages:
|
||||
if isinstance(focused, W.QLineEdit) and self.maps_tree.isAncestorOf(focused):
|
||||
return
|
||||
snapshot = self.engine.snapshot
|
||||
all_rows = stages(self.catalog, snapshot)
|
||||
views = self.prepared_views
|
||||
all_rows = views.maps if views and views.snapshot is snapshot and views.map_source == map_source(snapshot) else stages(self.catalog, snapshot)
|
||||
grouped = {}
|
||||
for row in all_rows:
|
||||
grouped.setdefault(row.stage_id, []).append(row)
|
||||
query = self.map_search.text().strip().casefold()
|
||||
expanded = {self.maps_tree.topLevelItem(i).text(0) for i in range(self.maps_tree.topLevelItemCount()) if self.maps_tree.topLevelItem(i).isExpanded()}
|
||||
old = self.maps_tree.currentItem()
|
||||
selected = old.data(0, C.Qt.ItemDataRole.UserRole) if old else None
|
||||
first_render = not self.maps_tree.topLevelItemCount()
|
||||
blocker = C.QSignalBlocker(self.maps_tree)
|
||||
self.maps_tree.clear()
|
||||
cities, shown = {}, 0
|
||||
policy = self.read_sweep_policy()
|
||||
team_ids = self.engine.sweeper.team_ids(snapshot, policy)
|
||||
visible = []
|
||||
for key, options in sorted(grouped.items(), key=lambda pair: (pair[1][0].city, pair[1][0].number, pair[0])):
|
||||
first = options[0]
|
||||
if self.only_unlocked.isChecked() and not any(s.unlocked for s in options):
|
||||
continue
|
||||
if query and query not in (first.city_name + key + first.number + first.name + " ".join(s.drops for s in options)).casefold():
|
||||
continue
|
||||
shown += 1
|
||||
city = cities.get(first.city)
|
||||
if city is None:
|
||||
city = W.QTreeWidgetItem(self.maps_tree, [first.city_name])
|
||||
city.setFirstColumnSpanned(True)
|
||||
city.setExpanded(first_render or first.city_name in expanded)
|
||||
cities[first.city] = city
|
||||
rule = self.map_rules.get(key, {})
|
||||
chosen = next((s for s in options if s.level == str(rule.get("level"))), None) if rule else None
|
||||
chosen = chosen or next((s for s in reversed(options) if s.unlocked), first)
|
||||
reason = self.engine.sweeper.reason(snapshot, chosen, policy)
|
||||
item = W.QTreeWidgetItem(city, ["", first.number, first.name, "", "★" * first.stars + "☆" * (3 - first.stars),
|
||||
reason or "可扫荡", str(chosen.stamina) + (" / " + chosen.tickets if chosen.tickets else ""), chosen.drops, "", str(self.engine.sweeper.used(snapshot, chosen))])
|
||||
item.setData(0, C.Qt.ItemDataRole.UserRole, key)
|
||||
item.setCheckState(0, C.Qt.CheckState.Checked if rule.get("enabled") else C.Qt.CheckState.Unchecked)
|
||||
if not any(s.unlocked and s.open for s in options):
|
||||
item.setFlags(item.flags() & ~C.Qt.ItemFlag.ItemIsUserCheckable)
|
||||
for col in (5, 6, 7):
|
||||
item.setToolTip(col, item.text(col))
|
||||
difficulty = W.QComboBox()
|
||||
for s in options:
|
||||
difficulty.addItem(f"难度 {s.level}" + ("(已通关)" if s.passed else ""), s.level)
|
||||
difficulty.model().item(difficulty.count() - 1).setEnabled(s.unlocked and s.open)
|
||||
difficulty.setCurrentIndex(difficulty.findData(chosen.level))
|
||||
# Keep displayed defaults and execution defaults identical.
|
||||
self.map_rules.setdefault(key, {"enabled": False, "level": chosen.level, "limit": 3})
|
||||
if not rule.get("enabled"):
|
||||
self.map_rules[key]["level"] = chosen.level
|
||||
difficulty.currentIndexChanged.connect(lambda index, key=key, widget=difficulty: self.map_rule_changed(key, level=widget.currentData()))
|
||||
limit = number(rule.get("limit", 3), 999)
|
||||
limit.valueChanged.connect(lambda value, key=key: self.map_rule_changed(key, limit=value))
|
||||
item.setSizeHint(0, C.QSize(90, max(difficulty.sizeHint().height(), limit.sizeHint().height()) + 4))
|
||||
self.maps_tree.setItemWidget(item, 3, difficulty)
|
||||
self.maps_tree.setItemWidget(item, 8, limit)
|
||||
if key == selected:
|
||||
self.maps_tree.setCurrentItem(item)
|
||||
del blocker
|
||||
reason = self.engine.sweeper.reason(snapshot, chosen, policy, team_ids=team_ids)
|
||||
visible.append((key, options, chosen, dict(self.map_rules[key]), reason))
|
||||
self._map_items = getattr(self, "_map_items", {})
|
||||
self._map_cities = getattr(self, "_map_cities", {})
|
||||
if not hasattr(self, "map_render_timer"):
|
||||
self.map_render_timer = RowBatch(self)
|
||||
wanted = {row[0] for row in visible}
|
||||
operations = [("remove", key) for key in self._map_items if key not in wanted] + [("row", row) for row in visible]
|
||||
first_render = not self.maps_tree.topLevelItemCount()
|
||||
def apply(operation):
|
||||
kind, data = operation
|
||||
blocker = C.QSignalBlocker(self.maps_tree)
|
||||
if kind == "remove":
|
||||
item = self._map_items.pop(data)
|
||||
item.parent().takeChild(item.parent().indexOfChild(item))
|
||||
return
|
||||
key, options, chosen, rule, reason = data
|
||||
first = options[0]
|
||||
city = self._map_cities.get(first.city)
|
||||
if city is None:
|
||||
city = W.QTreeWidgetItem(self.maps_tree, [first.city_name])
|
||||
city.setFirstColumnSpanned(True)
|
||||
city.setExpanded(first_render or bool(query))
|
||||
self._map_cities[first.city] = city
|
||||
item = self._map_items.get(key)
|
||||
if item is None:
|
||||
item = W.QTreeWidgetItem(city)
|
||||
item.setData(0, C.Qt.ItemDataRole.UserRole, key)
|
||||
difficulty = W.QComboBox()
|
||||
difficulty.currentIndexChanged.connect(lambda index, key=key, widget=difficulty: self.map_rule_changed(key, level=widget.currentData()))
|
||||
limit = number(rule.get("limit", 3), 999)
|
||||
limit.valueChanged.connect(lambda value, key=key: self.map_rule_changed(key, limit=value))
|
||||
self.maps_tree.setItemWidget(item, 3, difficulty)
|
||||
self.maps_tree.setItemWidget(item, 8, limit)
|
||||
item.setSizeHint(0, C.QSize(90, max(difficulty.sizeHint().height(), limit.sizeHint().height()) + 4))
|
||||
self._map_items[key] = item
|
||||
values = ["", first.number, first.name, "", "★" * first.stars + "☆" * (3 - first.stars), reason or "可扫荡",
|
||||
str(chosen.stamina) + (" / " + chosen.tickets if chosen.tickets else ""), chosen.drops, "", str(self.engine.sweeper.used(snapshot, chosen))]
|
||||
for col, text in enumerate(values):
|
||||
if item.text(col) != text:
|
||||
item.setText(col, text)
|
||||
if col in (5, 6, 7):
|
||||
item.setToolTip(col, text)
|
||||
item.setCheckState(0, C.Qt.CheckState.Checked if rule.get("enabled") else C.Qt.CheckState.Unchecked)
|
||||
flags = item.flags()
|
||||
item.setFlags(flags | C.Qt.ItemFlag.ItemIsUserCheckable if any(s.unlocked and s.open for s in options) else flags & ~C.Qt.ItemFlag.ItemIsUserCheckable)
|
||||
difficulty = self.maps_tree.itemWidget(item, 3)
|
||||
block_combo = C.QSignalBlocker(difficulty)
|
||||
labels = [(f"难度 {s.level}" + ("(已通关)" if s.passed else ""), s.level) for s in options]
|
||||
if [(difficulty.itemText(i), difficulty.itemData(i)) for i in range(difficulty.count())] != labels:
|
||||
difficulty.clear()
|
||||
for text, value in labels:
|
||||
difficulty.addItem(text, value)
|
||||
for i, stage in enumerate(options):
|
||||
difficulty.model().item(i).setEnabled(stage.unlocked and stage.open)
|
||||
difficulty.setCurrentIndex(difficulty.findData(chosen.level))
|
||||
limit = self.maps_tree.itemWidget(item, 8)
|
||||
block_limit = C.QSignalBlocker(limit)
|
||||
if not limit.hasFocus():
|
||||
limit.setValue(rule.get("limit", 3))
|
||||
def finish():
|
||||
for cid, city in list(self._map_cities.items()):
|
||||
if not city.childCount():
|
||||
self.maps_tree.takeTopLevelItem(self.maps_tree.indexOfTopLevelItem(city))
|
||||
del self._map_cities[cid]
|
||||
else:
|
||||
city.sortChildren(1, C.Qt.SortOrder.AscendingOrder)
|
||||
self.map_render_timer.start(operations, apply, finish)
|
||||
pending = self.engine.sweeper.state.get("pending")
|
||||
self.maps_summary.setText(f"已解锁 {sum(s.unlocked for s in all_rows)} 个难度;显示 {shown} 关;勾选 {sum(bool(r.get('enabled')) for r in self.map_rules.values())} 关。" +
|
||||
self.maps_summary.setText(f"已解锁 {sum(s.unlocked for s in all_rows)} 个难度;显示 {len(visible)} 关;勾选 {sum(bool(r.get('enabled')) for r in self.map_rules.values())} 关。" +
|
||||
(f" 待处理:{pending['stage']} / {pending['phase']}" if pending else "") +
|
||||
(" 正在执行扫荡计划。" if self.map_enabled.isChecked() and self.execute.isChecked() and self.monitoring else " 扫荡已停止。"))
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -33,6 +33,7 @@ class DebugWindow(W.QDialog):
|
||||
splitter.addWidget(self.rows)
|
||||
self.details = W.QPlainTextEdit()
|
||||
self.details.setReadOnly(True)
|
||||
self.details.setLineWrapMode(W.QPlainTextEdit.LineWrapMode.NoWrap)
|
||||
splitter.addWidget(self.details)
|
||||
splitter.setSizes([260, 400])
|
||||
layout.addWidget(splitter, 1)
|
||||
@@ -61,7 +62,12 @@ class DebugWindow(W.QDialog):
|
||||
return json.dumps(self.records[row], ensure_ascii=False, indent=2) if 0 <= row < len(self.records) else ""
|
||||
|
||||
def show_selected(self):
|
||||
self.details.setPlainText(self.selected_text())
|
||||
if self.isVisible():
|
||||
self.details.setPlainText(self.selected_text())
|
||||
|
||||
def showEvent(self, event):
|
||||
super().showEvent(event)
|
||||
self.show_selected()
|
||||
|
||||
def copy_selected(self):
|
||||
W.QApplication.clipboard().setText(self.selected_text())
|
||||
|
||||
@@ -3,7 +3,7 @@ import copy
|
||||
from dataclasses import asdict
|
||||
from PySide6 import QtCore as C, QtWidgets as W
|
||||
from .model import EggRule, duration
|
||||
from .native_widgets import IntegerInput
|
||||
from .native_widgets import IntegerInput, RowBatch
|
||||
|
||||
|
||||
class EggTable(W.QTableWidget):
|
||||
@@ -19,8 +19,9 @@ class EggTable(W.QTableWidget):
|
||||
self.setHorizontalHeaderLabels(headers)
|
||||
self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
self.horizontalHeader().setSectionResizeMode(W.QHeaderView.ResizeMode.ResizeToContents)
|
||||
self.horizontalHeader().setStretchLastSection(True)
|
||||
self.horizontalHeader().setSectionResizeMode(W.QHeaderView.ResizeMode.Interactive)
|
||||
for column, width in enumerate((130, 45, 65, 65, 90, 95, 95, 95, 160, 95, 90, 90, 100, 100, 160)):
|
||||
self.setColumnWidth(column, width)
|
||||
self.verticalHeader().setDefaultSectionSize(24)
|
||||
|
||||
def default_rule(self, key):
|
||||
@@ -29,7 +30,12 @@ class EggTable(W.QTableWidget):
|
||||
return asdict(EggRule(market_id=market))
|
||||
|
||||
def set_data(self, snapshot, rules, default_market="sc_city1"):
|
||||
self.snapshot, self.rules, self.default_market = snapshot, {str(key): asdict(EggRule(**rule)) for key, rule in rules.items()}, default_market
|
||||
normalized = {str(key): asdict(EggRule(**rule)) for key, rule in rules.items()}
|
||||
signature = (repr(snapshot.eggs(self.catalog)), normalized, default_market)
|
||||
if getattr(self, "render_signature", None) == signature:
|
||||
self.snapshot = snapshot
|
||||
return
|
||||
self.snapshot, self.rules, self.default_market = snapshot, normalized, default_market
|
||||
self.updating = True
|
||||
self.setSortingEnabled(False)
|
||||
groups = {}
|
||||
@@ -40,8 +46,13 @@ class EggTable(W.QTableWidget):
|
||||
group["ids"].append(str(egg["id"]))
|
||||
keys = list(dict.fromkeys(list(groups) + list(self.rules)))
|
||||
keys = [key for key in keys if self.catalog.monster(key)]
|
||||
old_keys = [self.item(i, 0).data(C.Qt.ItemDataRole.UserRole) for i in range(self.rowCount()) if self.item(i, 0)]
|
||||
keys = [key for key in old_keys if key in keys] + [key for key in keys if key not in old_keys]
|
||||
self.setRowCount(len(keys))
|
||||
for i, key in enumerate(keys):
|
||||
if not hasattr(self, "row_batch"):
|
||||
self.row_batch = RowBatch(self)
|
||||
def apply(entry):
|
||||
i, key = entry
|
||||
data, rule = self.catalog.monster(key), self.rules.get(key, self.default_rule(key))
|
||||
group = groups.get(key, {"count": 0, "ids": []})
|
||||
total = max(1, self.catalog.total_time(key))
|
||||
@@ -55,7 +66,19 @@ class EggTable(W.QTableWidget):
|
||||
item.setData(C.Qt.ItemDataRole.UserRole, key)
|
||||
item.setToolTip(f"魔物编号 {key}")
|
||||
self.setItem(i, j, item)
|
||||
existing = self.cellWidget(i, 3)
|
||||
if existing and existing.property("egg_type_id") == key:
|
||||
controls = [self.cellWidget(i, col) for col in range(3, 9)]
|
||||
blockers = [C.QSignalBlocker(control) for control in controls]
|
||||
controls[0].setChecked(rule["enabled"])
|
||||
for control, field in ((controls[1], "priority"), (controls[3], "refill_below"), (controls[4], "refill_target")):
|
||||
if not control.hasFocus():
|
||||
control.setValue(rule[field])
|
||||
controls[2].setCurrentIndex(max(0, controls[2].findData(rule["action"])))
|
||||
controls[5].setCurrentIndex(max(0, controls[5].findData(rule["market_id"])))
|
||||
return
|
||||
enabled = W.QCheckBox()
|
||||
enabled.setProperty("egg_type_id", key)
|
||||
enabled.setChecked(rule["enabled"])
|
||||
priority, below, target = IntegerInput(), IntegerInput(), IntegerInput()
|
||||
for control, low, high, value in ((priority, 1, 999, rule["priority"]), (below, 0, 1000, rule["refill_below"]),
|
||||
@@ -95,7 +118,11 @@ class EggTable(W.QTableWidget):
|
||||
control.valueChanged.connect(commit)
|
||||
action.currentIndexChanged.connect(commit)
|
||||
market.currentIndexChanged.connect(commit)
|
||||
self.setSortingEnabled(True)
|
||||
def finish():
|
||||
self.setSortingEnabled(True)
|
||||
self.updating = False
|
||||
self.render_signature = copy.deepcopy(signature)
|
||||
self.row_batch.start(enumerate(keys), apply, finish)
|
||||
self.updating = False
|
||||
|
||||
def add_rule(self, type_id):
|
||||
|
||||
@@ -27,6 +27,7 @@ class Engine:
|
||||
self.last_draw = ""
|
||||
self.growth_cache = {}
|
||||
self.growth_attempts = {}
|
||||
self.last_executed = False
|
||||
folder = Path(budget_path).parent if budget_path else None
|
||||
self.daily_policy = DailyPolicy()
|
||||
self.daily_ledger = DailyLedger(folder / "daily_claims.json" if folder else None)
|
||||
@@ -121,6 +122,7 @@ class Engine:
|
||||
return "会话心跳已更新"
|
||||
|
||||
def poll(self):
|
||||
self.last_executed = False
|
||||
settled = False
|
||||
if self.demo:
|
||||
if self.snapshot is None:
|
||||
@@ -143,6 +145,7 @@ class Engine:
|
||||
return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error)
|
||||
if self.auto and plans:
|
||||
action = plans[0]
|
||||
self.last_executed = True
|
||||
if action.kind == "daily":
|
||||
entry = next(row for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if row.action == action)
|
||||
self.claim_daily_entry(entry)
|
||||
@@ -164,6 +167,9 @@ class Engine:
|
||||
if action.kind == "buy":
|
||||
self.record_draw(response.get("eggs") or [])
|
||||
self.read_snapshot()
|
||||
if action.kind == "feed" and any(mid in self.snapshot.monsters for mid in action.payload["foods"]):
|
||||
self.auto = False
|
||||
raise ValueError("喂养已返回,但素材状态尚未同步;已停止,请刷新核对后再继续")
|
||||
message = ("[演示] " if self.demo else "") + action.description
|
||||
if action.kind == "buy" and self.last_draw:
|
||||
message += ";" + self.last_draw
|
||||
@@ -293,6 +299,15 @@ class Engine:
|
||||
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + quote.description + ",已完成"
|
||||
|
||||
def apply_demo(self, action):
|
||||
if action.kind == "collect" and sum(len(d["monsterId"]) for d in action.payload["datas"]) > 1:
|
||||
for data in action.payload["datas"]:
|
||||
for mid in data["monsterId"]:
|
||||
self.apply_demo(replace(action, payload={"datas": [{"monsterId": [mid], "roomId": data["roomId"]}]}))
|
||||
return
|
||||
if action.kind == "feed" and len(action.payload["foods"]) > 1:
|
||||
for mid in action.payload["foods"]:
|
||||
self.apply_demo(replace(action, payload=action.payload | {"foods": [mid]}))
|
||||
return
|
||||
raw = self.snapshot.raw
|
||||
if action.kind.startswith("quest_"):
|
||||
self.apply_demo_quest(action)
|
||||
|
||||
+165
-44
@@ -15,12 +15,13 @@ from .farming import Adb, FarmConfig, FarmRunner
|
||||
from .model import Catalog, Policy, WIKI, duration
|
||||
from .egg_rules_gui import EggTable
|
||||
from .management import expansion_quote, manual_monster_actions
|
||||
from .native_widgets import IntegerInput, use_native_scrollbars
|
||||
from .native_widgets import IntegerInput, RowBatch, use_native_scrollbars
|
||||
from .login import PasswordLogin, device_id, server_labels
|
||||
from .quests import QuestPolicy
|
||||
from .daily import DailyPolicy
|
||||
from .sweeping import SweepPolicy
|
||||
from .activity_gui import ActivityPages
|
||||
from .presentation import Presented, prepare_views, monster_rows
|
||||
from .capture import PAGES, load_buttons, read_profile, saved_profiles, save_page
|
||||
from .credentials import CredentialStore
|
||||
from .debug import TraceLog
|
||||
@@ -195,6 +196,9 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.farm = FarmRunner(Adb(), self.catalog, self.state)
|
||||
self.busy, self.monitoring = False, False
|
||||
self.active_job = None
|
||||
self.presentation_active = True
|
||||
self.latest_render = None
|
||||
self.prepared_views = None
|
||||
self.next_poll = self.next_farm = 0
|
||||
self.client_pending = None
|
||||
self.password_login_result = None
|
||||
@@ -239,6 +243,9 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.eggs.rules_changed.connect(self.egg_rules_changed)
|
||||
self.monsters = table(["魔物ID", "名称", "星", "等级 / 当前上限", "资质 攻/防/血/敏", "位置", "锁定", "管理范围",
|
||||
"喂养目标", "喂养优先级", "突破等级", "参考攻击", "参考防御", "参考生命", "参考敏捷", "好感", "喜欢的物品"])
|
||||
self.monsters.horizontalHeader().setSectionResizeMode(W.QHeaderView.ResizeMode.Interactive)
|
||||
for column, width in enumerate((115, 140, 45, 120, 150, 140, 80, 130, 90, 110, 85, 90, 90, 90, 90, 65, 220)):
|
||||
self.monsters.setColumnWidth(column, width)
|
||||
self.rooms_table = table(["牧场ID", "名称", "类型", "当前魔物", "容量", "空位"])
|
||||
self.slot_page = W.QWidget()
|
||||
slot_layout = W.QVBoxLayout(self.slot_page)
|
||||
@@ -342,6 +349,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.refresh_capture_profiles()
|
||||
self.render_catalog()
|
||||
self.install_refresh_menus()
|
||||
self.tabs.currentChanged.connect(self.render_current_page)
|
||||
self.reload_saved_sessions()
|
||||
self.timer = C.QTimer(self)
|
||||
self.timer.timeout.connect(self.schedule)
|
||||
@@ -1205,11 +1213,22 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
return
|
||||
self.busy = True
|
||||
self.update_monster_actions()
|
||||
job = Job(kind, function)
|
||||
catalog, engine = self.catalog, self.engine
|
||||
def background():
|
||||
started = time.perf_counter()
|
||||
value = function()
|
||||
if kind in ("poll", "monster_lock", "manual_monsters", "expansion", "growth_sync", "daily_claim", "connected"):
|
||||
snapshot = value[1] if kind == "connected" else value[0]
|
||||
managed = set() if kind == "connected" else set(engine.planner.managed)
|
||||
preparing = time.perf_counter()
|
||||
views = prepare_views(catalog, snapshot, managed)
|
||||
return Presented(value, views, (time.perf_counter() - preparing) * 1000, (time.perf_counter() - started) * 1000)
|
||||
return value
|
||||
job = Job(kind, background)
|
||||
self.active_job = job
|
||||
job.signals.result.connect(self.result)
|
||||
job.signals.error.connect(self.error)
|
||||
job.signals.done.connect(self.job_done)
|
||||
job.signals.result.connect(self.result, C.Qt.ConnectionType.QueuedConnection)
|
||||
job.signals.error.connect(self.error, C.Qt.ConnectionType.QueuedConnection)
|
||||
job.signals.done.connect(self.job_done, C.Qt.ConnectionType.QueuedConnection)
|
||||
self.pool.start(job)
|
||||
|
||||
@C.Slot()
|
||||
@@ -1226,11 +1245,23 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.pending_execute = False
|
||||
C.QTimer.singleShot(0, lambda: self.refresh(automated=True))
|
||||
|
||||
@C.Slot(str, object)
|
||||
def result(self, kind, value):
|
||||
metrics = None
|
||||
if isinstance(value, Presented):
|
||||
self.prepared_views = value.views
|
||||
metrics = value
|
||||
value = value.value
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
self.apply_result(kind, value)
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
self.error("显示数据时出错:" + str(error))
|
||||
if metrics and not self.engine.demo:
|
||||
self.trace.emit("info", "刷新耗时", scope="local", task=kind,
|
||||
worker_total_ms=round(metrics.worker_ms, 1), data_prepare_ms=round(metrics.prepare_ms, 1),
|
||||
ui_callback_ms=round((time.perf_counter() - started) * 1000, 1),
|
||||
note="worker总耗时包含网络;大列表在后续短批次更新")
|
||||
|
||||
def apply_result(self, kind, value):
|
||||
if kind in ("poll", "monster_lock", "manual_monsters", "expansion", "growth_sync", "daily_claim"):
|
||||
@@ -1238,6 +1269,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.render(snapshot, plans)
|
||||
self.report(message)
|
||||
self.reload_saved_sessions()
|
||||
if kind == "poll" and self.engine.last_executed and self.execute.isChecked() and self.monitoring:
|
||||
self.next_poll = time.monotonic() + .15
|
||||
if "策略暂不可用" in message:
|
||||
self.execute.setChecked(False)
|
||||
elif kind == "heartbeat":
|
||||
@@ -1339,6 +1372,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.login_status.setText(f"已获取 {self.server_list.count()} 个官方区服,请选择后点击“进入选中区服”")
|
||||
self.report(f"账号验证成功;官方返回 {self.server_list.count()} 个区服,请选择后进入")
|
||||
|
||||
@C.Slot(str)
|
||||
def error(self, message):
|
||||
last = self.trace.events[-1] if self.trace.events else {}
|
||||
if last.get("kind") != "error" or last.get("message") != self.trace.redact(message):
|
||||
@@ -1362,7 +1396,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
type_id, count = item.split(":")
|
||||
eggs[str(int(type_id))] = max(0, int(count))
|
||||
return Policy(enabled=self.ranch_enabled.isChecked(), strategy=self.strategy.currentData(), protect_star=self.protect_star.value(), protect_quality=self.protect_quality.currentData(),
|
||||
feed_target=self.target.currentData() or 0, target_level=self.target_level.value(), room_id=self.room.currentData() or 0,
|
||||
feed_target=getattr(self, "restore_target", self.target.currentData() or 0), target_level=self.target_level.value(), room_id=getattr(self, "restore_room", self.room.currentData() or 0),
|
||||
coins_per_exp=self.coin_exp.value(), fill=self.fill.isChecked(), egg_order=self.egg_order.currentData(),
|
||||
reserved_types=reserved, reserved_eggs=eggs, min_gold_per_hour=self.min_gold.value(), min_exp_per_hour=self.min_exp.value(),
|
||||
collect=self.collect.isChecked(), dispatch=self.dispatch.isChecked(), feed=self.feed.isChecked(), hatch_max_star=self.hatch_max_star.currentData(),
|
||||
@@ -1425,6 +1459,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.submit("farm", lambda: self.farm.tick(self.engine.snapshot))
|
||||
|
||||
def render(self, snapshot, plans):
|
||||
self.latest_render = (snapshot, plans)
|
||||
self.engine.snapshot = snapshot
|
||||
master = snapshot.raw["master"]
|
||||
self.summary.setText(f"{master.get('roleName', '')} | 金币 {master.get('money', '?')} | 氪金 {master.get('ke', '?')} | 体力 {master.get('ti', '?')}")
|
||||
decisions = {int((a.payload.get('monsterId') or a.payload.get('monsterIds') or a.payload.get('foods') or [0])[0]): a.description for a in plans if a.kind in ('sell', 'feed')}
|
||||
@@ -1450,15 +1486,98 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
rows.append([position + 1, slot["id"], status, "空位", "", "", "", "", ""])
|
||||
fill_table(self.slots, rows)
|
||||
self.slot_status.setText(f"已开启 {len(opened)} / {total_slots} 个坑位;第4坑为VIP专用({'已激活' if vip else '未激活'})。选择“未开启”的普通坑位后可扩建。")
|
||||
self.render_egg_rules()
|
||||
monster_rows = [[m["id"], m.get("nicName") or self.catalog.monster(m["typeId"]).get("name", "未知"), self.catalog.monster(m["typeId"]).get("star", "?"),
|
||||
f"{m.get('level', 1)} / {self.catalog.max_level(m) or '?'}", self.catalog.quality_text(m), "培育室 · " + snapshot.phase_text(m, self.catalog) if m.get("process") == 2 else f"牧场 {m.get('roomId', 0)}", "系统锁定" if m.get("sysLock") else "是" if m.get("lock") else "否",
|
||||
"本次培育" if int(m["id"]) in self.engine.planner.managed else "已有:不自动处理", "", "", m.get("potentialLevel", "?"),
|
||||
*self.catalog.reference_stats(m), m.get("feel", "?"), self.catalog.likes_text(m["typeId"])] for m in snapshot.raw["monsters"]]
|
||||
fill_table(self.monsters, monster_rows, sorting=False)
|
||||
for row_index, mon in enumerate(snapshot.raw["monsters"]):
|
||||
eggs = snapshot.eggs(self.catalog)
|
||||
incubating = sum(int(slot.get("monsterId") or 0) > 0 for slot in snapshot.raw["stacks"])
|
||||
stamp = time.strftime("%H:%M:%S", time.localtime(snapshot.received_at))
|
||||
self.data_summary.setText(f"{'演示数据' if self.engine.demo else '真实角色数据'} | 培育坑位 {len(snapshot.raw['stacks'])}(使用 {incubating}) | 魔物蛋 {len(eggs)} 类 / {sum(int(egg.get('num') or 0) for egg in eggs)} 枚 | 魔物 {len(snapshot.raw['monsters'])} | 牧场 {len(snapshot.raw['rooms'])} | 更新 {stamp}")
|
||||
fill_table(self.plans, [[a.kind, a.description] for a in plans])
|
||||
self.workflow_next.setText("下一步:" + plans[0].description if plans else "当前等待:" + ";".join(list(dict.fromkeys(self.engine.planner.notes))[:4]) if self.engine.planner.notes else "点击刷新 / 预览查看下一步")
|
||||
self.update_workflow_status()
|
||||
left = snapshot.raw.get("history", {}).get("loopTaskNum", "未知")
|
||||
self.quest_summary.setText(f"今日剩余可接次数:{left};当前委托:{len(self.engine.tasks.current(snapshot))}")
|
||||
if not self.engine.demo:
|
||||
self.reqid.setValue(self.engine.client.session.reqid)
|
||||
self.reqsid.setValue(self.engine.client.session.reqsid)
|
||||
|
||||
if self.presentation_active:
|
||||
self.render_current_page()
|
||||
|
||||
def set_presentation_active(self, active):
|
||||
self.presentation_active = active
|
||||
if not active:
|
||||
for name in ("map_render_timer", "monster_render_timer"):
|
||||
timer = getattr(self, name, None)
|
||||
if timer:
|
||||
timer.stop()
|
||||
if hasattr(self.eggs, "row_batch"):
|
||||
self.eggs.row_batch.stop()
|
||||
elif self.latest_render:
|
||||
self.render_current_page()
|
||||
|
||||
def render_current_page(self, *args):
|
||||
if self.closed or not self.presentation_active or not self.latest_render:
|
||||
return
|
||||
snapshot, plans = self.latest_render
|
||||
page = self.tabs.currentWidget()
|
||||
for name, target in (("map_render_timer", self.map_page), ("monster_render_timer", self.monster_page)):
|
||||
timer = getattr(self, name, None)
|
||||
if timer and page is not target:
|
||||
timer.stop()
|
||||
if page is not self.egg_page and hasattr(self.eggs, "row_batch"):
|
||||
self.eggs.row_batch.stop()
|
||||
try:
|
||||
if page is self.monster_page:
|
||||
self.render_monsters(snapshot)
|
||||
elif page is self.egg_page:
|
||||
self.render_egg_rules()
|
||||
elif page is self.room_page:
|
||||
self.render_rooms(snapshot)
|
||||
elif page is self.quests_table.parentWidget():
|
||||
self.render_quests(snapshot)
|
||||
elif page is self.map_page:
|
||||
self.render_maps()
|
||||
elif page is self.daily_page:
|
||||
self.render_daily()
|
||||
elif page is self.target.parentWidget() or page is self.automation_page:
|
||||
self.refresh_target_choices(snapshot)
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
self.report("页面数据暂不可用:" + str(error))
|
||||
|
||||
def render_monsters(self, snapshot):
|
||||
views = self.prepared_views
|
||||
managed = self.engine.planner.managed
|
||||
if views and views.snapshot is snapshot and views.monster_source == repr(snapshot.raw["monsters"]) and views.managed == managed:
|
||||
rows = views.monsters
|
||||
else:
|
||||
rows = monster_rows(self.catalog, snapshot, managed)
|
||||
signature = (rows, dict(self.feed_targets))
|
||||
if getattr(self, "monster_render_signature", None) == signature:
|
||||
return
|
||||
if not hasattr(self, "monster_render_timer"):
|
||||
self.monster_render_timer = RowBatch(self)
|
||||
self.monsters.setSortingEnabled(False)
|
||||
self.monsters.setRowCount(len(rows))
|
||||
def apply(entry):
|
||||
row_index, mon, values = entry
|
||||
for column, value in enumerate(values):
|
||||
item = self.monsters.item(row_index, column)
|
||||
if item is None:
|
||||
item = W.QTableWidgetItem()
|
||||
self.monsters.setItem(row_index, column, item)
|
||||
if item.data(C.Qt.ItemDataRole.DisplayRole) != value:
|
||||
item.setData(C.Qt.ItemDataRole.DisplayRole, value)
|
||||
mid = str(mon["id"])
|
||||
existing = self.monsters.cellWidget(row_index, 8)
|
||||
if existing and existing.property("monster_id") == mid:
|
||||
priority = self.monsters.cellWidget(row_index, 9)
|
||||
blockers = [C.QSignalBlocker(existing), C.QSignalBlocker(priority)]
|
||||
existing.setChecked(mid in self.feed_targets)
|
||||
existing.setEnabled(mon.get("process") == 3)
|
||||
if not priority.hasFocus():
|
||||
priority.setValue(self.feed_targets.get(mid, 100))
|
||||
return
|
||||
check, priority = W.QCheckBox(), IntegerInput()
|
||||
check.setProperty("monster_id", mid)
|
||||
priority.setRange(1, 999)
|
||||
priority.setValue(self.feed_targets.get(mid, 100))
|
||||
check.setChecked(mid in self.feed_targets)
|
||||
@@ -1477,8 +1596,23 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
priority.valueChanged.connect(changed)
|
||||
self.monsters.setCellWidget(row_index, 8, check)
|
||||
self.monsters.setCellWidget(row_index, 9, priority)
|
||||
self.monsters.item(row_index, 16).setToolTip(self.catalog.likes_text(mon["typeId"]))
|
||||
self.monsters.setSortingEnabled(True)
|
||||
self.monsters.item(row_index, 16).setToolTip(str(values[16]))
|
||||
def finish():
|
||||
self.monster_render_signature = copy.deepcopy(signature)
|
||||
self.monsters.setSortingEnabled(True)
|
||||
self.monster_render_timer.start(((i, mon, values) for i, (mon, values) in enumerate(zip(snapshot.raw["monsters"], rows))), apply, finish)
|
||||
|
||||
def refresh_target_choices(self, snapshot):
|
||||
self.update_combo(self.target, [("未设置:不自动喂养", 0)] + [(f"{self.catalog.monster(m['typeId']).get('name')} Lv.{m.get('level', 1)}/{self.catalog.max_level(m) or '?'} #{m['id']}", int(m["id"])) for m in snapshot.raw["monsters"] if m.get("process") == 3])
|
||||
self.update_combo(self.room, [("自动选择有空位的牧场", 0)] + [(f"牧场 {r['id']}", int(r["id"])) for r in snapshot.raw["rooms"]])
|
||||
if hasattr(self, "restore_target"):
|
||||
self.target.setCurrentIndex(max(0, self.target.findData(self.restore_target)))
|
||||
self.room.setCurrentIndex(max(0, self.room.findData(self.restore_room)))
|
||||
del self.restore_target
|
||||
del self.restore_room
|
||||
self.update_target_status()
|
||||
|
||||
def render_rooms(self, snapshot):
|
||||
rooms = []
|
||||
for room in snapshot.raw["rooms"]:
|
||||
info = self.catalog.data["room_info"].get(str(room.get("typeId")), {})
|
||||
@@ -1487,39 +1621,20 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
rooms.append([room["id"], room.get("name") or info.get("name") or "牧场", room.get("typeId", ""), used,
|
||||
capacity if capacity is not None else "未知", max(0, int(capacity) - used) if capacity is not None else "未知"])
|
||||
fill_table(self.rooms_table, rooms)
|
||||
eggs = snapshot.eggs(self.catalog)
|
||||
incubating = sum(int(slot.get("monsterId") or 0) > 0 for slot in snapshot.raw["stacks"])
|
||||
stamp = time.strftime("%H:%M:%S", time.localtime(snapshot.received_at))
|
||||
self.data_summary.setText(f"{'演示数据' if self.engine.demo else '真实角色数据'} | 培育坑位 {len(snapshot.raw['stacks'])}(使用 {incubating}) | 魔物蛋 {len(eggs)} 类 / {sum(int(egg.get('num') or 0) for egg in eggs)} 枚 | 魔物 {len(snapshot.raw['monsters'])} | 牧场 {len(rooms)} | 更新 {stamp}")
|
||||
fill_table(self.plans, [[a.kind, a.description] for a in plans])
|
||||
self.workflow_next.setText("下一步:" + plans[0].description if plans else "当前等待:" + ";".join(list(dict.fromkeys(self.engine.planner.notes))[:4]) if self.engine.planner.notes else "点击刷新 / 预览查看下一步")
|
||||
self.update_workflow_status()
|
||||
try:
|
||||
quest_policy = self.read_quest_policy()
|
||||
quest_rows = self.engine.tasks.rows(snapshot, quest_policy, self.read_policy())
|
||||
fill_table(self.quests_table, [[key, name, status,
|
||||
self.catalog.data["task_info"][key].get("reward", {}).get("money", 0),
|
||||
self.catalog.data["task_info"][key].get("reward", {}).get("ke", 0), text] for key, name, status, text, _ in quest_rows])
|
||||
self.render_maps()
|
||||
self.render_daily()
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
self.report("基础数据已显示;委托或地图暂不可用:" + str(error))
|
||||
left = snapshot.raw.get("history", {}).get("loopTaskNum", "未知")
|
||||
self.quest_summary.setText(f"今日剩余可接次数:{left};当前委托:{len(self.engine.tasks.current(snapshot))}")
|
||||
self.update_combo(self.target, [("未设置:不自动喂养", 0)] + [(f"{self.catalog.monster(m['typeId']).get('name')} Lv.{m.get('level', 1)}/{self.catalog.max_level(m) or '?'} #{m['id']}", int(m["id"])) for m in snapshot.raw["monsters"] if m.get("process") == 3])
|
||||
self.update_combo(self.room, [("自动选择有空位的牧场", 0)] + [(f"牧场 {r['id']}", int(r["id"])) for r in snapshot.raw["rooms"]])
|
||||
if hasattr(self, "restore_target") and not self.engine.demo:
|
||||
self.target.setCurrentIndex(max(0, self.target.findData(self.restore_target)))
|
||||
self.room.setCurrentIndex(max(0, self.room.findData(self.restore_room)))
|
||||
del self.restore_target
|
||||
self.update_target_status()
|
||||
if not self.engine.demo:
|
||||
self.reqid.setValue(self.engine.client.session.reqid)
|
||||
self.reqsid.setValue(self.engine.client.session.reqsid)
|
||||
|
||||
def render_quests(self, snapshot):
|
||||
quest_policy = self.read_quest_policy()
|
||||
quest_rows = self.engine.tasks.rows(snapshot, quest_policy, self.read_policy())
|
||||
fill_table(self.quests_table, [[key, name, status,
|
||||
self.catalog.data["task_info"][key].get("reward", {}).get("money", 0),
|
||||
self.catalog.data["task_info"][key].get("reward", {}).get("ke", 0), text] for key, name, status, text, _ in quest_rows])
|
||||
|
||||
@staticmethod
|
||||
def update_combo(widget, rows):
|
||||
if [(widget.itemText(i), widget.itemData(i)) for i in range(widget.count())] == rows:
|
||||
return
|
||||
previous = widget.currentData()
|
||||
blocker = C.QSignalBlocker(widget)
|
||||
widget.clear()
|
||||
for text, data in rows:
|
||||
widget.addItem(text, data)
|
||||
@@ -1831,6 +1946,12 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.timer.stop()
|
||||
if hasattr(self, "activity_save_timer"):
|
||||
self.activity_save_timer.stop()
|
||||
if hasattr(self.eggs, "row_batch"):
|
||||
self.eggs.row_batch.stop()
|
||||
for name in ("map_render_timer", "monster_render_timer"):
|
||||
timer = getattr(self, name, None)
|
||||
if timer:
|
||||
timer.stop()
|
||||
self.pending_refresh = None
|
||||
self.engine.auto = False
|
||||
self.monitoring = False
|
||||
|
||||
@@ -79,7 +79,8 @@ def manual_monster_actions(catalog, snapshot, kind, monster_ids, target_id=0):
|
||||
raise ValueError("目标已达到当前突破上限,或上限未知,不能喂养")
|
||||
if any(mon.get("process") != 3 for mon in monsters):
|
||||
raise ValueError("喂养素材需先从培育室收取到牧场")
|
||||
return [Action("feed", f"将 {len(ids)} 只素材喂给 #{target_id}", "monsterService/monsterIntensify", {"targetId": int(target_id), "foods": ids})]
|
||||
foods = "、".join(catalog.monster_label(mon) for mon in monsters)
|
||||
return [Action("feed", f"喂养 {catalog.monster_label(target)} ← {len(ids)} 只素材:{foods}", "monsterService/monsterIntensify", {"targetId": int(target_id), "foods": ids})]
|
||||
if kind != "sell":
|
||||
raise ValueError("未知魔物操作")
|
||||
return [Action("sell", f"派遣 {len(ids)} 只魔物", "monsterService/monsterSell", {"monsterIds": ids})]
|
||||
|
||||
@@ -88,6 +88,19 @@ class Catalog:
|
||||
row = self.monster(mon.get("typeId"))
|
||||
return int(row.get("sell_exp", 0)) + int(float(mon.get("exp", 0)) * self.data["game_setting"].get("monExpScale", 0.2))
|
||||
|
||||
def monster_label(self, mon):
|
||||
species = self.monster(mon.get("typeId")).get("name", "未知魔物")
|
||||
nickname = mon.get("nicName")
|
||||
return f"#{mon['id']} {species}" + (f"({nickname})" if nickname and nickname != species else "")
|
||||
|
||||
def feed_remaining(self, mon, stop_level):
|
||||
table = self.data.get("monster_level", {})
|
||||
limit = table.get(str(stop_level))
|
||||
current = table.get(str(mon.get("level", 1)))
|
||||
if limit is None or current is None:
|
||||
return None
|
||||
return max(0, int(limit) - max(int(mon.get("exp") or 0), int(current)))
|
||||
|
||||
def max_level(self, mon):
|
||||
info = self.data.get("potential_info", {})
|
||||
potential = mon.get("potentialLevel")
|
||||
@@ -333,6 +346,9 @@ class Planner:
|
||||
level = int(target.get("level", 1))
|
||||
reason = f"目标 #{mid} Lv.{level};当前突破上限 {cap};喂养停止等级 {limit}"
|
||||
if level < limit:
|
||||
if self.catalog.feed_remaining(target, limit) == 0:
|
||||
reason = f"目标 #{mid} 经验已达到停止等级,等待服务器同步"
|
||||
continue
|
||||
return target, reason
|
||||
return None, reason
|
||||
|
||||
@@ -434,6 +450,14 @@ class Planner:
|
||||
self.notes.append("请到“背包魔物蛋”勾选要孵化的蛋,并设置优先级和孵出后的去向")
|
||||
return []
|
||||
actions = []
|
||||
free_rooms = {}
|
||||
for room in snapshot.raw["rooms"]:
|
||||
rid = int(room["id"])
|
||||
if policy.room_id and rid != policy.room_id:
|
||||
continue
|
||||
capacity = int(self.catalog.data["room_info"].get(str(room.get("typeId")), {}).get("maxNum") or 0)
|
||||
used = sum(m.get("process") == 3 and int(m.get("roomId") or 0) == rid for m in snapshot.raw["monsters"])
|
||||
free_rooms[rid] = max(0, capacity - used)
|
||||
for mon in snapshot.raw["monsters"]:
|
||||
mid = int(mon["id"])
|
||||
if mid not in self.managed or mon.get("process") not in (2, 3):
|
||||
@@ -462,8 +486,9 @@ class Planner:
|
||||
# NetMonster.sellMonsters, whose active parameter is plural.
|
||||
actions.append(Action("sell", f"派遣 {name} #{mid}", "monsterService/monsterSell", {"monsterIds": [mid]}))
|
||||
elif mon.get("process") == 2 and policy.collect:
|
||||
room = snapshot.room_available(self.catalog, policy.room_id)
|
||||
room = next((rid for rid, free in free_rooms.items() if free > 0), None)
|
||||
if room is not None:
|
||||
free_rooms[room] -= 1
|
||||
actions.append(Action("collect", f"收取 {name} #{mid} → 牧场 {room}", "stackService/stackTransferMonster", {"datas": [{"monsterId": [mid], "roomId": room}]}))
|
||||
else:
|
||||
self.notes.append(f"{name} 等待收取:牧场没有空位")
|
||||
@@ -476,7 +501,7 @@ class Planner:
|
||||
elif disposition == "keep":
|
||||
self.notes.append(f"{name} 已保留:{reason}")
|
||||
if actions:
|
||||
return actions
|
||||
return self.batch_actions(actions, snapshot, policy)
|
||||
vip_info = snapshot.raw.get("activityHistory", {}).get("vipInfo") or {}
|
||||
vip = seconds(vip_info.get("vipTime")) > snapshot.now
|
||||
empty = [s for s in snapshot.raw["stacks"] if policy.fill and int(s.get("monsterId") or 0) <= 0 and (int(s.get("position", -1)) != 3 or vip)]
|
||||
@@ -502,3 +527,40 @@ class Planner:
|
||||
if not actions and not self.notes:
|
||||
self.notes.append("等待孵化 / 成长,成熟后按保护条件处理")
|
||||
return actions or self.purchase(snapshot, policy, daily_left)
|
||||
|
||||
def batch_actions(self, actions, snapshot, policy):
|
||||
monsters = snapshot.monsters
|
||||
collects = [a for a in actions if a.kind == "collect"]
|
||||
if collects:
|
||||
rooms = {}
|
||||
for action in collects:
|
||||
for data in action.payload["datas"]:
|
||||
rooms.setdefault(data["roomId"], []).extend(data["monsterId"])
|
||||
ids = [mid for mids in rooms.values() for mid in mids]
|
||||
description = "批量收取 " + "、".join(self.catalog.monster_label(monsters[mid]) for mid in ids)
|
||||
merged = Action("collect", description, "stackService/stackTransferMonster", {"datas": [{"monsterId": mids, "roomId": room} for room, mids in rooms.items()]})
|
||||
return [merged] + [a for a in actions if a.kind != "collect"]
|
||||
feeds = [a for a in actions if a.kind == "feed"]
|
||||
if not feeds:
|
||||
return actions
|
||||
target_id = feeds[0].payload["targetId"]
|
||||
target = monsters[target_id]
|
||||
stop_level = min(policy.target_level, self.catalog.max_level(target))
|
||||
need = self.catalog.feed_remaining(target, stop_level)
|
||||
ids, experience = [], 0
|
||||
for action in feeds:
|
||||
if action.payload["targetId"] != target_id:
|
||||
continue
|
||||
for mid in action.payload["foods"]:
|
||||
if mid in ids:
|
||||
continue
|
||||
ids.append(mid)
|
||||
experience += self.catalog.feed_exp(monsters[mid])
|
||||
if need is None or experience >= need:
|
||||
break
|
||||
if need is None or experience >= need:
|
||||
break
|
||||
label = self.catalog.monster_label(target)
|
||||
foods = "、".join(self.catalog.monster_label(monsters[mid]) for mid in ids)
|
||||
merged = Action("feed", f"喂养 {label} ← {len(ids)} 只素材:{foods}(经验 {experience})", "monsterService/monsterIntensify", {"targetId": target_id, "foods": ids})
|
||||
return [merged] + [a for a in actions if a.kind != "feed"]
|
||||
|
||||
@@ -1,5 +1,42 @@
|
||||
"""Native number inputs and scrollbars with usable click targets."""
|
||||
from PySide6 import QtCore as C, QtGui as G, QtWidgets as W
|
||||
import time
|
||||
|
||||
|
||||
class RowBatch(C.QObject):
|
||||
"""Create Qt rows in short event-loop slices, keeping input responsive."""
|
||||
def __init__(self, parent):
|
||||
super().__init__(parent)
|
||||
self.timer = C.QTimer(self)
|
||||
self.timer.setInterval(1)
|
||||
self.timer.timeout.connect(self.tick)
|
||||
self.running = False
|
||||
|
||||
def start(self, rows, apply, finished):
|
||||
self.stop()
|
||||
self.rows, self.apply, self.finished = iter(rows), apply, finished
|
||||
self.running = True
|
||||
self.tick()
|
||||
if self.running:
|
||||
self.timer.start()
|
||||
|
||||
def stop(self):
|
||||
self.timer.stop()
|
||||
self.running = False
|
||||
|
||||
@C.Slot()
|
||||
def tick(self):
|
||||
until = time.perf_counter() + .008
|
||||
count = 0
|
||||
while self.running and count < 24 and time.perf_counter() < until:
|
||||
try:
|
||||
row = next(self.rows)
|
||||
except StopIteration:
|
||||
self.stop()
|
||||
self.finished()
|
||||
return
|
||||
self.apply(row)
|
||||
count += 1
|
||||
|
||||
|
||||
class IntegerInput(W.QLineEdit):
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Pure presentation calculations: run in account workers, never touch Qt."""
|
||||
from dataclasses import dataclass
|
||||
from .maps import stages
|
||||
|
||||
|
||||
def monster_rows(catalog, snapshot, managed):
|
||||
return [[m["id"], m.get("nicName") or catalog.monster(m["typeId"]).get("name", "未知"), catalog.monster(m["typeId"]).get("star", "?"),
|
||||
f"{m.get('level', 1)} / {catalog.max_level(m) or '?'}", catalog.quality_text(m),
|
||||
"培育室 · " + snapshot.phase_text(m, catalog) if m.get("process") == 2 else f"牧场 {m.get('roomId', 0)}",
|
||||
"系统锁定" if m.get("sysLock") else "是" if m.get("lock") else "否",
|
||||
"本次培育" if int(m["id"]) in managed else "已有:不自动处理", "", "", m.get("potentialLevel", "?"),
|
||||
*catalog.reference_stats(m), m.get("feel", "?"), catalog.likes_text(m["typeId"])] for m in snapshot.raw["monsters"]]
|
||||
|
||||
|
||||
def map_source(snapshot):
|
||||
return repr((snapshot.raw.get("history"), snapshot.raw["master"].get("level")))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Views:
|
||||
snapshot: object
|
||||
monster_source: str
|
||||
managed: set
|
||||
monsters: list
|
||||
map_source: str
|
||||
maps: list
|
||||
|
||||
|
||||
@dataclass
|
||||
class Presented:
|
||||
value: object
|
||||
views: Views
|
||||
prepare_ms: float = 0
|
||||
worker_ms: float = 0
|
||||
|
||||
|
||||
def prepare_views(catalog, snapshot, managed):
|
||||
return Views(snapshot, repr(snapshot.raw["monsters"]), set(managed), monster_rows(catalog, snapshot, managed),
|
||||
map_source(snapshot), stages(catalog, snapshot))
|
||||
@@ -37,14 +37,15 @@ class SweepRunner:
|
||||
def team_ids(self, snapshot, policy):
|
||||
team = next((t for t in snapshot.raw.get("teams", []) if t.get("teamName") == policy.team and t.get("teamType") == "battleTeam"), {})
|
||||
ids = [int(mid) for mid in team.get("monsters", []) if mid and int(mid) > 0]
|
||||
return [mid for mid in ids if mid in snapshot.monsters]
|
||||
monsters = snapshot.monsters
|
||||
return [mid for mid in ids if mid in monsters]
|
||||
|
||||
def reason(self, snapshot, stage, policy):
|
||||
def reason(self, snapshot, stage, policy, *, team_ids=None):
|
||||
if self.state.get("pending"):
|
||||
return "有未完成的扫荡,请先在游戏内检查"
|
||||
if not stage.sweep:
|
||||
return stage.reason
|
||||
if not self.team_ids(snapshot, policy):
|
||||
if not (self.team_ids(snapshot, policy) if team_ids is None else team_ids):
|
||||
return "所选战队无有效魔物"
|
||||
positions = self.catalog.data.get("stage_task_positions", {})
|
||||
for task in snapshot.raw.get("currentTasks", []):
|
||||
|
||||
@@ -169,6 +169,9 @@ class AccountGuiTests(unittest.TestCase):
|
||||
self.connect(second, "account-b", 2, 202, calls)
|
||||
self.assertNotEqual(first.state, second.state)
|
||||
self.assertIsNot(first.pool, second.pool)
|
||||
hub.tabs.setCurrentWidget(first)
|
||||
for page in (first.egg_page, first.monster_page, first.room_page):
|
||||
first.tabs.setCurrentWidget(page)
|
||||
self.assertEqual([first.slots.rowCount(), first.eggs.rowCount(), first.monsters.rowCount(), first.rooms_table.rowCount()], [11, 4, 4, 1])
|
||||
self.assertEqual(first.saved_sessions.count(), 1)
|
||||
first.start_monitor.setChecked(True)
|
||||
|
||||
@@ -396,9 +396,11 @@ class AutomationGuiTests(unittest.TestCase):
|
||||
snapshot.raw["currentTasks"] = [{"id": 88, "typeId": key, "curStep": 1}]
|
||||
snapshot.monsters[900].update(level=20, potentialLevel=2)
|
||||
window.render(snapshot, [])
|
||||
window.refresh_target_choices(snapshot)
|
||||
window.target.setCurrentIndex(window.target.findData(900))
|
||||
self.assertIn("上限 20", window.target_status.text())
|
||||
reward = window.catalog.data["task_info"][key]["reward"]
|
||||
window.tabs.setCurrentWidget(window.quests_table.parentWidget())
|
||||
self.assertEqual(int(window.quests_table.item(0, 4).text()), reward["ke"])
|
||||
self.assertIn("氪金", window.summary.text())
|
||||
finally:
|
||||
@@ -415,6 +417,7 @@ class AutomationGuiTests(unittest.TestCase):
|
||||
window.start_monitor.setChecked(True)
|
||||
before = len(window.engine.snapshot.raw["monsters"])
|
||||
def select(mid):
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
row = next(i for i in range(window.monsters.rowCount()) if int(window.monsters.item(i, 0).text()) == mid)
|
||||
window.monsters.selectRow(row)
|
||||
select(101)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import copy
|
||||
import unittest
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.model import Catalog, Planner, Policy
|
||||
|
||||
|
||||
class BatchFeedingTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.catalog = Catalog()
|
||||
self.snapshot = demo_snapshot(self.catalog)
|
||||
template = self.snapshot.raw["monsters"][0]
|
||||
foods = [copy.deepcopy(template) | {"id": 101 + i, "process": 3, "mode": 2, "roomId": 1} for i in range(4)]
|
||||
self.snapshot.raw["monsters"] = foods + [self.snapshot.monsters[900]]
|
||||
self.snapshot.raw["stacks"] = []
|
||||
self.planner = Planner(self.catalog)
|
||||
self.planner.managed.update(m["id"] for m in foods)
|
||||
self.policy = Policy(strategy="experience", protect_star=6, protect_quality=5, feed_target=900, fill=False)
|
||||
|
||||
def test_all_eligible_foods_use_one_request_and_log_names_and_ids(self):
|
||||
actions = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(len(actions), 1)
|
||||
self.assertEqual(actions[0].payload, {"targetId": 900, "foods": [101, 102, 103, 104]})
|
||||
for mid in (900, 101, 102, 103, 104):
|
||||
self.assertIn(self.catalog.monster_label(self.snapshot.monsters[mid]), actions[0].description)
|
||||
|
||||
def test_locked_team_and_unmanaged_foods_are_excluded(self):
|
||||
self.snapshot.monsters[102]["lock"] = 1
|
||||
self.snapshot.raw["teams"][0]["monsters"].append(103)
|
||||
self.planner.managed.discard(104)
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["foods"], [101])
|
||||
|
||||
def test_remaining_experience_bounds_batch_at_current_breakthrough_cap(self):
|
||||
target = self.snapshot.monsters[900]
|
||||
target.update(level=19, potentialLevel=2, exp=self.catalog.data["monster_level"]["20"] - 1)
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["foods"], [101])
|
||||
target["level"] = 20
|
||||
self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(self.snapshot, self.policy)))
|
||||
|
||||
def test_full_first_target_advances_to_next_priority(self):
|
||||
first = self.snapshot.monsters[900]
|
||||
first.update(level=20, potentialLevel=2)
|
||||
self.snapshot.raw["monsters"].append(copy.deepcopy(first) | {"id": 901, "level": 1, "exp": 0})
|
||||
self.policy.feed_targets = {"900": 1, "901": 2}
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 901)
|
||||
|
||||
def test_collect_then_feed_all_in_two_batches(self):
|
||||
for mid in (101, 102, 103, 104):
|
||||
self.snapshot.monsters[mid].update(process=2, roomId=None)
|
||||
self.snapshot.raw["stacks"] = [{"id": i + 1, "position": i, "monsterId": 101 + i} for i in range(4)]
|
||||
engine = Engine(self.catalog)
|
||||
engine.snapshot, engine.policy, engine.auto = self.snapshot, self.policy, True
|
||||
_, actions, _ = engine.poll()
|
||||
self.assertTrue(all(self.snapshot.monsters[mid]["process"] == 3 for mid in (101, 102, 103, 104)))
|
||||
self.assertEqual(actions[0].payload["foods"], [101, 102, 103, 104])
|
||||
engine.poll()
|
||||
self.assertEqual(set(self.snapshot.monsters), {900})
|
||||
|
||||
def test_collection_reserves_room_space_for_entire_batch(self):
|
||||
for mid in (101, 102, 103, 104):
|
||||
self.snapshot.monsters[mid].update(process=2, roomId=None)
|
||||
room_type = str(self.snapshot.raw["rooms"][0]["typeId"])
|
||||
self.catalog.data["room_info"][room_type]["maxNum"] = 3
|
||||
actions = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(sum(len(d["monsterId"]) for d in actions[0].payload["datas"]), 2)
|
||||
@@ -73,8 +73,8 @@ class CoreTests(unittest.TestCase):
|
||||
mon.update(process=3, roomId=1)
|
||||
snapshot.raw["stacks"][0]["monsterId"] = 0
|
||||
plans = planner.plan(snapshot, policy)
|
||||
self.assertEqual(plans[0].kind, "feed")
|
||||
self.assertEqual(plans[0].payload, {"targetId": 900, "foods": [mon["id"]]})
|
||||
feeding = next(a for a in plans if a.kind == "feed")
|
||||
self.assertEqual(feeding.payload, {"targetId": 900, "foods": [mon["id"]]})
|
||||
snapshot.monsters[900]["level"] = policy.target_level
|
||||
self.assertFalse(any(a.kind == "feed" for a in planner.plan(snapshot, policy)))
|
||||
|
||||
|
||||
@@ -199,6 +199,7 @@ class GrowthGuiTests(unittest.TestCase):
|
||||
window.engine.policy = window.read_policy()
|
||||
window.engine.snapshot = client.snapshot()
|
||||
window.render(window.engine.snapshot, window.engine.plans())
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
row = next(i for i in range(window.slots.rowCount()) if window.slots.item(i, 1).text() == "1")
|
||||
self.assertIn("待同步", window.slots.item(row, 5).text())
|
||||
self.assertIn("待成熟", window.slots.item(row, 7).text())
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import copy
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
from PySide6 import QtCore as C, QtWidgets as W
|
||||
from PySide6.QtTest import QTest
|
||||
|
||||
from ranch_assistant.gui import Window
|
||||
from ranch_assistant.engine import demo_snapshot
|
||||
from ranch_assistant.engine import Engine
|
||||
from ranch_assistant.api import Client, Session, encode
|
||||
from ranch_assistant.tests.test_activities import scenario
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
|
||||
|
||||
class ResponsivenessTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.app = W.QApplication.instance() or W.QApplication([])
|
||||
|
||||
def wait(self, window):
|
||||
for _ in range(400):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
if not window.busy:
|
||||
return
|
||||
self.fail("Background operation did not complete")
|
||||
|
||||
def test_hidden_maps_are_not_rebuilt_on_poll(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.tabs.setCurrentIndex(0)
|
||||
with patch.object(window, "render_maps") as maps:
|
||||
window.render(window.engine.snapshot, [])
|
||||
maps.assert_not_called()
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_hidden_account_does_not_rebuild_large_monster_table(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.presentation_active = False
|
||||
snapshot = demo_snapshot(window.catalog)
|
||||
template = snapshot.raw["monsters"][-1]
|
||||
snapshot.raw["monsters"] = [copy.deepcopy(template) | {"id": 1000 + i} for i in range(500)]
|
||||
with patch.object(window.monsters, "setCellWidget") as cells:
|
||||
window.engine.snapshot = snapshot
|
||||
window.render(snapshot, [])
|
||||
self.assertEqual(cells.call_count, 0)
|
||||
self.assertIn("魔物 500", window.data_summary.text())
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_unchanged_maps_reuse_controls_and_keep_edits(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
catalog, snapshot = scenario()
|
||||
window.catalog = catalog
|
||||
window.engine.catalog = catalog
|
||||
window.engine.snapshot = snapshot
|
||||
window.render_maps()
|
||||
original = window.maps_tree.topLevelItem(0).child(0)
|
||||
edit = window.maps_tree.itemWidget(original, 8)
|
||||
edit.setText("12")
|
||||
window.render_maps()
|
||||
self.assertIs(window.maps_tree.topLevelItem(0).child(0), original)
|
||||
self.assertIs(window.maps_tree.itemWidget(original, 8), edit)
|
||||
self.assertEqual(edit.text(), "12")
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_hidden_debug_does_not_format_large_json(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
event = {"time": "2026-11-07T23:30:00+08:00", "kind": "response", "operation": "test", "body": {"rows": ["value"] * 1000}}
|
||||
with patch.object(window.debug_window, "selected_text", wraps=window.debug_window.selected_text) as formatting:
|
||||
window.on_network_event(event)
|
||||
formatting.assert_not_called()
|
||||
self.assertEqual(window.debug_window.rows.rowCount(), 1)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_slow_network_jobs_leave_ui_timer_responsive_and_accounts_parallel(self):
|
||||
with workspace_temp() as folder:
|
||||
windows = [Window(folder / str(i)) for i in range(2)]
|
||||
release = threading.Event()
|
||||
started = [threading.Event(), threading.Event()]
|
||||
beats, worker_threads = [], []
|
||||
timer = C.QTimer()
|
||||
timer.setInterval(5)
|
||||
timer.timeout.connect(lambda: beats.append(True))
|
||||
try:
|
||||
for window in windows:
|
||||
window.timer.stop()
|
||||
self.wait(window)
|
||||
def work(index):
|
||||
worker_threads.append(threading.get_ident())
|
||||
started[index].set()
|
||||
release.wait(2)
|
||||
return "done"
|
||||
timer.start()
|
||||
for i, window in enumerate(windows):
|
||||
window.submit("test", lambda i=i: work(i))
|
||||
for _ in range(20):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
self.assertTrue(all(event.is_set() for event in started))
|
||||
self.assertGreater(len(beats), 3)
|
||||
self.assertTrue(all(tid != threading.get_ident() for tid in worker_threads))
|
||||
self.assertTrue(all(w.busy for w in windows))
|
||||
finally:
|
||||
release.set()
|
||||
timer.stop()
|
||||
for window in windows:
|
||||
self.wait(window)
|
||||
window.close()
|
||||
|
||||
def test_large_two_account_replies_and_inventory_batches_keep_ui_responsive(self):
|
||||
with workspace_temp() as folder:
|
||||
windows = [Window(folder / str(i)) for i in range(2)]
|
||||
clients, beats = [], []
|
||||
timer = C.QTimer()
|
||||
timer.setInterval(5)
|
||||
timer.timeout.connect(lambda: beats.append(time.perf_counter()))
|
||||
try:
|
||||
for index, window in enumerate(windows):
|
||||
window.timer.stop()
|
||||
self.wait(window)
|
||||
snapshot = demo_snapshot(window.catalog)
|
||||
template = snapshot.raw["monsters"][-1]
|
||||
snapshot.raw["monsters"] = [copy.deepcopy(template) | {"id": 1000 + i} for i in range(80 if index == 0 else 500)]
|
||||
types = [int(k) for k in window.catalog.monsters if window.catalog.total_time(k) > 0][:200]
|
||||
snapshot.raw["items"] = [{"id": 2000 + i, "typeId": key, "num": 20} for i, key in enumerate(types)]
|
||||
client = Client(Session("http://127.0.0.1/test/", "synthetic-token"), trace=window.trace)
|
||||
data = encode(snapshot.raw | {"resCode": 0}, client.session.key)
|
||||
def post(*args, response_data=data, **kwargs):
|
||||
time.sleep(.7) # emulate the user's network latency
|
||||
return SimpleNamespace(status_code=200, content=response_data, headers={})
|
||||
client.http.post = post
|
||||
clients.append(client)
|
||||
window.engine = Engine(window.catalog, client)
|
||||
windows[1].set_presentation_active(False)
|
||||
windows[0].tabs.setCurrentWidget(windows[0].egg_page)
|
||||
windows[0].show()
|
||||
self.app.processEvents()
|
||||
timer.start()
|
||||
for window in windows:
|
||||
window.refresh()
|
||||
for _ in range(800):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
batch = getattr(windows[0].eggs, "row_batch", None)
|
||||
if not any(w.busy for w in windows) and (not batch or not batch.running):
|
||||
break
|
||||
self.assertFalse(any(w.busy for w in windows))
|
||||
self.assertEqual(windows[0].eggs.rowCount(), 200)
|
||||
self.assertEqual(windows[1].monsters.rowCount(), 0)
|
||||
self.assertGreater(len(beats), 10)
|
||||
self.assertLess(max(b - a for a, b in zip(beats, beats[1:])), .25)
|
||||
self.assertTrue(any(e["operation"] == "刷新耗时" for e in windows[0].trace.events))
|
||||
finally:
|
||||
timer.stop()
|
||||
for window in windows:
|
||||
self.wait(window)
|
||||
window.close()
|
||||
@@ -180,6 +180,7 @@ class ManualGuiTests(unittest.TestCase):
|
||||
try:
|
||||
self.wait(window)
|
||||
self.assertEqual(window.tabs.tabText(0), "登录")
|
||||
window.tabs.setCurrentWidget(window.egg_page)
|
||||
key = window.eggs.item(0, 0).data(C.Qt.ItemDataRole.UserRole)
|
||||
window.eggs.cellWidget(0, 3).setChecked(True)
|
||||
window.eggs.cellWidget(0, 4).setValue(1)
|
||||
@@ -192,6 +193,7 @@ class ManualGuiTests(unittest.TestCase):
|
||||
row = next(i for i in range(window.eggs.rowCount()) if window.eggs.item(i, 0).data(C.Qt.ItemDataRole.UserRole) == key)
|
||||
self.assertEqual(window.eggs.item(row, 2).text(), "0")
|
||||
self.assertTrue(window.eggs.cellWidget(row, 3).isChecked())
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
row = next(i for i in range(window.monsters.rowCount()) if window.monsters.item(i, 0).text() == "900")
|
||||
window.monsters.cellWidget(row, 8).setChecked(True)
|
||||
window.monsters.cellWidget(row, 9).setValue(1)
|
||||
@@ -273,6 +275,7 @@ class ManualGuiTests(unittest.TestCase):
|
||||
try:
|
||||
self.wait(window)
|
||||
def select(mid):
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
row = next(i for i in range(window.monsters.rowCount()) if window.monsters.item(i, 0).text() == str(mid))
|
||||
window.monsters.selectRow(row)
|
||||
select(101)
|
||||
|
||||
@@ -14,7 +14,7 @@ apk = next(p for p in root.glob("*.apk") if p.name.endswith("_1.9.68.apk"))
|
||||
tables = {}
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
tables["tjchannel"] = json.loads(archive.read("assets/tjchannel.json")) if "assets/tjchannel.json" in archive.namelist() else {"tjchannel": "unknow"}
|
||||
for name in ("monster_info", "room_info", "game_setting", "stage_info", "stage_sp", "activity_info", "server_info", "task_info", "gacha_machine", "potential_info", "stack_price", "room_price", "item_info"):
|
||||
for name in ("monster_info", "monster_level", "room_info", "game_setting", "stage_info", "stage_sp", "activity_info", "server_info", "task_info", "gacha_machine", "potential_info", "stack_price", "room_price", "item_info"):
|
||||
path = "data/table/" + name + ".json"
|
||||
raw = zlib.decompress(archive.read("assets/codes/" + hashlib.md5(path.encode()).hexdigest()))
|
||||
reader = Reader(raw)
|
||||
|
||||
Reference in New Issue
Block a user