Python# -*- coding: utf-8 -*-
"""
图寻答案地图标注器(中文版 · 傻瓜式)
不用手动复制网址/ID。你只需要做 3 件事:
① 把浏览器登录 Cookie 粘进来(按界面按钮有图文教程)
② 点"开启自动监测"
③ 在浏览器里开始打比赛 → 地图上自动出现彩色大头针(答案位置)
主界面全程不显示经纬度数字, 答案只在地图上以"彩色编号大头针"呈现。
"""
import sys
import os
# 本地依赖目录(沙箱/打包后也能加载 browser_cookie3 / pywin32 / websocket 等)
_ROOT_DIR = os.path.dirname(os.path.abspath(sys.executable if getattr(sys, "frozen", False) else __file__))
for _p in ("deps", os.path.join(_ROOT_DIR, "deps")):
if os.path.isdir(_p) and _p not in sys.path:
sys.path.insert(0, _p)
del _ROOT_DIR, _p
import re
import json
import time
import webbrowser
import threading
import urllib.parse
from datetime import datetime
from typing import Optional, Dict, List, Any, Tuple
from http.server import HTTPServer, BaseHTTPRequestHandler
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import requests
BASE_URL = "https://tuxun.fun"
HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0 Safari/537.36"
),
"Referer": "https://tuxun.fun/",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-CN,zh;q=0.9",
}
MAP_PORT_DEFAULT = 18765
POLL_SECONDS_DEFAULT = 3.0
APP_TITLE_CN = "图寻答案地图标注器"
REFRESH_ACTIVE_EVERY = 1 # 每几次 history 轮询就刷 1 次 ACTIVE 对局答案(默认 1,即每轮都刷)
LIVE_RECENT_WINDOW_MS = 15 * 60 * 1000 # 「最近 15 分钟内创建」默认当成可能进行中
LIVE_CANDIDATES_LIMIT = 5 # 启动时最多取 gmtCreate 最新的 N 条对局去 solo/get 看 status
TRACKED_GAME_TICK_SECONDS = 0.8 # 对「正在跟踪的 ACTIVE 对局,每 0.8 秒刷一次 solo/get(题数增加)
# ======================================================================
# 配置文件(记住 Cookie,下次启动不用再粘)
# ======================================================================
def _settings_path() -> str:
if getattr(sys, "frozen", False):
base = os.path.dirname(sys.executable)
else:
base = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base, ".tuxun_settings.json")
def load_settings() -> Dict[str, Any]:
p = _settings_path()
try:
with open(p, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
def save_settings(obj: Dict[str, Any]) -> None:
p = _settings_path()
try:
with open(p, "w", encoding="utf-8") as f:
json.dump(obj, f, ensure_ascii=False, indent=2)
except Exception:
pass
# ======================================================================
# 接口调用
# ======================================================================
def create_session(cookie: Optional[str] = None) -> requests.Session:
s = requests.Session()
s.headers.update(HEADERS)
s.trust_env = False
raw_session_value = None
raw_session_aliases = set()
if cookie:
cleaned = []
seen_keys = set()
raw = cookie.strip()
try:
for pair in re.split(r"\s*;\s*", raw):
pair = pair.strip()
if not pair or "=" not in pair: continue
k, v = pair.split("=", 1)
k = k.strip(); v = v.strip()
if not k: continue
kl = k.lower()
if kl in ("session",):
if raw_session_value is None:
raw_session_value = v
for alias in ("SESSION", "sessionid"):
if alias not in seen_keys:
cleaned.append(f"{alias}={v}"); seen_keys.add(alias)
raw_session_aliases.add(alias)
elif kl in ("sessionid",):
if raw_session_value is None:
raw_session_value = v
for alias in ("sessionid", "SESSION"):
if alias not in seen_keys:
cleaned.append(f"{alias}={v}"); seen_keys.add(alias)
raw_session_aliases.add(alias)
else:
if k not in seen_keys:
cleaned.append(f"{k}={v}"); seen_keys.add(k)
except Exception:
cleaned = [raw]
normalized = "; ".join(cleaned) if cleaned else raw
s.headers["Cookie"] = normalized
s._user_raw_session = raw_session_value or None
return s
def _get(s: requests.Session, path: str, params: Optional[Dict] = None, timeout: int = 20) -> Optional[Dict]:
try:
r = s.get(f"{BASE_URL}{path}", params=params or {}, timeout=timeout)
return r.json()
except Exception:
return None
def _post(s: requests.Session, path: str, json_body: Optional[Dict] = None, timeout: int = 20) -> Optional[Dict]:
try:
headers = {"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json, text/plain, */*",
"X-Requested-With": "XMLHttpRequest"}
r = s.post(f"{BASE_URL}{path}", json=json_body or {}, headers=headers, timeout=timeout)
return r.json()
except Exception:
return None
def _check_auth_via_profile(s: requests.Session) -> Tuple[bool, str, Dict[str, str]]:
"""返回 (是否通过, 账号信息或错误原因, 从 Set-Cookie 里抓回的 fun_ticket/HMACCOUNT)"""
user_sess = getattr(s, "_user_raw_session", None)
def _extract_set_cookies(r: Optional[requests.Response]
) -> Dict[str, str]:
if not r: return {}
sc = r.headers.get("Set-Cookie", "") or ""
if not sc: return {}
out: Dict[str, str] = {}
for key_name in ("SESSION", "sessionid", "fun_ticket", "HMACCOUNT"):
m = re.search(rf"\b{key_name}\s*=\s*([^;,\s]+)", sc, flags=re.IGNORECASE)
if m:
out[key_name] = m.group(1)
return out
def _new_session_issued(r: Optional[requests.Response]):
new_vals = _extract_set_cookies(r)
new_v = new_vals.get("SESSION") or new_vals.get("sessionid")
if user_sess and new_v and new_v != user_sess:
return True, new_v, new_vals
return False, new_v, new_vals
def _unpack_uid(j: Optional[Dict]):
if not (j and j.get("success")): return None, None, False
d = j.get("data") or {}
if isinstance(d, dict) and "userAO" in d:
d = d.get("userAO") or {}
uid = None
for k in ("userId", "id", "uid"):
v = d.get(k)
if v is not None and str(v) not in ("", "None", "null"):
uid = v; break
nick = ""
for k in ("nickname", "name", "userName"):
v = d.get(k)
if v: nick = v; break
placeholder = False
if (not uid) and (nick and ("注销" in str(nick) or "已注销" in str(nick))):
placeholder = True
return uid, nick, placeholder
uid1, nick1, ph1 = _unpack_uid(None)
uid2 = nick2 = ph2 = uid3 = nick3 = ph3 = None
reissued_any = False
any_new_session_v: Optional[str] = None
grabbed_fields: Dict[str, str] = {}
try:
r1 = s.get(f"{BASE_URL}/api/v0/tuxun/history/listSelfAll",
params={"pageNum": 1, "pageSize": 3}, timeout=20)
j1 = r1.json()
reissued_any, any_new_session_v, extra1 = _new_session_issued(r1)
grabbed_fields.update(extra1)
except Exception:
j1 = None
r1 = None
# ============= 【最高优先级】:listSelfAll / listSelfRating 成功且里面有真实 userId / 历史记录
if j1 is not None:
# j1.data 是列表(用户历史),不能直接传给 _unpack_uid(它期望 dict)
if j1.get("success") and isinstance(j1.get("data"), list):
data1 = j1.get("data") or []
best_uid = None
best_nick = None
for rec in data1:
if not isinstance(rec, dict): continue
u = rec.get("userId")
if u is not None and str(u) not in ("None", "", "null"):
best_uid = u
break
if uid1: best_uid = uid1
# 【立刻判为通过】:只要历史列表非空且能拿到真实 userId → 这个 Cookie 就是有效的
if best_uid:
# 再用 listSelfRating 补一次 nick / rating / province(可选)
j2a, extra_2a = None, {}
try:
r2a = s.get(f"{BASE_URL}/api/v0/tuxun/history/listSelfRating",
params={"pageNum": 1, "pageSize": 2}, timeout=20)
j2a = r2a.json()
extra_2a = _extract_set_cookies(r2a)
grabbed_fields.update(extra_2a)
except Exception:
j2a, extra_2a = None, {}
if j2a and j2a.get("success") and isinstance(j2a.get("data"), list):
for rec in j2a.get("data") or []:
if isinstance(rec, dict):
for k in ("userName", "nickname", "name"):
if rec.get(k): best_nick = str(rec.get(k))
if best_nick: break
if best_nick: break
if not best_nick:
best_nick = nick1 or nick2 or None
# 如果 still 没 nickname,拼个「图寻玩家_UID_xxxx」作为 fallback
if not best_nick:
best_nick = f"图寻玩家_UID_{best_uid}"
# ============= PASS =============
return True, (f"用户:{best_nick}(UID:{best_uid})"
f" | 历史列表有 {len(data1)} 场对局(Cookie 已验证有效)"), grabbed_fields
# 历史列表没 uid,但再请求一次 getProfile 试试(仍在 listSelfAll 这块分支内)
jp = None
try:
rp = s.get(f"{BASE_URL}/api/v0/tuxun/getProfile", timeout=20)
jp = rp.json()
grabbed_fields.update(_extract_set_cookies(rp))
except Exception:
jp = None
uid2, nick2, ph2 = _unpack_uid(jp)
if uid2 and not ph2:
return True, f"用户:{nick2 or '未命名'}(UID:{uid2})", grabbed_fields
if uid1 and not ph1:
return True, f"用户:{nick1 or '未命名'}(UID:{uid1})", grabbed_fields
# 历史列表空,且 Set-Cookie 换了新 SESSION → 这时才判为过期(之前的过期判定被我下沉到这了!)
if reissued_any and not (uid1 or uid2) and len(data1) == 0:
detail = ""
if user_sess and any_new_session_v:
detail = (f"\n\n💡 新旧 SESSION 比对(你粘的 vs 服务器要替换的):\n"
f" 你粘贴的 SESSION = {user_sess[:20]}…\n"
f" 服务器要换的新 SESSION = {any_new_session_v[:20]}…\n"
f" ⚠️ 两者不一致 = 你的 SESSION 服务器不认了(退出登录/过期)。")
if grabbed_fields:
extra = "\n\n🔎 附加信息(响应里带回来的字段):\n " + \
"\n ".join(f"{k} = {v[:20]}…" if len(str(v)) > 30 else f"{k} = {v}"
for k, v in grabbed_fields.items() if v)
else:
extra = ""
return False, ("Cookie 已过期 / 已被登出!\n"
"我发请求时,服务端立刻给我换了一个新 SESSION(说明当前这条 SESSION 服务器不认了)。\n\n"
"👉 解决办法:浏览器重新打开 https://tuxun.fun 再登录一次 → "
"F12 → 应用 → Cookies → 重新复制 SESSION=... + fun_ticket=... 两行。"
+ detail + extra), grabbed_fields
# ① 严格接口 user/getProfile(次优先,在历史列表判断不通过才跑)
try:
ru = s.get(f"{BASE_URL}/api/v0/tuxun/user/getProfile", timeout=20)
j = ru.json()
grabbed_fields.update(_extract_set_cookies(ru))
except Exception:
j = None
uid, nick, ph = _unpack_uid(j)
if uid and not ph:
return True, f"用户:{nick or '未命名'}(UID:{uid})", grabbed_fields
err1 = (j or {}).get("errorMessage") or (j or {}).get("hintMessage") or "未登录"
# ② 严格接口 listSelfRating
try:
r2 = s.get(f"{BASE_URL}/api/v0/tuxun/history/listSelfRating",
params={"pageNum": 1, "pageSize": 3}, timeout=20)
j2 = r2.json()
grabbed_fields.update(_extract_set_cookies(r2))
except Exception:
j2 = None
if j2 and j2.get("success"):
# 这也是一条可靠判定:rating 列表非空且里面有 userId → 这个 Cookie 就是有效的
if isinstance(j2.get("data"), list):
data2 = j2.get("data") or []
best_uid = None
best_nick = None
for rec in data2:
if isinstance(rec, dict):
u = rec.get("userId")
if u is not None and str(u) not in ("None", "", "null"):
best_uid = u
for k in ("userName", "nickname", "name"):
if rec.get(k): best_nick = str(rec.get(k))
break
if best_uid:
if not best_nick: best_nick = f"图寻玩家_UID_{best_uid}"
return True, (f"用户:{best_nick}(UID:{best_uid})"
f" | 评分列表有 {len(data2)} 场对局(Cookie 已验证有效)"), grabbed_fields
try:
r3 = s.get(f"{BASE_URL}/api/v0/tuxun/getProfile", timeout=20)
j3 = r3.json()
grabbed_fields.update(_extract_set_cookies(r3))
except Exception:
j3 = None
uid3, nick3, ph3 = _unpack_uid(j3)
if uid3 and not ph3:
return True, f"用户:{nick3 or '未命名'}(UID:{uid3})", grabbed_fields
err2 = (j2 or {}).get("errorMessage") or (j2 or {}).get("hintMessage") or "未登录"
# ③ fallback getProfile 必须有 userId (否则返回"已注销用户"占位符)
try:
r4 = s.get(f"{BASE_URL}/api/v0/tuxun/getProfile", timeout=20)
j4 = r4.json()
grabbed_fields.update(_extract_set_cookies(r4))
except Exception:
j4 = None
uid4, nick4, ph4 = _unpack_uid(j4)
if uid4 and not ph4:
return True, f"用户:{nick4 or '未命名'}(UID:{uid4})", grabbed_fields
if ph1 or (ph2 is True) or (ph is True) or (ph4 is True):
return False, ("Cookie 已过期(服务端返回「已注销用户」占位信息,没有拿到真实 UID)。\n\n"
"👉 解决:浏览器重新打开 https://tuxun.fun → 登录(右上角刷新你的昵称)→ "
"F12 → 应用 → Cookies → 重新复制 SESSION=...;fun_ticket=...;HMACCOUNT=..."), grabbed_fields
if reissued_any:
detail = ""
if user_sess and any_new_session_v:
detail = (f"\n\n💡 新旧 SESSION 比对:\n"
f" 你粘贴的 = {user_sess}\n"
f" 服务器换掉的 = {any_new_session_v}")
if grabbed_fields:
detail += "\n\n🔎 响应里额外带回来的字段(发回去可能让 SESSION 生效):\n"
for k, v in grabbed_fields.items():
if v:
detail += f" {k} = {v[:30]}{'…' if len(str(v)) > 30 else ''}\n"
return False, ("Cookie 已过期 / 已被登出!(每发一次请求,服务端都强制发一个新 SESSION 替换掉你粘的那条)\n\n"
"👉 解决:浏览器重新打开 https://tuxun.fun 再登录一次 → "
"F12 → 应用 → Cookies → 复制新的 SESSION=... 那一行,并把 fun_ticket、HMACCOUNT 一起复制过来。"
+ detail), grabbed_fields
return False, f"Cookie 无效({err1};{err2})。请重新按教程复制完整的 Cookie。", grabbed_fields
def list_self_history(s: requests.Session, page_size: int = 20) -> Tuple[bool, List[Dict[str, Any]], str]:
j = _get(s, "/api/v0/tuxun/history/listSelfAll",
params={"pageNum": 1, "pageSize": page_size})
if j is None:
return False, [], "网络不通"
if j.get("success"):
data = j.get("data") or []
if isinstance(data, list):
return True, data, "ok"
inner = (data.get("records") if isinstance(data, dict) else None) or \
(isinstance(data, dict) and data.get("list")) or \
(isinstance(data, dict) and data.get("items")) or []
if isinstance(inner, list):
return True, inner, "ok"
return True, [], "ok"
msg = (j.get("hintMessage") or j.get("hintCode") or j.get("message") or "未知错误")
return False, [], str(msg)
def get_solo_game(s: requests.Session, game_id: str) -> Dict[str, Any]:
j = _get(s, "/api/v0/tuxun/solo/get", params={"gameId": game_id})
if j is None:
return {"ok": False, "err": "network", "msg": "请求超时 / 网络不通"}
if j.get("success"):
d = j.get("data") or {}
rs = d.get("rounds") or []
rounds: List[Dict[str, Any]] = []
pano_cache: Dict[str, Dict[str, Any]] = {} # panoId -> 公开接口返回的坐标,避免同题重复请求
def _pick_lat_lng(r_obj: Dict[str, Any]) -> Tuple[Optional[float], Optional[float], Optional[str], Optional[str]]:
"""兼容 6 种位置写法:
1) r.lat / r.lng (你现在的最新对局就是这种,noMove 模式,已答完的题有)
2) r.pano.lat / .lng (旧版本/某些模式)
3) r.pano.latitude / .longitude
4) r.correctLat / correctLng
5) r.correctLocation.lat/lng
6) r.location / .center / .geo[.lat/.lng]
同时返回 panoId 和 source 作为附加。
"""
lat = lng = None
pano_id = None
source = None
pano_obj = r_obj.get("pano") if isinstance(r_obj.get("pano"), dict) else None
if isinstance(r_obj.get("source"), str) and r_obj.get("source"):
source = str(r_obj.get("source"))
if pano_obj:
if isinstance(pano_obj.get("source"), str) and pano_obj.get("source"):
source = str(pano_obj.get("source"))
pano_id = pano_obj.get("panoId") or r_obj.get("panoId")
else:
pano_id = r_obj.get("panoId")
candidates_lat = [
r_obj.get("lat"),
(pano_obj or {}).get("lat"),
(pano_obj or {}).get("latitude"),
r_obj.get("correctLat"),
(r_obj.get("correctLocation") or {}).get("lat") if isinstance(r_obj.get("correctLocation"), dict) else None,
(r_obj.get("correctLocation") or {}).get("latitude") if isinstance(r_obj.get("correctLocation"), dict) else None,
(r_obj.get("location") or {}).get("lat") if isinstance(r_obj.get("location"), dict) else None,
(r_obj.get("center") or {}).get("lat") if isinstance(r_obj.get("center"), dict) else None,
r_obj.get("latitude"),
]
candidates_lng = [
r_obj.get("lng"),
(pano_obj or {}).get("lng"),
(pano_obj or {}).get("lon"),
(pano_obj or {}).get("longitude"),
r_obj.get("correctLng"),
r_obj.get("correctLon"),
(r_obj.get("correctLocation") or {}).get("lng") if isinstance(r_obj.get("correctLocation"), dict) else None,
(r_obj.get("correctLocation") or {}).get("lon") if isinstance(r_obj.get("correctLocation"), dict) else None,
(r_obj.get("correctLocation") or {}).get("longitude") if isinstance(r_obj.get("correctLocation"), dict) else None,
(r_obj.get("location") or {}).get("lng") if isinstance(r_obj.get("location"), dict) else None,
(r_obj.get("center") or {}).get("lng") if isinstance(r_obj.get("center"), dict) else None,
r_obj.get("longitude"),
r_obj.get("lon"),
]
for x in candidates_lat:
try:
f = float(x)
if -90.0 <= f <= 90.0: lat = f; break
except Exception:
continue
for x in candidates_lng:
try:
f = float(x)
if -180.0 <= f <= 180.0: lng = f; break
except Exception:
continue
return lat, lng, (str(pano_id) if pano_id is not None else None), source
for idx, r in enumerate(rs):
if not isinstance(r, dict):
continue
lat, lng, pano_id, source = _pick_lat_lng(r)
# ============= 关键修复:未答完的题 rounds[i] 里只有 panoId 没 lat/lng → 走公开 getPanoInfo 实时拿 =============
if (lat is None or lng is None) and pano_id:
info = pano_cache.get(pano_id)
if info is None or not info:
# 传 rounds[i].source 作为提示:QQ 源 panoId 直接走 getQQPanoInfo
info = get_pano_info(s, pano_id, source_hint=source)
if info is None:
pano_cache[pano_id] = {}
else:
pano_cache[pano_id] = info or {}
if info:
tlat = info.get("lat")
tlng = info.get("lng")
tsrc = info.get("source") or source
try:
if tlat is not None: lat = float(tlat)
if tlng is not None: lng = float(tlng)
except Exception:
lat = lng = None
if (tsrc or "") and not source:
source = str(tsrc)
rounds.append({
"lat": lat, "lng": lng,
"panoId": pano_id, "source": source,
"move": r.get("move"), "heading": r.get("heading"),
})
# 额外回传 currentRound / totalRound:给 tracked_refresher 标「当前正在答第 X 题」用
cr = d.get("currentRound")
tr = d.get("totalRound")
try: cr_i = int(cr) if cr is not None else None
except Exception: cr_i = None
try: tr_i = int(tr) if tr is not None else (len(rounds) if rounds else None)
except Exception: tr_i = (len(rounds) if rounds else None)
return {
"ok": True,
"rounds": rounds,
"gameId": d.get("gameId") or game_id,
"type": d.get("type") or "",
"mapsName": d.get("mapsName") or d.get("modeName") or "",
"currentRound": cr_i,
"totalRound": tr_i,
"moveType": d.get("moveType") or "",
}
msg = str(j.get("hintMessage") or j.get("errorMessage") or j.get("message") or str(j))
s_msg = msg.lower()
if "login" in s_msg or "need_login" in str(j) or "unlogin" in s_msg:
return {"ok": False, "err": "need_login", "msg": "需要登录 Cookie,请重新粘贴。"}
if "timeout" in s_msg or "timed out" in s_msg:
return {"ok": False, "err": "network", "msg": msg}
return {"ok": False, "err": "other", "msg": msg}
def get_pano_info(s: requests.Session, pano_id: str, source_hint: Optional[str] = None) -> Optional[Dict]:
"""
调图寻前端真实在用的街景代理:
① 主路:GET /api/v0/tuxun/mapProxy/getGooglePanoInfo (谷歌 / 百度 / 图寻私有 panoId 都会走这个,返回嵌套数组 [null,null,lat,lng])
② QQ 源(panoId 前缀 10/12/27/29/34):GET /api/v0/tuxun/mapProxy/getQQPanoInfo (返回 data.lat / data.lng 字典,真实命中 32.16,118.94)
③ 兜底:POST getGooglePanoInfoPost
④ 旧接口:GET getPanoInfo(对部分百度源有效)
source_hint 可选:传 rounds[i].source 进来,知道是 qq_pano 就优先走 QQ 接口,省探测时间
"""
if not pano_id:
return None
lat = None; lng = None; source_out = None
def _walk_obj(obj, depth=0):
nonlocal lat, lng, source_out
if depth > 9: return
if isinstance(obj, dict):
for k in ("source", "panoSource", "from", "originSource", "type"):
if isinstance(obj.get(k), str) and obj.get(k) and not source_out:
source_out = str(obj.get(k))
candidates_lat_d = [obj.get("lat"), obj.get("latitude"), obj.get("y")]
candidates_lng_d = [obj.get("lng"), obj.get("lon"), obj.get("longitude"), obj.get("x")]
for x in candidates_lat_d:
try:
f = float(x)
if -90 <= f <= 90 and (lat is None or abs(f) > 0):
lat = f; break
except Exception: pass
for x in candidates_lng_d:
try:
f = float(x)
if -180 <= f <= 180 and (lng is None or abs(f) > 0):
lng = f; break
except Exception: pass
for key in ("location", "coordinate", "center", "correctLocation", "result", "data", "point", "pos", "Location", "Coordinate", "Point", "Pos"):
sub = obj.get(key)
if sub is not None: _walk_obj(sub, depth + 1)
for v in obj.values():
if isinstance(v, (dict, list, tuple)): _walk_obj(v, depth + 1)
elif isinstance(obj, (list, tuple)):
L = len(obj)
# 图寻代理真实格式:4 项 [null, null, lat, lng](索引 2=lat 3=lng)
if L == 4:
try:
a2 = float(obj[2]); a3 = float(obj[3])
if -90 <= a2 <= 90 and -180 <= a3 <= 180:
if lat is None: lat = a2
if lng is None: lng = a3
except Exception: pass
# 另一种:[lng, lat] 2 项
if L == 2:
try:
a0 = float(obj[0]); a1 = float(obj[1])
if -180 <= a0 <= 180 and -90 <= a1 <= 90:
if lng is None: lng = a0
if lat is None: lat = a1
except Exception: pass
for v in obj:
if isinstance(v, (dict, list, tuple)): _walk_obj(v, depth + 1)
def _is_qq_like(pid: str, sh: Optional[str]) -> bool:
pid_l = (pid or "").lower()
sh_l = (sh or "").lower()
if "qq" in sh_l or "tencent" in sh_l or "腾讯" in sh_l: return True
# 腾讯/QQ panoId 前缀规律:101010 / 1209 / 2703 / 2904 / 3401 等纯数字 18~20 位,以 10/12/27/29/34 开头
if pid_l.isdigit() and len(pid_l) >= 12:
if pid_l.startswith(("10", "12", "27", "29", "34", "11", "44", "51", "37", "33", "32", "43", "42", "45", "21", "22", "23", "35", "36", "24", "25", "26", "53", "54", "61", "62", "63", "64", "65")):
return True
return False
qq_like = _is_qq_like(pano_id, source_hint)
# 如果知道是 QQ 源 → 先走 QQ 专属接口(1010103014… 实测只有这个接口能命中)
if qq_like:
j_qq = _get(s, "/api/v0/tuxun/mapProxy/getQQPanoInfo", params={"pano": pano_id, "panoId": pano_id, "from": "tuxun"}, timeout=10)
if j_qq is not None: _walk_obj(j_qq)
# 主路:GET /mapProxy/getGooglePanoInfo(对 google/baidu/private 全部命中 22/27)
if lat is None or lng is None:
j = _get(s, "/api/v0/tuxun/mapProxy/getGooglePanoInfo", params={"pano": pano_id, "panoId": pano_id, "id": pano_id, "from": "tuxun"}, timeout=10)
if j is not None: _walk_obj(j)
if lat is None or lng is None:
# POST 版兜底
j2 = _post(s, "/api/v0/tuxun/mapProxy/getGooglePanoInfoPost", json_body={"pano": pano_id, "panoId": pano_id, "id": pano_id, "from": "tuxun"}, timeout=10)
if j2 is not None: _walk_obj(j2)
# 还没拿到 & 是 QQ 源 → 再补一次 QQ 接口(怕前面没传 source_hint 漏判)
if qq_like is False:
j_qq2 = _get(s, "/api/v0/tuxun/mapProxy/getQQPanoInfo", params={"pano": pano_id, "panoId": pano_id, "from": "tuxun"}, timeout=10)
if j_qq2 is not None: _walk_obj(j_qq2)
# 最终兜底:GET /mapProxy/getPanoInfo
if lat is None or lng is None:
j3 = _get(s, "/api/v0/tuxun/mapProxy/getPanoInfo", params={"pano": pano_id, "panoId": pano_id, "from": "tuxun"}, timeout=10)
if isinstance(j3, dict) and j3.get("success") and isinstance(j3.get("data"), dict):
_walk_obj(j3.get("data") or {})
elif j3 is not None:
_walk_obj(j3)
if lat is not None and lng is not None:
api_used = "getQQPanoInfo" if qq_like else "getGooglePanoInfo_proxy"
return {"lat": float(lat), "lng": float(lng),
"source": source_out or source_hint or api_used}
return None
def extract_game_id_from_url(text: str) -> Optional[str]:
if not text:
return None
text = text.strip()
m = re.search(
r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
r"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", text)
if m:
return m.group(0)
if re.fullmatch(r"[0-9a-fA-F-]{36}", text):
return text
return None
def fmt_ts(ms: Optional[int]) -> str:
if not ms:
return "—"
try:
return datetime.fromtimestamp(int(ms) / 1000).strftime("%Y-%m-%d %H:%M")
except Exception:
return "—"
def match_type_display(t: Optional[str]) -> str:
return {"solo_match": "积分赛", "daily_challenge": "每日挑战"}.get(t or "", t or "其它")
def area_display(rt: Optional[str]) -> str:
return {"china": "🇨🇳 中国", "world": "🌏 全球"}.get(rt or "", rt or "-")
# ======================================================================
# 本地地图服务器(浏览器里看彩针)
# ======================================================================
MAP_STATE: Dict[str, Any] = {"rounds": [], "current": 0, "title": "等待新对局…"}
STATE_LOCK = threading.Lock() # 多线程(tracked_refresher + main_live + map_handler)读写 MAP_STATE 统一加锁,避免竞态半写
LEAFLET_HTML = r"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>答案地图</title>
<!-- Leaflet 三重 CDN 兜底(大陆网络不稳时自动切换) -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
onerror="this.onerror=null;this.href='https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css';" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.js';"
onload="window.__leafletOK=1"></script>
<script>
(function(){
function needPatch(){ try{ return typeof L === 'undefined' || !L.map; }catch(e){ return true; } }
function loadCDNJS(){
if(!needPatch()){ window.__leafletOK=1; return; }
var s=document.createElement('script');
s.src='https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js';
s.onload=function(){ window.__leafletOK=1; };
document.head.appendChild(s);
var l=document.createElement('link');
l.rel='stylesheet';l.href='https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css';
document.head.appendChild(l);
}
if(document.readyState==='loading'){
document.addEventListener('DOMContentLoaded', function(){ setTimeout(loadCDNJS, 2000); });
}else{
setTimeout(loadCDNJS, 2000);
}
})();
</script>
<style>
html,body{margin:0;padding:0;height:100%;background:#0f1420;color:#e6edf3;font-family:"Microsoft YaHei","Segoe UI",sans-serif;}
#hd{padding:10px 18px;background:#161b2a;border-bottom:1px solid #222a3c;display:flex;align-items:center;gap:14px;flex-wrap:wrap;}
#tt{font-size:16px;font-weight:700;color:#7cc4ff;}
#rounds{display:flex;gap:6px;flex-wrap:wrap;}
.rbtn{border:1px solid #2a3350;background:#1a2033;color:#cbd5e1;padding:6px 12px;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;transition:all .12s;}
.rbtn:hover{background:#222a43;}
.rbtn.active{background:#1f6feb;border-color:#3d8bfd;color:#fff;box-shadow:0 0 0 2px rgba(31,111,235,.25);}
.rbtn.pending{background:#11141e;border-color:#2a3350;color:#565f77;cursor:default;}
.rbtn.pending::after{content:"⏳";margin-left:5px;opacity:.7;}
.rbtn.current{background:#991b1b;border-color:#ef4444;color:#fff;box-shadow:0 0 0 3px rgba(239,68,68,.22);animation:pulse 1.4s ease-in-out infinite;}
@keyframes pulse{0%,100%{transform:scale(1);}50%{transform:scale(1.04);}}
#baseBox{display:flex;gap:6px;margin-left:auto;align-items:center;flex-wrap:wrap;}
.bbtn{border:1px solid #2a3350;background:#1a2033;color:#cbd5e1;padding:7px 12px;border-radius:6px;cursor:pointer;font-size:12px;font-weight:600;}
.bbtn:hover{background:#222a43;}
.bbtn.active{background:#16a34a;border-color:#22c55e;color:#fff;}
#all{border:1px solid #2a3350;background:#1a2033;color:#cbd5e1;padding:7px 14px;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;}
#all:hover{background:#222a43;}
#wrap{position:relative;height:calc(100% - 56px);width:100%;}
#map{height:100%;width:100%;background:#0b0f18;}
.leaflet-popup-content-wrapper{background:#1a2033;color:#e6edf3;border:1px solid #2a3350;font-size:13px;}
.leaflet-popup-tip{background:#1a2033;}
.pt{font-weight:700;color:#7cc4ff;margin-bottom:4px;font-size:15px;}
.ps{color:#9aa7bd;}
#toast{position:absolute;top:80px;left:50%;transform:translateX(-50%);background:#1f6feb;color:#fff;padding:10px 20px;border-radius:10px;font-size:15px;z-index:1000;display:none;box-shadow:0 4px 16px rgba(0,0,0,.4);font-weight:600;}
#warnBar{position:absolute;top:12px;left:12px;right:12px;background:rgba(191,54,61,.92);color:#fff;padding:10px 14px;border-radius:8px;z-index:999;display:none;font-weight:600;box-shadow:0 2px 12px rgba(0,0,0,.35);font-size:13px;}
#warnBar a{color:#fff;text-decoration:underline;margin-left:6px;}
</style>
</head>
<body>
<div id="hd">
<div id="tt">—</div>
<div id="rounds"></div>
<div id="baseBox">
<span style="color:#9aa7bd;font-size:12px;">底图:</span>
<button class="bbtn active" data-key="gaode_road">高德 路网(默认)</button>
<button class="bbtn" data-key="gaode_sat">高德 卫星</button>
</div>
<button id="all">🔍 显示全部</button>
</div>
<div id="wrap">
<div id="warnBar"></div>
<div id="toast"></div>
<div id="map"></div>
</div>
<script>
var __baseLayers = {
gaode_road: {
name: '高德路网(推荐/默认)',
url: 'https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
opts: { maxZoom: 18, maxNativeZoom: 18, subdomains: ['1','2','3','4'],
keepBuffer: 8, updateWhenIdle: false, updateWhenZooming: true, crossOrigin: true,
attribution: '© 高德' }
},
gaode_sat: {
name: '高德卫星',
url: 'https://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
opts: { maxZoom: 18, maxNativeZoom: 18, subdomains: ['1','2','3','4'],
keepBuffer: 8, updateWhenIdle: false, updateWhenZooming: true, crossOrigin: true,
attribution: '© 高德' }
}
};
var map = null, markers = [], lastKey = "", lastTs = 0, currentBase = null, baseLayer = null;
var DATA = {"rounds": [], "current": 0, "title": "等待新对局…"};
function warn(msg, href){
var w = document.getElementById('warnBar');
w.innerHTML = msg + (href ? ('<a href="'+href+'" target="_blank">手动在新窗口打开底图</a>') : '');
w.style.display = 'block';
}
function toast(msg){
var t=document.getElementById('toast');t.innerText=msg;t.style.display='block';
setTimeout(function(){t.style.display='none';},2800);
}
function addTileErrorHandler(layer, keyName){
var shown = false;
layer.on('tileerror', function(ev){
if(shown) return;
shown = true;
warn('⚠️ 高德底图加载失败(网络/CDN限制)。👉 请切换右上角底图按钮到【高德卫星】,或稍后刷新。');
toast('底图加载失败,切换底图试试');
setTimeout(function(){ shown = false; }, 8000);
});
}
function setBase(key){
if(!map) return;
currentBase = key;
var cfg = __baseLayers[key];
if(baseLayer){ try{ map.removeLayer(baseLayer); }catch(e){} baseLayer = null; }
baseLayer = L.tileLayer(cfg.url, cfg.opts);
addTileErrorHandler(baseLayer, key);
baseLayer.addTo(map);
document.querySelectorAll('.bbtn').forEach(function(b){
b.classList.toggle('active', b.getAttribute('data-key') === key);
});
}
function pin(r,idx,focus){
if(r.lat===null || r.lat===undefined || r.lng===null || r.lng===undefined) return null; // 坐标未加载(未答完的题等 panoInfo 回填中)→ 先不画 pin
var isCur = r.isCurrent === true;
var colors=["#ef4444","#f97316","#eab308","#22c55e","#3b82f6","#8b5cf6","#ec4899","#14b8a6","#f43f5e","#22d3ee","#a78bfa","#84cc16"];
var c=isCur?'#ef4444':colors[idx%colors.length]; // 当前题强制红底
var w=isCur?44:34, pad=isCur?5:3;
var ic=L.divIcon({className:'rmarker',html:'<div style="background:'+c+';color:#fff;width:'+w+'px;height:'+w+'px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:'+(isCur?16:13)+'px;border:'+pad+'px solid #fff;box-shadow:0 6px 18px rgba(0,0,0,'+(isCur?'.55':'.45')+')">'+(idx+1)+(isCur?'📍':'')+'</div>',iconSize:[w,w],iconAnchor:[w/2,w/2]});
var m=L.marker([r.lat,r.lng],{icon:ic, zIndexOffset: isCur? 500 : 0}).addTo(map);
var src=(r.source||'').replace(/_pano$/,'')||'街景';
var extra='';
try{ extra='<div class="ps" style="margin-top:4px;opacity:.75">坐标:'+Number(r.lat).toFixed(5)+', '+Number(r.lng).toFixed(5)+'</div>'; }catch(e){}
m.bindPopup('<div class="pt">第 '+(idx+1)+' 题'+(isCur?'(当前进行中)':'')+'</div><div class="ps">来源:'+src+'</div>'+extra);
if(focus) try{ m.openPopup(); }catch(e){}
markers.push(m);return m;
}
function clearAll(){markers.forEach(function(m){try{ map.removeLayer(m); }catch(e){}});markers=[];}
function renderAll(){
try{
clearAll();var bds=[];var curIdx=-1;
DATA.rounds.forEach(function(r,i){
if(!r) return;
var pm = pin(r,i,false);
if(pm){
try{
var la = Number(r.lat), ln = Number(r.lng);
if(la===la && ln===ln && la >= -90 && la <= 90 && ln >= -180 && ln <= 180) bds.push([la,ln]);
}catch(e){}
}
if(r && r.isCurrent===true) curIdx=i;
});
if(bds.length===1){ try{ map.setView(bds[0],11); }catch(e){} }
else if(bds.length>1){
try{
if(bds.length===1){ map.setView(bds[0],11); }
else { map.fitBounds(bds,{padding:[60,60], maxZoom: 16}); }
}catch(e){ toast('⚠️ 地图范围计算出错'); }
} else {
try{ map.setView([35.8617, 104.1954], 4); }catch(e){}
}
highlightRounds(curIdx>=0 ? curIdx : -1);
if(curIdx>=0 && DATA.rounds[curIdx] && DATA.rounds[curIdx].lat!=null && DATA.rounds[curIdx].lng!=null){
try{ map.setView([Number(DATA.rounds[curIdx].lat),Number(DATA.rounds[curIdx].lng)], Math.max(map.getZoom()||10, 11)); }catch(e){}
}
}catch(e){ console.error(e); toast('⚠️ 渲染出错:'+(e.message||e)); }
}
function renderOne(idx){
try{
clearAll();
var r=DATA.rounds[idx];
if(!r){ warn('这题不存在'); return; }
var noCoord = (r.lat===null || r.lat===undefined || r.lng===null || r.lng===undefined);
if(noCoord){ toast('⏳ 这题坐标还在加载中…稍后再点'); return; }
var ok = pin(r,idx,true);
if(!ok){ toast('⏳ 这题坐标还在加载中…(pin 初始化失败)'); return; }
try{ map.setView([Number(r.lat),Number(r.lng)],12); }catch(e){ toast('⚠️ 地图跳转失败:'+(e.message||e)); }
highlightRounds(idx);
}catch(e){ console.error(e); toast('⚠️ 显示这题时出错:'+(e.message||e)); }
}
function highlightRounds(a){
document.querySelectorAll('.rbtn').forEach(function(b,i){
b.classList.toggle('active',i===a);
// 额外:没坐标的题按钮灰色,表示加载中
var rd = (DATA.rounds||[])[i];
var noCoord = !!(rd && (rd.lat===null || rd.lat===undefined || rd.lng===null || rd.lng===undefined));
b.classList.toggle('pending', noCoord);
if(rd && rd.isCurrent===true) b.classList.add('current');
else b.classList.remove('current');
});
}
function buildButtons(){
try{
var w=document.getElementById('rounds');if(!w){ return; }
w.innerHTML='';
DATA.rounds.forEach(function(r,i){
var b=document.createElement('button');
b.className='rbtn';b.innerText='第'+(i+1)+'题';
var noCoord = !!(r && (r.lat===null || r.lat===undefined || r.lng===null || r.lng===undefined));
if(noCoord) b.classList.add('pending');
b.addEventListener('click',function(){ renderOne(i); });
w.appendChild(b);
});
}catch(e){ console.error(e); toast('⚠️ 按钮渲染出错'); }
}
function loadState(){
try{
fetch('/__state__',{cache:'no-store'}).then(function(r){return r.json();}).then(function(d){
try{
var rounds = d.rounds || [];
var serverKey = (d.stateKey || null);
var serverTs = Number(d.updatedAt || 0);
// 双保险:① stateKey 变了就重绘;② updatedAt 比上次新也重绘(防止未来 stateKey 逻辑又漏判)
var skip = false;
if(serverKey){
if(serverKey === lastKey && serverTs <= lastTs){ skip = true; }
lastKey = serverKey;
} else {
var key=(d.title||'')+'|'+rounds.length+'|'+
rounds.map(function(r){return (r.panoId||(r.lat+','+r.lng));}).join('|');
if(key===lastKey && serverTs <= lastTs){ skip = true; }
lastKey = key;
}
if(serverTs > lastTs){ lastTs = serverTs; }
if(skip) return;
if(rounds.length===0){ DATA=d||{}; return; }
DATA=d;
if(document.getElementById('tt')) document.getElementById('tt').innerText = d.title || '—';
buildButtons();renderAll();
toast('🎯 答案已更新:共 '+rounds.length+' 题');
}catch(e){ console.error(e); toast('⚠️ 状态解析出错:'+(e.message||e)); }
}).catch(function(){});
}catch(e){ console.error(e); }
}
function ensureMap(){
if(map) return true;
try{
if(typeof L === 'undefined' || !L.map){ return false; }
map = L.map('map', { preferCanvas: true, worldCopyJump: true, fadeAnimation: false,
zoomAnimation: true, zoomSnap: 0.25, wheelPxPerZoomLevel: 80,
inertia: true, inertiaDeceleration: 3000 })
.setView([35.8617, 104.1954], 4);
setBase('gaode_road');
document.querySelectorAll('.bbtn').forEach(function(b){
b.addEventListener('click', function(){
var k = b.getAttribute('data-key');
if(k) setBase(k);
});
});
document.getElementById('all').addEventListener('click',renderAll);
return true;
}catch(e){ return false; }
}
function boot(){
if(ensureMap()){
loadState();
setInterval(loadState, 1000);
}else{
warn('⚠️ Leaflet.js 没加载成功(CDN 不通)。👉 稍后刷新重试。');
setTimeout(boot, 1200);
}
}
if(document.readyState==='loading'){
document.addEventListener('DOMContentLoaded', function(){ setTimeout(boot, 250); });
}else{
setTimeout(boot, 250);
}
</script>
</body>
</html>
"""
class MapHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def do_GET(self):
if self.path in ("/", "/index.html", "/map.html"):
body = LEAFLET_HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
elif self.path == "/__state__":
with STATE_LOCK:
body = json.dumps(MAP_STATE, ensure_ascii=False).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store, must-revalidate")
self.end_headers()
self.wfile.write(body)
else:
self.send_response(404)
self.end_headers()
def start_map_server(port: int) -> HTTPServer:
srv = HTTPServer(("127.0.0.1", port), MapHandler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
# ======================================================================
# 主题配色(中文友好 深色舒适)
# ======================================================================
C = {
"bg0": "#0f1420", "bg1": "#161b2a", "bg2": "#1a2033", "bg3": "#222a43",
"line": "#2a3350", "text": "#e6edf3", "muted": "#9aa7bd",
"accent": "#1f6feb", "accent2": "#7cc4ff",
"ok": "#22c55e", "warn": "#f59e0b", "err": "#ef4444", "live": "#16a34a",
"step1": "#ef4444", "step2": "#f59e0b", "step3": "#22c55e",
"step4": "#3b82f6", "step5": "#8b5cf6",
}
def setup_styles():
st = ttk.Style()
try: st.theme_use("clam")
except Exception: pass
st.configure("TFrame", background=C["bg1"])
st.configure("TLabel", background=C["bg1"], foreground=C["text"], font=("Microsoft YaHei", 10))
st.configure("Muted.TLabel", background=C["bg1"], foreground=C["muted"], font=("Microsoft YaHei", 9))
st.configure("BigBold.TLabel", background=C["bg1"], foreground=C["text"],
font=("Microsoft YaHei", 11, "bold"))
st.configure("Title.TLabel", background=C["bg1"], foreground=C["accent2"],
font=("Microsoft YaHei", 13, "bold"))
st.configure("Step.TLabel", background=C["bg1"], foreground=C["muted"],
font=("Consolas", 9))
st.configure("TButton", background=C["bg3"], foreground=C["text"],
borderwidth=0, padding=(12, 7), font=("Microsoft YaHei", 10, "bold"))
st.map("TButton", background=[("active", C["accent"])])
st.configure("Primary.TButton", background=C["accent"], foreground="#ffffff",
borderwidth=0, padding=(14, 9), font=("Microsoft YaHei", 11, "bold"))
st.map("Primary.TButton", background=[("active", "#3d8bfd")])
st.configure("Ghost.TButton", background=C["bg2"], foreground=C["text"],
borderwidth=0, padding=(10, 6), font=("Microsoft YaHei", 9))
st.map("Ghost.TButton", background=[("active", C["bg3"])])
st.configure("TEntry", fieldbackground=C["bg0"], foreground=C["text"],
insertcolor=C["text"], bordercolor=C["line"],
lightcolor=C["line"], darkcolor=C["line"])
st.configure("TCombobox", fieldbackground=C["bg0"], background=C["bg3"],
foreground=C["text"], arrowcolor=C["accent2"])
st.configure("TLabelframe", background=C["bg1"], foreground=C["accent2"],
bordercolor=C["line"])
st.configure("TLabelframe.Label", background=C["bg1"], foreground=C["accent2"],
font=("Microsoft YaHei", 11, "bold"))
st.configure("Treeview", background=C["bg0"], foreground=C["text"],
fieldbackground=C["bg0"], bordercolor=C["line"],
rowheight=28, font=("Microsoft YaHei", 9))
st.configure("Treeview.Heading", background=C["bg2"], foreground=C["accent2"],
font=("Microsoft YaHei", 10, "bold"))
st.map("Treeview", background=[("selected", C["accent"])],
foreground=[("selected", "#ffffff")])
# ======================================================================
# 题卡组件
# ======================================================================
class RoundCard(tk.Frame):
def __init__(self, master, idx, data, on_loc, on_copy):
super().__init__(master, bg=C["bg2"],
highlightbackground=C["line"], highlightthickness=1, bd=0)
self.idx, self.data = idx, data
colors = ["#ef4444","#f97316","#eab308","#22c55e","#3b82f6","#8b5cf6","#ec4899","#14b8a6"]
cc = colors[idx % len(colors)]
src = (data.get("source") or "").replace("_pano", "").upper() or "街景"
tk.Label(self, text=f"{idx+1:02d}", bg=cc, fg="#ffffff",
font=("Microsoft YaHei", 13, "bold"), width=3, anchor="center").pack(
side="left", padx=(12, 14), pady=12)
mid = tk.Frame(self, bg=C["bg2"])
mid.pack(side="left", fill="both", expand=True, pady=9)
tk.Label(mid, text=f"第 {idx+1} 题 · {src}", bg=C["bg2"],
fg=C["accent2"], font=("Microsoft YaHei", 11, "bold")).pack(anchor="w")
subs = []
if data.get("move") is not None:
subs.append("可移动" if data["move"] else "固定视角")
hd = data.get("heading")
if hd is not None:
try: subs.append(f"朝向 {float(hd):.0f}°")
except Exception: subs.append(f"朝向 {hd}")
if subs:
tk.Label(mid, text=" · ".join(subs), bg=C["bg2"],
fg=C["muted"], font=("Microsoft YaHei", 9)).pack(anchor="w", pady=(2, 0))
pid = data.get("panoId")
if pid:
tk.Label(mid, text=f"街景编号:{pid[:10]}…{pid[-6:]}", bg=C["bg2"],
fg=C["muted"], font=("Consolas", 8)).pack(anchor="w", pady=(2, 0))
btns = tk.Frame(self, bg=C["bg2"])
btns.pack(side="right", padx=12)
tk.Button(btns, text="📋 复制地图链接", relief="flat", bg=C["bg3"], fg=C["text"],
activebackground=C["bg2"], activeforeground=C["text"],
font=("Microsoft YaHei", 9, "bold"), padx=10, pady=6, cursor="hand2",
command=lambda: on_copy(idx)).pack(side="right", padx=(6, 0))
tk.Button(btns, text="📍 在地图定位", relief="flat", bg=C["accent"], fg="#ffffff",
activebackground="#3d8bfd", activeforeground="#ffffff",
font=("Microsoft YaHei", 9, "bold"), padx=12, pady=6, cursor="hand2",
command=lambda: on_loc(idx)).pack(side="right")
# ======================================================================
# 启动首屏 —— 傻瓜式 3 步引导弹窗
# ======================================================================
class GuideWindow(tk.Toplevel):
def __init__(self, master, app):
super().__init__(master)
self.app = app
self.title(f"{APP_TITLE_CN} — 3 步上手")
self.configure(bg=C["bg0"])
self.geometry("760x560")
self.minsize(680, 500)
try:
self.iconbitmap(default="")
except Exception:
pass
self.transient(master)
self.grab_set()
self._build()
def _build(self):
# Header
h = tk.Frame(self, bg=C["bg1"], height=72,
highlightbackground=C["line"], highlightthickness=1)
h.pack(side="top", fill="x")
tk.Label(h, text="🎯 图寻答案地图标注器 · 3 步上手 🎯",
bg=C["bg1"], fg=C["accent2"],
font=("Microsoft YaHei", 18, "bold")).pack(pady=(14, 0))
tk.Label(h, text="不用记任何命令,照着做就行!",
bg=C["bg1"], fg=C["muted"],
font=("Microsoft YaHei", 10)).pack(pady=(2, 10))
body = tk.Frame(self, bg=C["bg0"])
body.pack(fill="both", expand=True, padx=20, pady=16)
steps = [
(C["step1"], "① 粘 Cookie(每次打开都要重新粘贴一次,不会保存)",
"点击左边「📖 我不会拿 Cookie!点我看图文教程」按钮,\n"
"跟着图文 6 步从浏览器复制到 SESSION=...(或 sessionid=...),\n"
"粘进左边第一步的大框里,再点「✅ 验证 Cookie」。\n\n"
"✅ 必选:SESSION=xxxx 或 sessionid=xxxx(至少 1 个)\n"
"🟡 可选:fun_ticket=xxxx、HMACCOUNT=xxxx(服务器会自动帮你补,不用手动找)"),
(C["step2"], "② 开启自动监测(绿点亮起就对了)",
"点绿色大按钮「🚀 开启自动监测」。\n"
"软件会每隔几秒自动看一眼你有没有新开一局,\n"
"不用你手动复制任何网址。"),
(C["step3"], "③ 去浏览器开一局,答案自动上地图!",
"正常打开 tuxun.fun → 匹配 → 中国积分 → 开始匹配。\n"
"一进入对局,软件立刻自动抓取全部答案,\n"
"弹出浏览器地图窗口,把 5~6 道题的位置\n"
"用彩色编号大头针全部标出来 🎉\n"
"(界面里不显示任何经纬度数字,更安全!)"),
]
for color, title, desc in steps:
row = tk.Frame(body, bg=C["bg1"],
highlightbackground=C["line"], highlightthickness=1)
row.pack(fill="x", pady=7)
cdot = tk.Frame(row, bg=color, width=44, height=44)
cdot.pack_propagate(False)
cdot.pack(side="left", padx=14, pady=14)
num = title[0]
tk.Label(cdot, text=num, bg=color, fg="#ffffff",
font=("Microsoft YaHei", 18, "bold")).pack(expand=True)
info = tk.Frame(row, bg=C["bg1"])
info.pack(side="left", fill="both", expand=True, padx=(0, 12), pady=12)
tk.Label(info, text=title, bg=C["bg1"], fg=C["text"],
font=("Microsoft YaHei", 12, "bold")).pack(anchor="w")
tk.Label(info, text=desc, bg=C["bg1"], fg=C["muted"],
justify="left", font=("Microsoft YaHei", 10)).pack(anchor="w", pady=(4, 0))
foot = tk.Frame(self, bg=C["bg1"], height=64,
highlightbackground=C["line"], highlightthickness=1)
foot.pack(side="bottom", fill="x")
def _open_guide_cookie():
try:
self.destroy()
except Exception:
pass
self.app._show_cookie_guide()
tk.Button(foot, text="📖 先打开:Cookie 图文教程", relief="flat",
bg=C["bg3"], fg=C["text"], activebackground=C["accent"],
activeforeground="#ffffff",
font=("Microsoft YaHei", 10, "bold"), padx=18, pady=9, cursor="hand2",
command=_open_guide_cookie).pack(side="left", padx=20, pady=12)
def _ok():
try: self.destroy()
except Exception: pass
self.app._open_map_browser()
tk.Button(foot, text="✅ 我知道了,打开地图页", relief="flat",
bg=C["accent"], fg="#ffffff", activebackground="#3d8bfd",
activeforeground="#ffffff",
font=("Microsoft YaHei", 11, "bold"), padx=22, pady=10, cursor="hand2",
command=_ok).pack(side="right", padx=20, pady=12)
# ======================================================================
# 主程序
# ======================================================================
class App:
def __init__(self, root: tk.Tk):
self.root = root
self.root.title(APP_TITLE_CN)
self.root.geometry("1280x800")
self.root.minsize(1120, 700)
self.root.configure(bg=C["bg0"])
self.map_port = MAP_PORT_DEFAULT
self.server: Optional[HTTPServer] = None
self.session: requests.Session = create_session(None)
self.rounds: List[Dict] = []
self.game_type = ""
self.maps_name = ""
self.current_game_id: Optional[str] = None
self.current_round: Optional[int] = None # 进行中对局:当前正在答第几题(1-based)
self.total_round: Optional[int] = None # 总题数
self.live_enabled = False
self.live_thread: Optional[threading.Thread] = None
self.live_stop = threading.Event()
self.poll_seconds = POLL_SECONDS_DEFAULT
self.seen_game_ids: set = set()
self.last_gmt_create = 0
self.tracked_active_game: Optional[str] = None # 正在跟踪的「进行中」对局 gameId
self.active_refresh_counter = 0
self.manual_override_until: float = 0.0 # 用户手动加载某局后,短暂不被 ACTIVE 覆盖的 deadline(epoch)
setup_styles()
self._build_ui()
self._start_map_server()
self._log(f"本地地图页已启动:http://127.0.0.1:{self.map_port}/")
self._log("如果没自动弹出地图,点右上角「打开地图页」按钮。")
# 只读取上次保存的界面偏好(poll_seconds),**Cookie 按用户要求不再自动加载,每次都要手动重输**
cfg = load_settings()
try:
poll = float(cfg.get("poll_seconds") or POLL_SECONDS_DEFAULT)
if 1.0 <= poll <= 30.0:
self.poll_seconds = poll
except Exception:
pass
self.poll_var.set(f"{self.poll_seconds:.1f}")
# 首启必然没有 Cookie → 弹「3 步上手」引导窗(不再自动回填上次,让用户每次按教程新复制)
self.root.after(600, self._show_guide)
# ============== UI ==============
def _build_ui(self):
wrap = tk.Frame(self.root, bg=C["bg0"])
wrap.pack(fill="both", expand=True)
# ========== 顶部大条 ==========
top = tk.Frame(wrap, bg=C["bg1"], height=66,
highlightbackground=C["line"], highlightthickness=1)
top.pack(side="top", fill="x")
tk.Label(top, text="🎯 图寻答案 · 地图自动标注器",
bg=C["bg1"], fg=C["accent2"],
font=("Microsoft YaHei", 15, "bold")).pack(side="left", padx=20, pady=14)
tk.Label(top, text="只要 3 步,自动监测,不显示任何经纬度数字 · 只在地图标彩色大头针",
bg=C["bg1"], fg=C["muted"],
font=("Microsoft YaHei", 10)).pack(side="left", padx=4)
pill_wrap = tk.Frame(top, bg=C["bg1"])
pill_wrap.pack(side="right", padx=18)
self.live_pill = tk.Label(pill_wrap, text="⚪ 自动监测:关闭",
bg=C["bg3"], fg=C["muted"],
font=("Microsoft YaHei", 10, "bold"),
padx=14, pady=6, cursor="hand2")
self.live_pill.pack(side="right", padx=(8, 0))
self.live_pill.bind("<Button-1>", lambda e: self._toggle_live())
self.status_lbl = tk.Label(pill_wrap, text="待机中", bg=C["bg1"], fg=C["muted"],
font=("Consolas", 10), padx=10)
self.status_lbl.pack(side="right")
self.open_map_btn = tk.Button(top, text="🗺️ 打开地图页", relief="flat",
bg=C["accent"], fg="#ffffff",
activebackground="#3d8bfd", activeforeground="#ffffff",
font=("Microsoft YaHei", 11, "bold"), padx=18, pady=8,
cursor="hand2", command=self._open_map_browser)
self.open_map_btn.pack(side="right", padx=14, pady=14)
# ========== 主左右分栏 ==========
body = tk.Frame(wrap, bg=C["bg0"])
body.pack(fill="both", expand=True, padx=14, pady=14)
# ========== 左侧控制面板(420px,核心 3 步) ==========
left = tk.Frame(body, bg=C["bg1"], highlightbackground=C["line"], highlightthickness=1)
left.pack(side="left", fill="both", expand=False)
left.configure(width=430)
left.pack_propagate(False)
# —— 第一步:Cookie ——
box1 = ttk.Labelframe(left, text=" ① 粘贴 Cookie(每次打开程序都要重新粘贴,不会自动保存) ", padding=14)
box1.pack(fill="x", padx=14, pady=(14, 10))
# 顶部红色警告条:绝对强调「不会保存,每次重输」
warn_strip = tk.Frame(box1, bg="#5c1f1f",
highlightbackground="#a02525", highlightthickness=1)
warn_strip.pack(fill="x", pady=(0, 10))
tk.Label(warn_strip,
text="⚠️ 重要:Cookie 不会保存到电脑上! 每次打开本程序都要重新复制一次。",
bg="#5c1f1f", fg="#ffd4d4",
font=("Microsoft YaHei", 9, "bold"),
padx=10, pady=6, justify="left", wraplength=380
).pack(fill="x", anchor="w")
# 「要抓哪几个 Cookie」大白话说明
cookie_info = tk.Frame(box1, bg=C["bg1"])
cookie_info.pack(fill="x", pady=(0, 8))
tk.Label(cookie_info, text="你需要从浏览器复制以下 Cookie(最少 1 个必选,其他可选):",
bg=C["bg1"], fg=C["text"],
font=("Microsoft YaHei", 10, "bold")).pack(anchor="w")
rows_cookie = [
("🟢 必选", "SESSION=xxxx 或 sessionid=xxxx", "(两个名字出现哪个就复制哪个,二者选其一即可)"),
("🟡 可选", "fun_ticket=xxxx", "(不是每次都有;服务器响应里它会自动帮你补)"),
("🟡 可选", "HMACCOUNT=xxxx", "(不是每次都有;服务器响应里它会自动帮你补)"),
]
for tag, kex, desc in rows_cookie:
row = tk.Frame(cookie_info, bg=C["bg1"])
row.pack(fill="x", anchor="w", pady=1)
tk.Label(row, text=tag, width=9, anchor="w",
bg=C["bg1"], fg=C["accent2"],
font=("Microsoft YaHei", 9, "bold")).pack(side="left")
tk.Label(row, text=kex,
bg=C["bg1"], fg=C["ok"],
font=("Consolas", 10, "bold")).pack(side="left")
tk.Label(row, text=" " + desc,
bg=C["bg1"], fg=C["muted"],
font=("Microsoft YaHei", 9)).pack(side="left")
tk.Label(cookie_info,
text="\n💡 正确粘贴格式示例:SESSION=YWQ0OWI4MzEtMzExZi00YjIwLThkZDUtMDUwNjhhM2EzOGVk; fun_ticket=abc123",
bg=C["bg1"], fg=C["accent2"],
font=("Consolas", 9), justify="left", wraplength=380
).pack(fill="x", anchor="w")
b_row = tk.Frame(box1, bg=C["bg1"])
b_row.pack(fill="x", pady=(10, 6))
ttk.Button(b_row, text="📖 我不会拿 Cookie!点我看图文教程(6 步)",
style="Primary.TButton", command=self._show_cookie_guide
).pack(side="left", expand=True, fill="x", padx=(0, 6))
ttk.Button(b_row, text="✅ 验证 Cookie", style="TButton",
command=self._verify_cookie_click).pack(side="right", padx=(6, 0))
self.cookie_entry = tk.Text(box1, height=3, bg=C["bg0"], fg=C["text"],
insertbackground=C["text"], bd=0, wrap="word",
highlightbackground=C["line"], highlightthickness=1,
font=("Consolas", 9))
self.cookie_entry.pack(fill="x", pady=(2, 6))
self.account_lbl = tk.Label(box1, text="(把复制好的 SESSION=... / sessionid=... 粘进上面的文本框,再点右侧『✅ 验证 Cookie』,这里会显示你的账号名)",
bg=C["bg1"], fg=C["muted"],
font=("Microsoft YaHei", 9), justify="left", wraplength=380)
self.account_lbl.pack(fill="x", anchor="w")
# 快捷填充区:只留「剪贴板一键填」+「清空」两个常用按钮,移除「用上次保存的」「你给我的 Cookie #1/#2」(不存 Cookie 了,也不要把硬编码 Cookie 放源码里)
quick_row = tk.Frame(box1, bg=C["bg1"])
quick_row.pack(fill="x", pady=(10, 0))
def _q_paste_and_go(cs: str):
c = self._clean_cookie(cs)
self.cookie_entry.delete("1.0", "end")
self.cookie_entry.insert("1.0", c)
self._save_cookie_only()
threading.Thread(target=self._verify_cookie_worker,
kwargs={"silent": False}, daemon=True).start()
def _q_clipboard():
try:
cs = self.root.clipboard_get()
except Exception:
messagebox.showwarning(APP_TITLE_CN, "剪贴板是空的,或被其他程序锁定了。")
return
if not cs or not cs.strip():
messagebox.showinfo(APP_TITLE_CN, "剪贴板里是空的,先去浏览器复制好 Cookie 再点我。")
return
_q_paste_and_go(cs)
def _q_clear():
self.cookie_entry.delete("1.0", "end")
self.account_lbl.configure(text="(已清空,去浏览器重新复制吧~", fg=C["muted"])
self._set_status("Cookie 已清空", C["muted"])
btns = [
("📋 用我剪贴板的内容(一键粘贴+验证)", _q_clipboard, "#6a0dad"),
("🧹 清空输入框", _q_clear, "#a0522d"),
]
for idx, (txt, cmd, col) in enumerate(btns):
tk.Button(quick_row, text=txt, relief="flat", cursor="hand2",
bg=col, fg="#ffffff",
activebackground=col, activeforeground="#ffffff",
font=("Microsoft YaHei", 10, "bold"),
padx=12, pady=6, command=cmd
).pack(side="left", padx=(0 if idx == 0 else 8), fill="x", expand=True)
tk.Label(quick_row,
text="(先在浏览器复制好 SESSION=…,再点左边紫色「📋 用剪贴板」就会自动填好并立即验证,最省事!)",
bg=C["bg1"], fg=C["muted"], font=("Microsoft YaHei", 8), justify="left"
).pack(fill="x", pady=(6, 0), anchor="w")
diag_row = tk.Frame(box1, bg=C["bg1"])
diag_row.pack(fill="x", pady=(10, 0))
tk.Button(diag_row, text="🔧 诊断:抓请求日志(写到右侧日志)",
relief="flat", cursor="hand2",
bg="#d9534f", fg="#ffffff",
activebackground="#b52b27", activeforeground="#ffffff",
font=("Microsoft YaHei", 10, "bold"),
padx=14, pady=7, command=self._diag_cookie_click
).pack(side="left")
tk.Button(diag_row, text="📝 复制诊断结果",
relief="flat", cursor="hand2",
bg="#f0ad4e", fg="#ffffff",
activebackground="#ec971f", activeforeground="#ffffff",
font=("Microsoft YaHei", 10, "bold"),
padx=14, pady=7, command=self._diag_copy_click
).pack(side="left", padx=(8, 0))
tk.Label(diag_row,
text="(按了诊断后,右侧『运行日志』会出现 4 组 CASE 的请求细节;把日志发我我就能直接看出为啥过期)",
bg=C["bg1"], fg=C["muted"], font=("Microsoft YaHei", 8), justify="left"
).pack(fill="x", pady=(8, 0), anchor="w")
self._last_diag_text = ""
# —— 第二步:启动监测 ——
box2 = ttk.Labelframe(left, text=" ② 开启自动监测(点完绿了就别动了) ", padding=14)
box2.pack(fill="x", padx=14, pady=(4, 10))
interval_row = tk.Frame(box2, bg=C["bg1"])
interval_row.pack(fill="x", pady=(0, 10))
tk.Label(interval_row, text="⏱ 每隔", bg=C["bg1"],
fg=C["text"], font=("Microsoft YaHei", 10)).pack(side="left")
self.poll_var = tk.StringVar(value="3.0")
tk.Entry(interval_row, textvariable=self.poll_var, width=5,
bg=C["bg0"], fg=C["text"], insertbackground=C["text"],
font=("Consolas", 10), justify="center",
highlightbackground=C["line"], highlightthickness=1, bd=0,
).pack(side="left", padx=(10, 4))
tk.Label(interval_row, text="秒 查一次服务器(建议 1.5 ~ 4)",
bg=C["bg1"], fg=C["muted"],
font=("Microsoft YaHei", 9)).pack(side="left")
self.toggle_live_btn = ttk.Button(box2, text="🚀 点我:开启自动监测",
style="Primary.TButton",
command=self._toggle_live)
self.toggle_live_btn.pack(fill="x", pady=(0, 8))
tk.Label(box2, text="监测原理:每隔几秒读一次你账号的「最近比赛记录」,\n"
"一旦服务器出现新对局 ID,立刻把答案抓回来标到地图上。",
bg=C["bg1"], fg=C["muted"], font=("Microsoft YaHei", 9),
justify="left", wraplength=380).pack(anchor="w")
# —— 第三步:打开地图 ——
box3 = ttk.Labelframe(left, text=" ③ 查看地图答案 ", padding=14)
box3.pack(fill="x", padx=14, pady=(4, 10))
ttk.Button(box3, text="🗺️ 打开地图页(答案在这里看)",
style="Primary.TButton", command=self._open_map_browser
).pack(fill="x", pady=(0, 8))
ttk.Button(box3, text="🔄 重新加载当前对局", style="Ghost.TButton",
command=self._reload_current).pack(fill="x")
# —— 加载到的题目列表(可展开滚动)——
box4 = ttk.Labelframe(left, text=" 📋 当前对局题目(点定位/复制链接) ", padding=10)
box4.pack(fill="both", expand=True, padx=14, pady=(4, 14))
self.rounds_wrap = tk.Frame(box4, bg=C["bg1"])
self.rounds_wrap.pack(fill="both", expand=True)
self._empty_rounds()
# ========== 右侧:历史对局表 + 活动日志 ==========
right = tk.Frame(body, bg=C["bg0"])
right.pack(side="left", fill="both", expand=True, padx=(14, 0))
# R1: 历史记录表(最近比赛)
rh = tk.Frame(right, bg=C["bg1"], height=305,
highlightbackground=C["line"], highlightthickness=1)
rh.pack(side="top", fill="x")
rh.pack_propagate(False)
hh = tk.Frame(rh, bg=C["bg1"])
hh.pack(fill="x", padx=14, pady=(12, 6))
tk.Label(hh, text="📜 最近 20 局记录(双击任一行 → 立刻把该局答案标到地图上)",
bg=C["bg1"], fg=C["accent2"],
font=("Microsoft YaHei", 11, "bold")).pack(side="left")
self.meta_lbl = tk.Label(hh, text="—", bg=C["bg1"], fg=C["muted"],
font=("Microsoft YaHei", 9))
self.meta_lbl.pack(side="right")
ttk.Button(hh, text="🔄 刷新记录", style="Ghost.TButton",
command=self._refresh_history_click).pack(side="right", padx=10)
cols = ("type", "area", "rating", "delta", "created", "finished", "status")
tv_wrap = tk.Frame(rh, bg=C["bg0"])
tv_wrap.pack(fill="both", expand=True, padx=14, pady=(0, 14))
self.tree = ttk.Treeview(tv_wrap, columns=cols, show="headings", selectmode="browse", height=8)
col_cfg = [
("type", "类型", 90, "w"),
("area", "地区", 80, "center"),
("rating", "当前积分", 78, "center"),
("delta", "积分变化", 78, "center"),
("created", "开始时间", 150, "center"),
("finished","结束时间", 150, "center"),
("status", "状态", 80, "center"),
]
for c, t, w, an in col_cfg:
self.tree.heading(c, text=t)
self.tree.column(c, width=w, anchor=an)
self.tree.tag_configure("active", background="#152a1e")
self.tree.tag_configure("current", background="#10233e")
vsb = ttk.Scrollbar(tv_wrap, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=vsb.set)
self.tree.pack(side="left", fill="both", expand=True)
vsb.pack(side="right", fill="y")
self.tree.bind("<Double-1>", lambda e: self._load_selected())
self.tree.bind("<<TreeviewSelect>>", self._on_tree_select)
# R2: 选中行操作按钮栏
ab = tk.Frame(right, bg=C["bg1"],
highlightbackground=C["line"], highlightthickness=1)
ab.pack(side="top", fill="x", pady=(12, 0))
tk.Label(ab, text="当前选中:", bg=C["bg1"], fg=C["muted"],
font=("Microsoft YaHei", 9)).pack(side="left", padx=14, pady=10)
self.sel_lbl = tk.Label(ab, text="(还没选,从上面表里点一行)",
bg=C["bg1"], fg=C["accent2"],
font=("Microsoft YaHei", 10, "bold"))
self.sel_lbl.pack(side="left", padx=6, pady=10)
ttk.Button(ab, text="🎯 加载这局答案 → 标到地图上",
style="Primary.TButton", command=self._load_selected
).pack(side="right", padx=14, pady=8)
# R3: 日志
log = tk.Frame(right, bg=C["bg1"],
highlightbackground=C["line"], highlightthickness=1)
log.pack(side="top", fill="both", expand=True, pady=(12, 0))
lh = tk.Frame(log, bg=C["bg1"])
lh.pack(fill="x", padx=14, pady=(10, 2))
tk.Label(lh, text="🧾 运行日志", bg=C["bg1"], fg=C["accent2"],
font=("Microsoft YaHei", 11, "bold")).pack(side="left")
tk.Button(lh, text="清空", relief="flat", bg=C["bg3"], fg=C["text"],
activebackground=C["bg2"], font=("Microsoft YaHei", 8, "bold"),
padx=10, pady=2, cursor="hand2",
command=self._clear_log).pack(side="right")
self.log_txt = scrolledtext.ScrolledText(
log, bg=C["bg0"], fg=C["text"],
insertbackground=C["text"], bd=0,
font=("Consolas", 9), wrap="word",
selectbackground=C["accent"])
self.log_txt.pack(fill="both", expand=True, padx=14, pady=(2, 12))
self.log_txt.configure(state="disabled")
# ============== Rounds 占位/渲染 ==============
def _empty_rounds(self):
for w in self.rounds_wrap.winfo_children():
w.destroy()
tk.Label(self.rounds_wrap,
text="\n".join([
"还没有加载对局。",
"",
"✅ 如果已开启自动监测:",
" 去浏览器开一局,会自动出现在这里。",
"",
"⌨️ 如果想查旧比赛:",
" 去右边历史表里双击某一行即可。",
]), bg=C["bg1"], fg=C["muted"], justify="left",
font=("Microsoft YaHei", 10), wraplength=380
).pack(expand=True, padx=14, pady=30)
def _render_rounds(self):
for w in self.rounds_wrap.winfo_children():
w.destroy()
if not self.rounds:
self._empty_rounds()
self.root.after(0, self._update_track_lbl)
return
self.root.after(0, self._update_track_lbl)
wrap = tk.Frame(self.rounds_wrap, bg=C["bg1"])
wrap.pack(fill="both", expand=True)
canvas = tk.Canvas(wrap, bg=C["bg1"], highlightthickness=0, bd=0)
vsb = ttk.Scrollbar(wrap, orient="vertical", command=canvas.yview)
inner = tk.Frame(canvas, bg=C["bg1"])
inner.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=inner, anchor="nw", width=398)
canvas.configure(yscrollcommand=vsb.set)
canvas.pack(side="left", fill="both", expand=True)
vsb.pack(side="right", fill="y")
for i, rd in enumerate(self.rounds):
RoundCard(inner, i, rd, self._locate_round, self._copy_link).pack(
fill="x", padx=2, pady=6)
# ============== 地图服务/弹出 ==============
def _start_map_server(self):
port = self.map_port
for _ in range(30):
try:
self.server = start_map_server(port)
self.map_port = port
return
except OSError:
port += 1
self._log("⚠️ 启动本地地图服务失败,所有端口都被占用?请关占用程序重开。")
self.server = None
def _open_map_browser(self):
if not self.server:
messagebox.showerror(APP_TITLE_CN, "本地地图服务没启动,请关闭软件重开。")
return
url = f"http://127.0.0.1:{self.map_port}/"
webbrowser.open(url, new=1, autoraise=True)
self._log(f"🗺️ 已打开地图:{url}")
def _push_state(self, extra_rounds=None, extra_title=None):
rounds = extra_rounds if extra_rounds is not None else self.rounds
tp = (self.game_type or "").upper().replace("_", " ")
mp = self.maps_name or ""
parts = [p for p in (tp, mp, extra_title) if p]
title = " · ".join(parts) if parts else f"{len(rounds)} 题"
if len(rounds) > 1:
title += f"(共 {len(rounds)} 题)"
pieces = []
for r in rounds:
p_lat = str(r.get("lat")) if r.get("lat") is not None else ""
p_lng = str(r.get("lng")) if r.get("lng") is not None else ""
p_pid = str(r.get("panoId") or "")
p_cur = str(1 if r.get("isCurrent") else 0)
pieces.append(f"{p_lat}|{p_lng}|{p_pid}|{p_cur}")
# ★★★ 关键修复:每次 _push_state 都把 updatedAt(毫秒时间戳)拼进 stateKey ★★★
# 之前 bug:tracked_refresher 每 0.8 秒 force_apply=True 调 _push_state,但 rounds 内容没变 → stateKey 完全一样 → 前端判重跳过不刷新,用户以为得重启才出
# 现在:哪怕 rounds 一字没变,时间戳也变 → stateKey 必变 → 前端 loadState 1 秒内必触发重绘
updated_ts = int(time.time() * 1000)
state_key = f"{len(rounds)}::{self.current_round or 0}::{str(self.current_game_id or '')}::{'//'.join(pieces)}::t{updated_ts}"
with STATE_LOCK:
MAP_STATE["rounds"] = rounds
MAP_STATE["title"] = title
MAP_STATE["current"] = int(self.current_round or 0)
MAP_STATE["stateKey"] = state_key
MAP_STATE["updatedAt"] = updated_ts
# ============== 状态 ==============
def _set_status(self, text, color=None):
self.status_lbl.configure(text=text, fg=color or C["muted"])
self.root.update_idletasks()
def _set_live_pill(self, enabled):
if enabled:
self.live_pill.configure(text="🟢 自动监测:开启中", bg=C["live"], fg="#ffffff")
self.toggle_live_btn.configure(text="⏸ 点我:停止自动监测")
else:
self.live_pill.configure(text="⚪ 自动监测:关闭", bg=C["bg3"], fg=C["muted"])
self.toggle_live_btn.configure(text="🚀 点我:开启自动监测")
self._update_track_lbl()
def _update_track_lbl(self):
meta = ""
if self.tracked_active_game:
meta = f"🎯 持续跟踪对局中:{self.tracked_active_game[:8]}…"
elif self.current_game_id:
meta = f"📌 当前对局:{self.current_game_id[:8]}…"
self.meta_lbl.configure(
text=(meta + (f" | 共 {len(self.rounds)} 题 · {self.maps_name or self.game_type or '-'}"
if self.rounds else meta))
if meta else (f"共 {len(self.rounds)} 题 · {self.maps_name or self.game_type or '-'}"
if self.rounds else "—"))
# ============== 日志 ==============
def _log(self, msg):
ts = datetime.now().strftime("%H:%M:%S")
line = f"[{ts}] {msg}\n"
def _do():
self.log_txt.configure(state="normal")
self.log_txt.insert("end", line)
self.log_txt.see("end")
self.log_txt.configure(state="disabled")
if threading.current_thread() is threading.main_thread():
_do()
else:
self.root.after(0, _do)
def _clear_log(self):
self.log_txt.configure(state="normal")
self.log_txt.delete("1.0", "end")
self.log_txt.configure(state="disabled")
# ============== 引导弹窗 ==============
def _show_guide(self):
try:
GuideWindow(self.root, self)
except Exception as e:
self._log(f"⚠️ 引导弹窗错误:{e}")
def _show_cookie_guide(self):
top = tk.Toplevel(self.root)
top.title("📖 10 秒拿到 Cookie · 图文教程")
top.configure(bg=C["bg0"])
top.geometry("860x620")
top.minsize(780, 560)
top.transient(self.root)
h = tk.Frame(top, bg=C["bg1"], height=64,
highlightbackground=C["line"], highlightthickness=1)
h.pack(side="top", fill="x")
tk.Label(h, text="📖 10 秒从浏览器复制 Cookie · 一步一步跟着做",
bg=C["bg1"], fg=C["accent2"],
font=("Microsoft YaHei", 15, "bold")).pack(pady=14)
body = tk.Frame(top, bg=C["bg0"])
body.pack(fill="both", expand=True, padx=20, pady=16)
steps = [
(C["step1"], "第 1 步:打开并登录 tuxun.fun",
"在你平常用的浏览器(Chrome / Edge)里打开 https://tuxun.fun ,\n"
"确保你已经登录了自己的账号。\n\n"
"💡 本程序需要以下 Cookie(最少复制 1 个必选,其他可选):\n"
" 🟢 必选 ①:SESSION=xxxx 或 sessionid=xxxx(二选一即可)\n"
" 🟡 可选 ②:fun_ticket=xxxx(不是每次都有,程序会自动帮你补)\n"
" 🟡 可选 ③:HMACCOUNT=xxxx(不是每次都有,程序会自动帮你补)\n\n"
"✅ 正确粘贴示例:SESSION=YWQ0OWI4MzEtMzExZi00YjIwLThkZDUtMDUwNjhhM2EzOGVk; fun_ticket=abc123"),
(C["step2"], "第 2 步:按 F12 打开开发者工具",
"在 tuxun.fun 页面里按一下键盘左上角的 【F12】 键,\n"
"(Edge 浏览器可能弹出提示,点「打开 DevTools」即可)\n"
"会弹出一个黑黑/灰灰的调试面板。"),
(C["step3"], "第 3 步:顶部切到「应用 / Application」标签",
"面板顶部一排小标签,找到写着「应用 Application」的那一个,点它。\n"
"(没看到?把面板拉宽一点,或点标签右侧的小三角「›」展开更多标签)"),
(C["step4"], "第 4 步:左边找到 Cookies → https://tuxun.fun",
"面板左侧有一个长长的列表,向下滚一点点,找到「🔽 存储 Storage」下面的「Cookies」。\n"
"点一下 Cookies 左边的 ▶ 展开,再点它下面的「https://tuxun.fun」,\n"
"右边就会出现一张表格,每一行就是一个 Cookie!"),
(C["step5"], "第 5 步:在表格里找 SESSION(或 sessionid)整行复制,能看到多少就复制多少",
"右边表格的「名称 Name」列里,找到写着 SESSION 或 sessionid 的那一行:\n"
" → 直接双击「值 Value」列的那串长字符串 → 【Ctrl + C】复制;\n"
" → 能同时看到 fun_ticket / HMACCOUNT 就一起复制,用分号隔开格式是「SESSION=xxx; fun_ticket=xxx;」\n"
" → 复制不到 fun_ticket/HMACCOUNT 也不用担心!点验证后程序会自动帮你补全。\n\n"
"⚠️ 重要建议:直接复制整个 SESSION=值 一起粘贴,不要只复制值(更省事,不会漏)。"),
(C["step1"], "第 6 步:粘回软件 → 一键填剪贴板 → 验证",
"回到本程序,点第一步下面的紫色大按钮「📋 用我剪贴板的内容(一键粘贴+验证)」,\n"
"就会自动把你复制的粘进文本框,并立刻请求服务器验证!\n"
"验证通过后,文本框下方会显示你的昵称 + UID,就说明成功啦 🎉\n\n"
"⚠️ 记住:Cookie 不会保存到电脑!每次打开本程序都要重复一次以上步骤。"),
]
canvas_ = tk.Canvas(body, bg=C["bg0"], highlightthickness=0, bd=0)
vsb_ = ttk.Scrollbar(body, orient="vertical", command=canvas_.yview)
inner_ = tk.Frame(canvas_, bg=C["bg0"])
inner_.bind("<Configure>", lambda e: canvas_.configure(scrollregion=canvas_.bbox("all")))
canvas_.create_window((0, 0), window=inner_, anchor="nw", width=800)
canvas_.configure(yscrollcommand=vsb_.set)
canvas_.pack(side="left", fill="both", expand=True)
vsb_.pack(side="right", fill="y")
for color, title, desc in steps:
row = tk.Frame(inner_, bg=C["bg1"],
highlightbackground=C["line"], highlightthickness=1)
row.pack(fill="x", pady=8, padx=4)
dot = tk.Frame(row, bg=color, width=36, height=36)
dot.pack_propagate(False)
dot.pack(side="left", padx=14, pady=14)
n = re.search(r"第\s*(\d+)\s*步", title)
num_text = (n.group(1) if n else title[0])
tk.Label(dot, text=num_text, bg=color, fg="#ffffff",
font=("Microsoft YaHei", 14, "bold")).pack(expand=True)
info = tk.Frame(row, bg=C["bg1"])
info.pack(side="left", fill="both", expand=True, padx=(0, 14), pady=12)
tk.Label(info, text=title, bg=C["bg1"], fg=C["text"],
font=("Microsoft YaHei", 11, "bold")).pack(anchor="w")
tk.Label(info, text=desc, bg=C["bg1"], fg=C["muted"],
justify="left", font=("Microsoft YaHei", 10)).pack(anchor="w", pady=(4, 0))
f = tk.Frame(top, bg=C["bg1"], height=60,
highlightbackground=C["line"], highlightthickness=1)
f.pack(side="bottom", fill="x")
def _ok():
top.destroy()
self._open_map_browser()
tk.Button(f, text="✅ 好,我这就去复制 Cookie", relief="flat",
bg=C["accent"], fg="#ffffff", activebackground="#3d8bfd",
activeforeground="#ffffff",
font=("Microsoft YaHei", 11, "bold"), padx=24, pady=10, cursor="hand2",
command=_ok).pack(side="right", padx=20, pady=10)
# ============== Cookie 校验 ==============
# ---------------- 诊断:把 4 种发送方式 + 4 条接口 的请求细节全打到右侧日志 ---------------
def _diag_cookie_click(self):
raw = self.cookie_entry.get("1.0", "end")
c = self._clean_cookie(raw)
if not c:
messagebox.showwarning(APP_TITLE_CN,
"Cookie 框还空着!先去浏览器 F12 → 应用 → Cookies → tuxun.fun → 把 SESSION/fun_ticket/HMACCOUNT 粘进来,再点诊断。")
return
self._set_status("正在诊断 Cookie(后台跑 4 组请求,约 15 秒…)", C["warn"])
threading.Thread(target=self._diag_worker, args=(c,), daemon=True).start()
def _diag_copy_click(self):
if not (self._last_diag_text or "").strip():
messagebox.showinfo(APP_TITLE_CN, "还没诊断过哦~先点左侧红色的「🔧 诊断:抓请求日志」。")
return
try:
self.root.clipboard_clear()
self.root.clipboard_append(self._last_diag_text)
try: self.root.update()
except Exception: pass
messagebox.showinfo(APP_TITLE_CN,
f"✅ 已复制诊断结果({len(self._last_diag_text)} 字)到剪贴板!\n直接去聊天窗口 Ctrl+V 发给我就行。")
except Exception as e:
messagebox.showwarning(APP_TITLE_CN,
f"复制失败: {e}\n\n请手动选中右侧运行日志的内容复制。")
def _diag_worker(self, cookie_str: str):
def _parse_dict(cs: str) -> Dict[str, str]:
d: Dict[str, str] = {}
for pair in re.split(r"\s*;\s*", cs):
pair = pair.strip()
if not pair or "=" not in pair: continue
k, v = pair.split("=", 1)
k = k.strip(); v = v.strip()
if k: d[k] = v
for src in ("SESSION", "sessionid"):
if src in d:
for dst in ("SESSION", "sessionid"):
if dst not in d: d[dst] = d[src]
return d
def _dump(prefix: str, r: requests.Response) -> str:
lines: List[str] = []
lines.append(f"{'='*36} {prefix} {'='*36}")
lines.append(f">>> {r.request.method} {r.request.url}")
lines.append(">>> REQUEST HEADERS:")
for k, v in r.request.headers.items():
if k.lower() == "cookie":
v = (v[:180] + "…") if len(v) > 180 else v
lines.append(f" {k}: {v}")
lines.append(f"<<< STATUS: {r.status_code}")
lines.append("<<< RESPONSE HEADERS:")
for k, v in r.headers.items():
if k.lower() == "set-cookie":
for p in [x.strip() for x in v.split(",")
if any(z in x for z in ("SESSION", "fun_ticket", "HMACCOUNT", "sessionid"))]:
lines.append(f" SET-COOKIE (key part): {p[:200]}")
else:
lines.append(f" {k}: {v[:120]}")
try:
j = r.json()
if isinstance(j, dict):
keys_line = ", ".join(str(x) for x in list(j.keys())[:12])
lines.append(f"<<< JSON BODY (top keys): {keys_line}")
d = j.get("data")
if isinstance(d, dict):
u = d.get("userAO") if "userAO" in d else d
if isinstance(u, dict):
lines.append(f" userAO.userId = {u.get('userId')!r}")
lines.append(f" userAO.userName = {u.get('userName')!r}")
lines.append(f" userAO.nickname = {u.get('nickname')!r}")
lines.append(" body[:320]=" + json.dumps(j, ensure_ascii=False)[:320])
else:
lines.append(f"<<< JSON BODY type={type(j).__name__}")
lines.append(" body[:320]=" + json.dumps(j, ensure_ascii=False)[:320])
except Exception:
lines.append("<<< TEXT BODY[:320]: " + r.text[:320])
lines.append("")
return "\n".join(lines)
PATHS = (
"/",
"/api/v0/tuxun/history/listSelfAll?pageNum=1&pageSize=3",
"/api/v0/tuxun/getProfile",
"/api/v0/tuxun/history/listSelfRating?pageNum=1&pageSize=3",
)
CASES = (
("A. headers[Cookie]=整串 (allow_redirects=True)", True, True ),
("B. cookies=dict (allow_redirects=True)", False, True ),
("C. headers[Cookie]=整串 (allow_redirects=FALSE)", True, False),
("D. cookies=dict (allow_redirects=FALSE)", False, False),
)
parsed = _parse_dict(cookie_str)
header_cs = "; ".join(f"{k}={v}" for k, v in parsed.items())
out: List[str] = []
out.append(f"==== Cookie 诊断报告(生成时间 {datetime.now().strftime('%H:%M:%S')})====\n")
out.append(f"你粘贴的原始 Cookie(已清洗): {cookie_str[:220]}{'…' if len(cookie_str) > 220 else ''}")
out.append(f"解析出来的字段数: {len(parsed)},字段名: {', '.join(parsed.keys())}")
out.append(f"最终发出去的 headers Cookie: {header_cs[:200]}{'…' if len(header_cs) > 200 else ''}\n")
for label, use_hdr, allow_redir in CASES:
out.append(f"\n################ {label} ################")
s = requests.Session()
s.trust_env = False
s.headers.update(HEADERS)
if use_hdr:
s.headers["Cookie"] = header_cs
cookies_arg = None
else:
cookies_arg = parsed
for p in PATHS:
url = BASE_URL + p
tag = "GET " + p.split("?")[0]
try:
r = s.get(url, cookies=cookies_arg, allow_redirects=allow_redir, timeout=15)
except Exception as e:
out.append(f"EXC on {tag}: {e}")
continue
out.append(_dump(tag, r))
out.append("")
final = "\n".join(out)
def _ui():
self._log("==== Cookie 诊断报告(发我这段就行)START ====")
for ln in final.splitlines():
self._log(ln)
self._log("==== Cookie 诊断报告 END ====")
self._last_diag_text = final
self._set_status("诊断完成:右侧日志已生成;点黄色「📝 复制诊断结果」发给我。", C["ok"])
messagebox.showinfo(APP_TITLE_CN,
"诊断完成!\n\n右侧『运行日志』里已经写入了 4 组 CASE + 4 条接口的细节。\n"
"直接点左边黄色按钮『📝 复制诊断结果』→ 去聊天窗口 Ctrl+V 发给我。")
try: self.root.after(0, _ui)
except Exception: pass
def _save_cookie_only(self):
# 注意:按用户要求,**不再把 Cookie 存到本地文件**,只在内存里构造 session 用
c = self._clean_cookie(self.cookie_entry.get("1.0", "end"))
save_settings({"poll_seconds": self.poll_seconds})
if c:
self.session = create_session(c)
@staticmethod
def _clean_cookie(raw: str) -> str:
"""处理用户复制时经常多带的东西:Cookie: 前缀、多余空白行、首尾空格。"""
if not raw:
return ""
c = raw.strip()
# 去掉常见误复制的「Cookie:」「Cookie:」前缀
for prefix in ("Cookie:", "Cookie:", "cookie:", "COOKIE:"):
if c.startswith(prefix):
c = c[len(prefix):].strip()
break
# 去掉 \r\n 变成单行(Cookie 本身必须单行,别用分号替换,怕值里的 HTML 实体)
c = re.sub(r"[\r\n\t]+", " ", c).strip()
# 合并中间多余空格
c = re.sub(r" {2,}", " ", c)
return c.strip()
def _verify_cookie_click(self):
raw = self.cookie_entry.get("1.0", "end")
c = self._clean_cookie(raw)
# 如果被自动清洗过,写回输入框(用户能看到处理后的样子)
if c != raw.strip():
self.cookie_entry.delete("1.0", "end")
self.cookie_entry.insert("1.0", c)
if not c:
messagebox.showwarning(APP_TITLE_CN,
"Cookie 框还空着呢!\n先点「📖 我不会拿 Cookie」跟着教程复制。")
return
self.account_lbl.configure(text="⏳ 正在验证第 1 步:请求历史列表…", fg=C["warn"])
self._set_status("验证中…(1/4) 请求历史列表", C["warn"])
self._ac_progress_stage = 0
self._ac_progress_alive = True
def _ticker():
if not getattr(self, "_ac_progress_alive", False):
return
self._ac_progress_stage = self._ac_progress_stage + 1
s = self._ac_progress_stage
if s == 1:
txt = "⏳ 正在验证第 2 步:请求评分列表…"
st = "验证中…(2/4) 请求评分列表"
elif s == 2:
txt = "⏳ 正在验证第 3 步:请求用户资料…"
st = "验证中…(3/4) 请求用户资料"
elif s == 3:
txt = "⏳ 正在验证第 4 步:兜底资料校验…(稍等几秒)"
st = "验证中…(4/4) 兜底校验"
else:
txt = f"⏳ 正在验证(已等待 {s} 秒,马上好)…"
st = f"验证中…(已 {s}s)"
try:
self.account_lbl.configure(text=txt, fg=C["warn"])
self._set_status(st, C["warn"])
except Exception:
return
try:
self.root.after(1500, _ticker)
except Exception:
pass
try: self.root.after(1500, _ticker)
except Exception: pass
threading.Thread(target=self._verify_cookie_worker,
kwargs={"silent": False}, daemon=True).start()
def _verify_cookie_worker(self, silent: bool):
c = self._clean_cookie(self.cookie_entry.get("1.0", "end"))
if not c:
if not silent:
self.root.after(0, lambda: self.account_lbl.configure(
text="❌ Cookie 为空,请先粘贴。", fg=C["err"]))
return
self.session = create_session(c)
has_sess = (bool(re.search(r"\bsessionid\s*=", c, flags=re.IGNORECASE)) or
bool(re.search(r"\bSESSION\s*=", c)))
_tup = _check_auth_via_profile(self.session)
if len(_tup) == 2:
ok, info = _tup # type: ignore[misc]
extra_fields = {}
else:
ok, info, extra_fields = _tup # type: ignore[misc]
hist_ok, recs, _ = list_self_history(self.session, page_size=20)
def _save_and_reconstruct():
self._ac_progress_alive = False # ← 进度文字动画停
self._save_cookie_only()
if extra_fields and isinstance(extra_fields, dict):
need = False
rebuilt = {}
raw_now = self._clean_cookie(self.cookie_entry.get("1.0", "end"))
for p in re.split(r"\s*;\s*", raw_now):
p = p.strip()
if not p or "=" not in p: continue
k, v = p.split("=", 1); k = k.strip(); v = v.strip()
if k: rebuilt[k] = v
for kk, vv in extra_fields.items():
if not vv: continue
if kk in rebuilt and rebuilt[kk] != vv:
need = True; rebuilt[kk] = vv
elif kk not in rebuilt:
need = True; rebuilt[kk] = vv
if need:
c2 = "; ".join(f"{k}={v}" for k, v in rebuilt.items())
self.cookie_entry.delete("1.0", "end")
self.cookie_entry.insert("1.0", c2)
self.session = create_session(c2)
# 按用户要求:不再把 Cookie 存本地,只保留 poll_seconds
save_settings({"poll_seconds": self.poll_seconds})
self.root.after(0, _save_and_reconstruct)
if hist_ok:
self.root.after(0, lambda: self._render_history(recs))
self.root.after(0, lambda: self._on_verify_result(ok, info, silent, has_sessionid=has_sess,
extra_fields=extra_fields))
def _on_verify_result(self, ok: bool, info: str, silent: bool, has_sessionid: bool = True,
extra_fields: Optional[Dict[str, Any]] = None):
extra_fields = extra_fields or {}
if ok:
self.account_lbl.configure(text=f"✅ {info}", fg=C["ok"])
self._set_status("Cookie 通过", C["ok"])
self._log(f"✅ Cookie 验证通过 — {info}")
if not silent:
messagebox.showinfo(APP_TITLE_CN,
f"验证成功!\n{info}\n\n现在可以点「🚀 开启自动监测」啦~")
else:
self.account_lbl.configure(text=f"❌ {info}", fg=C["err"])
self._set_status("Cookie 无效", C["err"])
self._log(f"❌ Cookie 验证失败:{info}" + (" (没看到 SESSION= 或 sessionid=)" if not has_sessionid else ""))
# 如果你响应里有 fun_ticket / HMACCOUNT,我帮你自动拼回去了 → 提示用户再点一次验证
hint = ""
auto_filled_keys = [k for k in ("fun_ticket", "HMACCOUNT") if extra_fields.get(k)]
if auto_filled_keys:
hint = (f"\n\n🤖 自动修复:我从服务器响应里看到了 {', '.join(auto_filled_keys)},"
f"已经自动补到了你上面的输入框,并保存到了本地。\n"
f"👉 你现在只需要:不用再复制了,**再点一次『✅ 验证 Cookie』按钮**!")
if not silent:
messagebox.showerror(APP_TITLE_CN,
"Cookie 无效或已过期。\n\n"
+ str(info)
+ ("" if has_sessionid else
"\n\n⚠️ 小贴士:我在你粘贴的内容里没看到 SESSION= / sessionid= 字段,"
"请回到 F12 → 应用 → Cookies → https://tuxun.fun → "
"把右边表格里「名称 = SESSION」那一行整个「值」都复制过来。")
+ hint)
# ============== 历史记录渲染 ==============
def _refresh_history_click(self):
c = self._clean_cookie(self.cookie_entry.get("1.0", "end"))
if not c:
messagebox.showwarning(APP_TITLE_CN, "请先完成第一步:粘贴并验证 Cookie。")
return
self.session = create_session(c)
self._set_status("刷新中…", C["warn"])
threading.Thread(target=self._refresh_history_worker,
kwargs={"force_report": True}, daemon=True).start()
# ============== helper:二次判定某条 history 是否是「真·进行中」 ==============
def _hist_is_really_active(self, rec: Dict[str, Any]) -> bool:
"""给 list_self_history 拿到的 record,先过一层轻量条件,再走 solo/get 的强校验 data.status 是否 running/playing/waiting_*。
另外对 moveType=daily_challenge(每日挑战)做专门兼容:daily_challenge 的 data.status 可能不是 running,但 currentRound 还没走到最后一题 → 也当成正在进行中。
"""
if not isinstance(rec, dict): return False
gmt_end = rec.get("gmtEnd")
gc = rec.get("gmtCreate") or 0
move_type = (rec.get("moveType") or "").lower()
try:
gmt_end_int = int(gmt_end) if gmt_end not in (None, 0, "0", "") else 0
except Exception:
gmt_end_int = 0
def _basic_pass():
# ① 没结束时间(真的还在打)
if not gmt_end_int:
return True
# ② 排名字段没值(大概率还在打没出结果)
rk1, rk2, rch = rec.get("selfRank"), rec.get("teamRank"), rec.get("ratingChange")
if rk1 in (None, "") and rk2 in (None, "") and rch in (None, ""):
return True
# ③ 过去 2 小时刚创建的(daily_challenge 有时填了 gmtEnd 但还在第二题)
now_ms = int(time.time() * 1000)
try:
gmt_create_int = int(gc) if gc else 0
except Exception:
gmt_create_int = 0
if gmt_create_int > 0 and (now_ms - gmt_create_int) <= int(2 * 3600 * 1000):
return True
# ④ moveType 是 daily_challenge:每日挑战一旦创建了,就是进行中(除非服务端强制写了 end)
if move_type == "daily_challenge":
return True
return False
if not _basic_pass():
return False
gid = rec.get("gameId")
if not gid: return False
try:
j = _get(self.session, '/api/v0/tuxun/solo/get', params={'gameId': str(gid)}, timeout=10)
except Exception:
return False
status = None
cur_r_int = total_r_int = 0
rounds = []
if isinstance(j, dict) and isinstance(j.get("data"), dict):
data = j["data"]
status = str(data.get("status") or "").strip().lower()
rounds = data.get("rounds") or []
try:
total_r_int = len(rounds) if isinstance(rounds, list) else (int(data.get("totalRound") or 0))
cur_r_int = int(data.get("currentRound") or 0)
except Exception:
total_r_int = cur_r_int = 0
# 显式 running/playing/live 等直接算进行中
if status in ("running", "playing", "live", "wait", "waiting", "waiting_for_players",
"waiting_for_ready", "paused", "starting"):
return True
# 专门兼容:moveType=daily_challenge,且有 rounds 列表,不是所有题都完成(currentRound>=1 且 currentRound < 总题数,或 totalRound>0 但 status 空)
if move_type == "daily_challenge":
if total_r_int > 0:
# 只要「已答到第 1 题或以上」,且「没答完最后一题」,就当成进行中
if cur_r_int > 0 and cur_r_int < total_r_int:
return True
# 总 round>0,但 status 空 / 没写 finish → 也当成进行中(daily_challenge 服务端有时不写 status)
if status not in ("finish", "finished", "ended", "over", "done"):
return True
# 兜底:daily_challenge 有 rounds 列表至少 ≥ 1,且 moveType=daily_challenge + 没填 gmtEnd,就直接判定进行中
if isinstance(rounds, list) and len(rounds) >= 1 and not gmt_end_int:
return True
# 兜底:任何类型,有 rounds/round,但没说 finish,也当成还在进行
if (not status or status in ("", "none", "0", "null")) and total_r_int > 0 and cur_r_int > 0:
if cur_r_int <= total_r_int and status not in ("finish", "finished", "ended", "over", "done"):
return True
return False
def _refresh_history_worker(self, force_report: bool = False):
ok, recs, msg = list_self_history(self.session, page_size=20)
if ok:
if force_report:
self._log(f"✅ 历史记录已刷新,共 {len(recs)} 场。")
self._set_status("刷新完成", C["ok"])
self.root.after(0, lambda: self._render_history(recs))
return True, recs
else:
if force_report:
self._log(f"❌ 刷新历史失败:{msg}")
self._set_status("刷新失败", C["err"])
return False, []
def _render_history(self, records: List[Dict]):
self.tree.delete(*self.tree.get_children())
active_gids: set = set()
current_gid = str(self.current_game_id or "")
for r in records:
gid = str(r.get("gameId") or "")
end_ms = r.get("gmtEnd")
score = r.get("score")
if not end_ms or score is None:
active_gids.add(gid)
for r in records:
gid = str(r.get("gameId") or "")
t = match_type_display(r.get("type"))
area = area_display(r.get("ratingType"))
rating = r.get("rating") or "—"
delta = r.get("ratingChange")
if delta is None:
delta_txt = "—"
else:
try:
v = float(delta)
delta_txt = f"+{v:.0f}" if v >= 0 else f"{v:.0f}"
except Exception:
delta_txt = str(delta)
created = fmt_ts(r.get("gmtCreate"))
finished = fmt_ts(r.get("gmtEnd")) if r.get("gmtEnd") else "▶ 进行中"
status = "进行中" if (gid in active_gids) else "已结束"
tags = ()
if gid in active_gids:
tags = ("active",)
if gid == current_gid:
tags = tags + ("current",)
self.tree.insert("", "end", iid=gid, values=(
t, area, rating, delta_txt, created, finished, status,
), tags=tags)
def _on_tree_select(self, _evt=None):
sel = self.tree.selection()
if not sel:
self.sel_lbl.configure(text="(还没选,从上面表里点一行)")
return
gid = sel[0]
vals = self.tree.item(gid, "values") or ()
t = vals[0] if len(vals) else ""
area = vals[1] if len(vals) > 1 else ""
status = vals[6] if len(vals) > 6 else ""
show = f"{t} {area} · {status} · ID:{gid[:8]}…{gid[-6:]}"
self.sel_lbl.configure(text=show)
def _load_selected(self):
sel = self.tree.selection()
if not sel:
messagebox.showinfo(APP_TITLE_CN, "先从上面表里点一局要查的。")
return
gid = sel[0]
c = self._clean_cookie(self.cookie_entry.get("1.0", "end"))
if not c:
messagebox.showwarning(APP_TITLE_CN, "请先完成第一步:粘贴并验证 Cookie。")
return
self.session = create_session(c)
# 用户手动加载历史 → 15 秒内监测到的 ACTIVE 不会覆盖掉它
self.manual_override_until = time.time() + 15.0
self._log(f"📥 手动加载对局 {gid[:8]}…{gid[-6:]}(15 秒内进行中对局不会自动覆盖)")
self._set_status("手动加载中…", C["warn"])
threading.Thread(target=self._fetch_and_apply_game,
args=(gid, "历史记录(手动)"), daemon=True).start()
# ============== 对局加载 ==============
def _fetch_and_apply_game(self, gid, source, force_apply=True, open_browser_if_new=True, quiet=False):
"""
force_apply = 即便这局已经是 current_game_id,也强制刷一次 rounds(用于持续刷新 ACTIVE 对局)
open_browser_if_new = 如果是新对局(不是 current_game_id)就自动弹浏览器;如果只是刷新就不弹
quiet = 静默刷新(只改 rounds/map,不打日志、不刷历史高亮树)
"""
# 判定「是否需要 apply」:如果不是当前局就一定 apply;是当前局但 force_apply=True 也 apply
is_current = (self.current_game_id and str(self.current_game_id) == str(gid))
if is_current and not force_apply:
return
# 如果当前局是手动 override(用户双击了历史)且「这不是当前那局」,就不要抢着替换
if (not is_current) and time.time() < self.manual_override_until:
return
res = get_solo_game(self.session, gid)
if not res.get("ok"):
self._handle_fetch_err(res)
return
rounds = res.get("rounds") or []
if not rounds:
if not quiet:
self._log("⚠️ 这一局还没有题目(可能还未开局)。")
self._set_status("题目未就绪", C["warn"])
return
# 先保存旧的 current_round:用于 changed 判定(哪怕 rounds 没变,只是 currentRound 跳了也算变了)
old_current_round = self.current_round
new_current_round = None
if isinstance(res.get("currentRound"), int):
new_current_round = res.get("currentRound")
else:
try: new_current_round = int(res.get("currentRound")) if res.get("currentRound") is not None else None
except Exception: new_current_round = None
new_total_round = None
if isinstance(res.get("totalRound"), int):
new_total_round = res.get("totalRound")
else:
try: new_total_round = int(res.get("totalRound")) if res.get("totalRound") is not None else (len(rounds) if rounds else None)
except Exception: new_total_round = (len(rounds) if rounds else None)
# 给 rounds[i] 标 isCurrent:前端高亮绿色按钮 + 画一个更大的红色 pin(第 X 题)
for i, rd in enumerate(rounds):
# 先清掉旧标记(避免 dict 复用导致脏数据)
rd.pop("isCurrent", None)
if isinstance(new_current_round, int) and (i + 1) == new_current_round:
rd["isCurrent"] = True
# 如果只是静默刷新 → 不用再弹浏览器 + 少刷屏日志
changed = False
if not is_current:
changed = True
else:
# 先比 rounds 内容(长度/每一题 lat/lng/panoId/isCurrent),再比 currentRound 值,任一变了都算 changed
if self._rounds_changed(rounds):
changed = True
elif new_current_round != old_current_round:
changed = True
self.rounds = rounds
self.game_type = res.get("type") or ""
self.maps_name = res.get("mapsName") or ""
self.current_game_id = gid
self.current_round = new_current_round
self.total_round = new_total_round
# 只要 force_apply=True 或 changed → 一定 _push_state(更新 stateKey/updatedAt,前端立刻触发重绘,不等到重启跟踪)
if force_apply or changed:
self._push_state(extra_title=source)
if changed:
self.root.after(0, self._render_rounds)
if (not is_current) and open_browser_if_new:
self.root.after(0, self._open_map_browser)
if not quiet:
verb = "🔄 已刷新" if is_current else "🎯 加载"
cur_txt = f" · 当前第 {new_current_round}/{new_total_round} 题" if isinstance(new_current_round, int) and new_total_round else ""
self._log(f"{verb} 答案(共 {len(rounds)} 题 — 类型:{self.game_type or '-'} · "
f"题包:{self.maps_name or '-'}{cur_txt}|来源:{source})")
self._set_status("🎯 答案已标到地图", C["ok"])
# 把历史表里这行高亮成 current
if changed:
self.root.after(1200, lambda: self._refresh_history_worker(force_report=False))
# ============= 通用 helper:判定 rounds 真的有变化(要触发前端刷新) =============
def _rounds_changed(self, new_rounds: List[Dict[str, Any]]) -> bool:
old_rounds = self.rounds or []
new_rounds = new_rounds or []
if len(old_rounds) != len(new_rounds):
return True
for x, y in zip(old_rounds, new_rounds):
if str(x.get("lat")) != str(y.get("lat")): return True
if str(x.get("lng")) != str(y.get("lng")): return True
if str(x.get("panoId") or "") != str(y.get("panoId") or ""): return True
if str(x.get("source") or "") != str(y.get("source") or ""): return True
# 切题时 isCurrent 从 False→True / True→False 也算 changed,保证 stateKey 必变
if bool(x.get("isCurrent")) != bool(y.get("isCurrent")): return True
return False
def _refresh_after_load(self):
try:
self.root.update()
except Exception:
pass
def _handle_fetch_err(self, res):
err = res.get("err")
msg = res.get("msg", "")
if err == "need_login":
self._log("❌ /solo/get 提示未登录:Cookie 过期或不完整。")
self._set_status("Cookie 失效", C["err"])
self.root.after(0, lambda: messagebox.showerror(APP_TITLE_CN,
"这个接口要求最新的 Cookie。\n\n请按「📖 我不会拿 Cookie」教程重新复制一遍。"))
elif err == "network":
self._log(f"❌ 网络错误:{msg}")
self._set_status("网络错误", C["err"])
else:
self._log(f"❌ 抓取失败:{msg}")
self._set_status("抓取失败", C["err"])
def _reload_current(self):
if not self.current_game_id:
messagebox.showinfo(APP_TITLE_CN, "还没有任何对局被加载,先去浏览器开一局,或从右边表双击一局。")
return
c = self.cookie_entry.get("1.0", "end").strip()
if c:
self.session = create_session(c)
self._log(f"🔄 重新加载当前对局 {self.current_game_id[:8]}…")
self._set_status("重载中…", C["warn"])
threading.Thread(target=self._fetch_and_apply_game,
args=(self.current_game_id, "手动重载"), daemon=True).start()
# ============== 单题定位/复制链接 ==============
def _locate_round(self, idx):
if idx < 0 or idx >= len(self.rounds):
return
r = self.rounds[idx]
# 切换 map state 到单题状态,触发地图页自动刷新
temp_rounds = [dict(r)]
self._push_state(extra_rounds=temp_rounds,
extra_title=f"第 {idx+1} 题 单独显示")
if self.server:
webbrowser.open(f"http://127.0.0.1:{self.map_port}/", new=2, autoraise=True)
self._log(f"📍 单独显示第 {idx+1} 题")
# 2.5 秒后恢复显示全部题
def _restore():
time.sleep(2.6)
self._push_state(extra_title="全部题目")
threading.Thread(target=_restore, daemon=True).start()
def _copy_link(self, idx):
if idx < 0 or idx >= len(self.rounds):
return
r = self.rounds[idx]
link = (f"https://www.openstreetmap.org/?mlat={r['lat']}&mlon={r['lng']}"
f"#map=14/{r['lat']}/{r['lng']}")
try:
self.root.clipboard_clear()
self.root.clipboard_append(link)
self._log(f"📋 第 {idx+1} 题的地图链接已复制到剪贴板。")
except Exception as e:
self._log(f"⚠️ 复制链接失败:{e}")
# ============== 实时监测 ==============
def _toggle_live(self):
if self.live_enabled:
self._stop_live()
else:
self._start_live()
def _start_live(self):
c = self._clean_cookie(self.cookie_entry.get("1.0", "end"))
if not c:
messagebox.showwarning(APP_TITLE_CN,
"监测要读你账号的最近比赛,所以必须先完成「① 粘 Cookie → ✅ 验证」。\n\n"
"点「📖 我不会拿 Cookie!点我看图文教程」跟着做 6 步,1 分钟就能复制好。\n"
"(最少只需要 SESSION=xxxxx 或 sessionid=xxxxx 这 1 个就够用!)")
return
# 解析轮询间隔
try:
v = float(self.poll_var.get())
v = max(1.0, min(30.0, v))
self.poll_seconds = v
self.poll_var.set(f"{v:.1f}")
except Exception:
self.poll_seconds = POLL_SECONDS_DEFAULT
self.poll_var.set(f"{POLL_SECONDS_DEFAULT:.1f}")
save_settings({"poll_seconds": self.poll_seconds})
self.session = create_session(c)
# 先尝试验证一次 Cookie 有效性
self._set_status("验证 Cookie…", C["warn"])
_tup2 = _check_auth_via_profile(self.session)
if len(_tup2) == 2:
ok, info = _tup2 # type: ignore[misc]
else:
ok, info, _extra_ignored = _tup2 # type: ignore[misc]
if not ok:
self.account_lbl.configure(text=f"❌ {info}", fg=C["err"])
messagebox.showerror(APP_TITLE_CN,
f"监测启动失败:Cookie 无效。\n\n原因:{info}\n\n"
f"请按教程重复制一次 Cookie。")
self._set_status("Cookie 无效", C["err"])
return
self.account_lbl.configure(text=f"✅ {info}", fg=C["ok"])
self.live_stop.clear()
self.seen_game_ids = set()
self.last_gmt_create = 0
self.live_enabled = True
self._set_live_pill(True)
self.live_thread = threading.Thread(target=self._live_loop, daemon=True)
self.live_thread.start()
self._log(f"🚀 自动监测已启动 — 每 {self.poll_seconds:.1f} 秒查一次,监测到新对局自动加载。")
self._set_status("🟢 监测中", C["live"])
def _stop_live(self):
self.live_enabled = False
self.live_stop.set()
self._set_live_pill(False)
self._log("⏸ 自动监测已停止。")
self._set_status("待机中", C["muted"])
def _live_loop(self):
# 初始化:先加载一次历史,把当前的比赛 ID 都记为已看,避免把旧局再抓一遍
ok, recs = self._refresh_history_worker(force_report=False)
if not ok:
self._log("⚠️ 首次读取历史失败,监测将继续重试…")
else:
for r in recs:
g = str(r.get("gameId") or "")
if g:
self.seen_game_ids.add(g)
try:
gc = int(r.get("gmtCreate") or 0)
if gc > self.last_gmt_create:
self.last_gmt_create = gc
except Exception:
pass
# 如果一上来就有进行中的局(真·二次判定通过),自动加载
recs_ok = recs if ok and isinstance(recs, list) else []
# 先取 gmtCreate 最新的 N 条 → 每条都跑一次真·进行中判定(solo/get data.status)
top_candidates = sorted(recs_ok, key=lambda r: int(r.get("gmtCreate") or 0),
reverse=True)[:int(LIVE_CANDIDATES_LIMIT)]
active = []
for r in top_candidates:
try:
if self._hist_is_really_active(r):
active.append(r)
except Exception:
continue
if not active:
# 如果都没 running,退而求其次:「没 gmtEnd 且 selfRank/teamRank/ratingChange 都空」的那一条
def _fallback_pass(rr):
rk1, rk2, rch = rr.get("selfRank"), rr.get("teamRank"), rr.get("ratingChange")
if rk1 in (None, "") and rk2 in (None, "") and rch in (None, "") and not rr.get("gmtEnd"):
return True
return False
active = [r for r in recs_ok if _fallback_pass(r)]
active.sort(key=lambda r: int(r.get("gmtCreate") or 0), reverse=True)
if active:
gid = str(active[0].get("gameId") or "")
if gid:
self.tracked_active_game = gid
self.root.after(0, self._update_track_lbl)
self._log(f"🎯 启动时检测到进行中对局,持续跟踪并刷新:{gid[:8]}…")
self.root.after(0, lambda g=gid:
threading.Thread(target=self._fetch_and_apply_game,
args=(g, "监测-启动时的进行中对局", True, True, False), daemon=True).start())
tick = 0
# ============= 新增:tracked_active_game 专用高频刷新线程(每 0.8 秒 solo/get 一次 rounds) =============
# 原因:原来等 history 轮询(poll_seconds=3~5 秒)才刷 1 次 rounds,会导致「第 1 题→第 2 题」隔了 3 秒以上才更
tracked_stop = self.live_stop
tracked_gid_holder: Dict[str, Any] = {"gid": None}
def _tracked_refresher():
last_solo_err_ts = 0
while not tracked_stop.is_set():
current_gid = tracked_gid_holder.get("gid")
try:
if not current_gid:
time.sleep(min(0.6, float(TRACKED_GAME_TICK_SECONDS)))
continue
tag = (self.current_game_id == current_gid)
# 强制刷新 rounds,即便 tracked_gid 没变;force_apply 跳过 _rounds_changed 的 diff
self._fetch_and_apply_game(
current_gid,
"监测-跟踪中对局高频刷 rounds",
True, # force_apply
False, # open_browser_if_new
True # quiet(不 log 每一次,避免刷屏)
)
except Exception as e2:
now2 = time.time()
if now2 - last_solo_err_ts > 12.0:
self._log(f"⚠️ 跟踪对局刷新异常(每 12 秒最多报 1 次):{e2}")
last_solo_err_ts = now2
# 睡眠:用小步睡,stop 事件能立刻唤醒
slept2 = 0.0
step2 = 0.12
total_sleep = float(TRACKED_GAME_TICK_SECONDS)
while slept2 + step2 / 2 < total_sleep and not tracked_stop.is_set():
time.sleep(step2)
slept2 += step2
threading.Thread(target=_tracked_refresher, daemon=True).start()
# 把 tracked_active_game 初始化时的 gid 同步进 holder(每轮主循环都会更新 holder,保证高频线程跟着换)
tracked_gid_holder["gid"] = self.tracked_active_game
while not self.live_stop.is_set():
slept = 0.0
step = min(0.4, self.poll_seconds / 6)
while slept + step/2 < self.poll_seconds and not self.live_stop.is_set():
time.sleep(step)
slept += step
if self.live_stop.is_set():
break
tick += 1
try:
ok, new_recs = self._refresh_history_worker(force_report=False)
if not ok:
self._log(f"⚠️ 第 {tick} 次轮询读历史失败,下次重试。")
continue
new_recs = new_recs if isinstance(new_recs, list) else []
# ---------- (1) 更新「进行中」跟踪目标(只查 gmtCreate 最新的 5 条,避免每次读一堆 API) ----------
top_now = sorted(new_recs, key=lambda r: int(r.get("gmtCreate") or 0),
reverse=True)[:int(LIVE_CANDIDATES_LIMIT)]
real_active_now = []
for r in top_now:
try:
if self._hist_is_really_active(r):
real_active_now.append(r)
except Exception:
continue
real_active_now.sort(key=lambda r: int(r.get("gmtCreate") or 0), reverse=True)
new_active_gid = str(real_active_now[0].get("gameId") or "") if real_active_now else None
if new_active_gid and new_active_gid != self.tracked_active_game:
self.tracked_active_game = new_active_gid
tracked_gid_holder["gid"] = new_active_gid
self.root.after(0, self._update_track_lbl)
self._log(f"🎯 检测到新的进行中对局,切到跟踪它:{new_active_gid[:8]}…")
if (not new_active_gid) and self.tracked_active_game:
self._log(f"✅ 进行中对局 {self.tracked_active_game[:8]}… 已结束,停止持续跟踪刷新。")
self.tracked_active_game = None
tracked_gid_holder["gid"] = None
self.root.after(0, self._update_track_lbl)
# ---------- (2) 每隔 REFRESH_ACTIVE_EVERY 次轮询刷一次 tracked ----------
self.active_refresh_counter += 1
if (self.tracked_active_game
and (self.active_refresh_counter % max(1, int(REFRESH_ACTIVE_EVERY)) == 0)):
tag = self.current_game_id == self.tracked_active_game
# 如果当前对局就是 tracked,就是静默刷新(不开新标签,只刷 rounds/push)
# 否则视为新对局,让 _fetch 自己处理要不要开标签
threading.Thread(
target=self._fetch_and_apply_game,
args=(self.tracked_active_game, "监测-持续刷新进行中对局",
True, # force_apply = 即便 current 也是它,也要刷
not tag, # open_browser_if_new = 只有不是 current 才开
tag), # quiet = 只有已是 current 才静默
daemon=True).start()
# ---------- (3) 找从未见过的新对局(一次性,防止没被 ACTIVE 选中的历史) ----------
new_candidates = sorted(
[r for r in new_recs
if (str(r.get("gameId") or "") not in self.seen_game_ids)
or (int(r.get("gmtCreate") or 0) > self.last_gmt_create)],
key=lambda r: int(r.get("gmtCreate") or 0)
)
for r in new_candidates:
gid = str(r.get("gameId") or "")
if not gid or gid in self.seen_game_ids:
try:
gc = int(r.get("gmtCreate") or 0)
if gc > self.last_gmt_create:
self.last_gmt_create = gc
except Exception:
pass
continue
self.seen_game_ids.add(gid)
try:
gc = int(r.get("gmtCreate") or 0)
if gc > self.last_gmt_create:
self.last_gmt_create = gc
except Exception:
pass
# 新对局!立即抓答案(如果它就是 ACTIVE,那上面 (2) 已经在刷了,这里 skip 去重)
if gid == self.tracked_active_game:
continue
t = match_type_display(r.get("type"))
area = area_display(r.get("ratingType"))
self._log(f"🎯 监测到新对局:[{t} {area}] {gid[:8]}… → 立即加载答案")
self.root.after(0, lambda g=gid:
threading.Thread(target=self._fetch_and_apply_game,
args=(g, "自动监测-新对局", True, True, False), daemon=True).start())
except Exception as e:
self._log(f"⚠️ 第 {tick} 次轮询异常:{e}")
# ============== 关闭 ==============
def on_close(self):
# 按用户要求:关闭时也不存 Cookie 到本地,只保存 poll_seconds 等界面偏好
save_settings({"poll_seconds": self.poll_seconds})
try:
self.live_stop.set()
except Exception:
pass
if self.server:
try:
self.server.shutdown()
except Exception:
pass
self.root.destroy()
def main():
if sys.platform.startswith("win"):
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
root = tk.Tk()
try:
from ctypes import windll # type: ignore
try:
windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
except Exception:
pass
app = App(root)
root.protocol("WM_DELETE_WINDOW", app.on_close)
root.mainloop()
if __name__ == "__main__":
main()