nonebot-plugin-efthelper 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1112 @@
1
+ """玩家资料卡片合成。
2
+
3
+ 把角色立绘和文字信息合成到一张图里:
4
+ ┌──────────────────────────────────────────────┐
5
+ │ ┌────────┐ [ PvE ] │
6
+ │ │ │ xL1gHTx │
7
+ │ │ 角色 │ 等级 22 · USEC · 声望 0 │
8
+ │ │ 立绘 │ ██████████░░ 81.3% │
9
+ │ │ │ PMC Scav │
10
+ │ └────────┘ 场次 93 场次 9 │
11
+ │ ────────────────────────────────────── │
12
+ │ 成就 7 · 时长 88.7h · 更新于 13.2 天前 │
13
+ └──────────────────────────────────────────────┘
14
+
15
+ 背景配色随阵营变化:USEC 冷色调,BEAR 暖色调。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import io
21
+ import logging
22
+ import os
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Any, Dict, List, Optional, Tuple
26
+
27
+ from PIL import Image, ImageDraw, ImageFilter, ImageFont
28
+
29
+ try: # 让它也能脱离包单独 import(脚本 / 单测)
30
+ from .endings import ending_label
31
+ except ImportError: # pragma: no cover
32
+ from endings import ending_label
33
+
34
+ logger = logging.getLogger("nonebot_plugin_efthelper")
35
+
36
+ # ---------------------------------------------------------------- 配色
37
+
38
+ RGB = Tuple[int, int, int]
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Palette:
43
+ """阵营配色。"""
44
+
45
+ top: RGB # 渐变顶部
46
+ bottom: RGB # 渐变底部
47
+ glow: RGB # 角色背后的光晕
48
+ accent: RGB # 强调色(进度条、分隔线、数值)
49
+ text: RGB
50
+ text_dim: RGB
51
+ panel: RGB # 统计块底色
52
+
53
+
54
+ _TEXT = (240, 246, 252)
55
+
56
+ # 卡片背景配色由**游戏模式**决定,与阵营无关。
57
+ # 阵营改用右下角的徽章图标表示(USEC / BEAR)。
58
+ MODE_PALETTES: Dict[str, Palette] = {
59
+ # PVP 正式服 —— 棕
60
+ "regular": Palette(
61
+ top=(122, 82, 46),
62
+ bottom=(26, 16, 8),
63
+ glow=(198, 140, 80),
64
+ accent=(240, 178, 110),
65
+ text=_TEXT,
66
+ text_dim=(208, 186, 162),
67
+ panel=(56, 38, 22),
68
+ ),
69
+ # PVE —— 蓝
70
+ "pve": Palette(
71
+ top=(38, 92, 148),
72
+ bottom=(7, 18, 32),
73
+ glow=(74, 148, 216),
74
+ accent=(98, 180, 255),
75
+ text=_TEXT,
76
+ text_dim=(158, 186, 214),
77
+ panel=(16, 38, 62),
78
+ ),
79
+ # PVPs 赛季 —— 绿
80
+ "pvp-season": Palette(
81
+ top=(34, 112, 78),
82
+ bottom=(6, 24, 16),
83
+ glow=(72, 188, 126),
84
+ accent=(98, 226, 154),
85
+ text=_TEXT,
86
+ text_dim=(160, 210, 186),
87
+ panel=(14, 46, 32),
88
+ ),
89
+ }
90
+
91
+ DEFAULT_PALETTE = MODE_PALETTES["pve"]
92
+
93
+ # 阵营徽章配色(图标染色 + 名称)
94
+ FACTION_COLORS: Dict[str, RGB] = {
95
+ "USEC": (126, 186, 255),
96
+ "BEAR": (255, 148, 110),
97
+ }
98
+
99
+ # 模式徽章配色
100
+ MODE_COLORS: Dict[str, RGB] = {
101
+ "regular": (214, 78, 58),
102
+ "pve": (58, 160, 96),
103
+ "pvp-season": (150, 92, 200),
104
+ }
105
+
106
+ MODE_TAG: Dict[str, str] = {
107
+ "regular": "PVP",
108
+ "pve": "PVE",
109
+ "pvp-season": "PVPs",
110
+ }
111
+
112
+ ASSETS_DIR = Path(__file__).parent / "assets"
113
+
114
+ # 阵营水印在右侧信息栏里的位置。数值越大越靠左(相对卡片右边界的偏移)。
115
+ # 右栏本身是 fx(560) ~ 1156,USEC 水印按 520 高缩放后宽约 416,
116
+ # 545 大约让它居中;想更靠右就调小,更靠左就调大。
117
+ WATERMARK_LEFT_OFFSET = 545
118
+ WATERMARK_TOP = 96
119
+ WATERMARK_BOTTOM = 616
120
+
121
+ CARD_W, CARD_H = 1200, 675
122
+
123
+ # ---------------------------------------------------------------- 字体
124
+
125
+ # 常见发行版 / 容器里的 CJK 字体位置。装了 nonebot-plugin-localstore 的话
126
+ # 也可以把字体放进插件数据目录,用 EFT_FONT_PATH 指定。
127
+ _FONT_CANDIDATES = [
128
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
129
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc",
130
+ "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
131
+ "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
132
+ "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
133
+ "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
134
+ "/System/Library/Fonts/PingFang.ttc",
135
+ "C:/Windows/Fonts/msyh.ttc",
136
+ ]
137
+ _BOLD_CANDIDATES = [
138
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc",
139
+ "/usr/share/fonts/truetype/noto/NotoSansCJK-Bold.ttc",
140
+ "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
141
+ "/System/Library/Fonts/PingFang.ttc",
142
+ "C:/Windows/Fonts/msyhbd.ttc",
143
+ ]
144
+
145
+ _font_cache: Dict[Tuple[str, int], ImageFont.FreeTypeFont] = {}
146
+
147
+
148
+ def _first_existing(paths: List[str]) -> Optional[str]:
149
+ for p in paths:
150
+ if p and os.path.exists(p):
151
+ return p
152
+ return None
153
+
154
+
155
+ def find_font(*, bold: bool = False, override: Optional[str] = None) -> Optional[str]:
156
+ """找一个能显示中文的字体文件。找不到返回 None(会退回 Pillow 内置位图字体)。"""
157
+ if override and os.path.exists(override):
158
+ return override
159
+ env = os.environ.get("EFT_FONT_BOLD_PATH" if bold else "EFT_FONT_PATH")
160
+ if env and os.path.exists(env):
161
+ return env
162
+ return _first_existing(_BOLD_CANDIDATES if bold else _FONT_CANDIDATES)
163
+
164
+
165
+ def load_font(size: int, *, bold: bool = False, override: Optional[str] = None):
166
+ path = find_font(bold=bold, override=override)
167
+ key = (path or "__default__", size)
168
+ if key in _font_cache:
169
+ return _font_cache[key]
170
+ if path:
171
+ try:
172
+ # index=0 对应 NotoSansCJK 里的简体中文(SC)
173
+ font = ImageFont.truetype(path, size, index=0)
174
+ except Exception as exc: # noqa: BLE001
175
+ logger.warning("加载字体 %s 失败:%s,退回内置字体", path, exc)
176
+ font = ImageFont.load_default(size=size)
177
+ else:
178
+ font = ImageFont.load_default(size=size)
179
+ _font_cache[key] = font
180
+ return font
181
+
182
+
183
+ # ---------------------------------------------------------------- 绘图工具
184
+
185
+
186
+ def _gradient(size: Tuple[int, int], top: RGB, bottom: RGB) -> Image.Image:
187
+ """竖直渐变。用 1px 宽的图拉伸,比逐像素快得多。"""
188
+ w, h = size
189
+ strip = Image.new("RGB", (1, h))
190
+ px = strip.load()
191
+ for y in range(h):
192
+ t = y / max(1, h - 1)
193
+ px[0, y] = tuple(int(top[i] + (bottom[i] - top[i]) * t) for i in range(3))
194
+ return strip.resize((w, h), Image.BILINEAR)
195
+
196
+
197
+ def _radial_glow(size: Tuple[int, int], color: RGB, radius: float):
198
+ """角色背后的一团光晕。返回 (RGB 色块, L 通道蒙版)。"""
199
+ w, h = size
200
+ layer = Image.new("L", (w, h), 0)
201
+ draw = ImageDraw.Draw(layer)
202
+ cx, cy = w // 2, h // 2
203
+ steps = 26
204
+ for i in range(steps, 0, -1):
205
+ r = radius * i / steps
206
+ draw.ellipse(
207
+ [cx - r, cy - r * 0.95, cx + r, cy + r * 0.95],
208
+ fill=int(150 * (1 - i / steps) ** 1.6),
209
+ )
210
+ layer = layer.filter(ImageFilter.GaussianBlur(radius * 0.10))
211
+ return color, layer
212
+
213
+
214
+ def _text(draw: ImageDraw.ImageDraw, xy, s: str, font, fill, anchor="la") -> None:
215
+ draw.text(xy, s, font=font, fill=fill, anchor=anchor)
216
+
217
+
218
+ # ------------------------------------------------------------ 阵营徽章
219
+
220
+ _faction_icon_cache: Dict[str, Optional[Image.Image]] = {}
221
+
222
+
223
+ def faction_icon(faction: str) -> Optional[Image.Image]:
224
+ """加载阵营徽章的 alpha 蒙版(L 模式,可任意染色)。
225
+
226
+ 图标来自 Escape from Tarkov 官方素材,随插件一起分发;
227
+ 文件不存在或损坏时返回 None,调用方退回纯文字徽章。
228
+ """
229
+ key = faction.upper()
230
+ if key in _faction_icon_cache:
231
+ return _faction_icon_cache[key]
232
+
233
+ icon: Optional[Image.Image] = None
234
+ path = ASSETS_DIR / f"{key.lower()}.png"
235
+ if path.exists():
236
+ try:
237
+ with Image.open(path) as im:
238
+ icon = im.convert("L")
239
+ except Exception as exc: # noqa: BLE001
240
+ logger.warning("加载阵营图标 %s 失败:%s", path, exc)
241
+ else:
242
+ logger.debug("阵营图标不存在:%s", path)
243
+
244
+ _faction_icon_cache[key] = icon
245
+ return icon
246
+
247
+
248
+ def _draw_character_placeholder(
249
+ card: Image.Image, faction: str, box: Tuple[int, int, int, int]
250
+ ) -> None:
251
+ """立绘拿不到时的占位:淡化的大号阵营徽章 + 一行说明。
252
+
253
+ 比留一块空白强,也不至于让用户以为卡片坏了。
254
+ """
255
+ left, top, right, bottom = box
256
+ width, height = right - left, bottom - top
257
+
258
+ mask = faction_icon(faction)
259
+ if mask is not None:
260
+ # 徽章按角色区高度的一半左右放置,居中偏上
261
+ icon_h = int(height * 0.52)
262
+ scale = icon_h / mask.height
263
+ icon_w = max(1, int(mask.width * scale))
264
+ resized = mask.resize((icon_w, icon_h), Image.LANCZOS)
265
+
266
+ base = FACTION_COLORS.get(faction.upper(), (235, 240, 248))
267
+ tint = tuple(min(255, int(c + (255 - c) * 0.5)) for c in base)
268
+ layer = Image.new("RGBA", (icon_w, icon_h), tint + (255,))
269
+ layer.putalpha(resized.point(lambda v: int(v * 0.30)))
270
+ card.alpha_composite(layer, (left + (width - icon_w) // 2, top + int(height * 0.16)))
271
+
272
+ # 同样画在透明图层上,否则 (255,255,255,22) 会被写成纯白色块
273
+ overlay = Image.new("RGBA", card.size, (0, 0, 0, 0))
274
+ draw = ImageDraw.Draw(overlay)
275
+ font = load_font(19)
276
+ hint = "立绘服务暂不可用"
277
+ tw = draw.textlength(hint, font=font)
278
+ ty = top + int(height * 0.76)
279
+ draw.rounded_rectangle(
280
+ [left + (width - tw) / 2 - 14, ty - 7, left + (width + tw) / 2 + 14, ty + 25],
281
+ radius=8,
282
+ fill=(255, 255, 255, 22),
283
+ )
284
+ draw.text(
285
+ (left + width / 2, ty + 9),
286
+ hint,
287
+ font=font,
288
+ fill=(255, 255, 255, 170),
289
+ anchor="mm",
290
+ )
291
+ card.alpha_composite(overlay)
292
+
293
+
294
+ def draw_faction_watermark(
295
+ card: Image.Image,
296
+ faction: str,
297
+ *,
298
+ box: Tuple[int, int, int, int],
299
+ opacity: float = 0.20,
300
+ whiten: float = 0.55,
301
+ ) -> None:
302
+ """把阵营徽章作为右侧信息栏的背景水印。
303
+
304
+ 图标本身是 alpha 蒙版,这里先按阵营配色染色、再往白里提亮,
305
+ 最后整体压到很低的透明度,保证压在上面的文字依然清晰可读。
306
+
307
+ `box` 是 (left, top, right, bottom)。图标等比缩放到该高度,
308
+ 宽度按原始比例算出来,允许超出 box 右侧被卡片裁掉。
309
+ """
310
+ mask = faction_icon(faction)
311
+ if mask is None:
312
+ return
313
+
314
+ left, top, _, bottom = box
315
+ height = max(1, bottom - top)
316
+ scale = height / mask.height
317
+ width = max(1, int(mask.width * scale))
318
+ resized = mask.resize((width, height), Image.LANCZOS)
319
+
320
+ base = FACTION_COLORS.get(faction.upper(), (235, 240, 248))
321
+ tint = tuple(min(255, int(c + (255 - c) * whiten)) for c in base)
322
+
323
+ layer = Image.new("RGBA", (width, height), tint + (255,))
324
+ layer.putalpha(resized.point(lambda v: int(v * opacity)))
325
+ card.alpha_composite(layer, (left, top))
326
+
327
+
328
+ def _fit_text(
329
+ draw: ImageDraw.ImageDraw,
330
+ s: str,
331
+ max_w: int,
332
+ start: int,
333
+ *,
334
+ bold: bool = False,
335
+ min_size: int = 18,
336
+ ) -> Tuple[str, Any]:
337
+ """让文本放进 max_w:先缩字号,缩到下限仍放不下就截断加省略号。
338
+
339
+ 返回 (要画的文本, 字体)。注意返回的文本可能和输入不同——
340
+ 实测有昵称长到 60 个字符,光缩字号是不够的。
341
+ """
342
+ size = start
343
+ while size > min_size:
344
+ font = load_font(size, bold=bold)
345
+ if draw.textlength(s, font=font) <= max_w:
346
+ return s, font
347
+ size -= 2
348
+
349
+ font = load_font(min_size, bold=bold)
350
+ if draw.textlength(s, font=font) <= max_w:
351
+ return s, font
352
+
353
+ ellipsis = "…"
354
+ ell_w = draw.textlength(ellipsis, font=font)
355
+ out = ""
356
+ for ch in s:
357
+ if draw.textlength(out + ch, font=font) + ell_w > max_w:
358
+ break
359
+ out += ch
360
+ return (out + ellipsis) if out else ellipsis, font
361
+
362
+
363
+ def _flow_text(
364
+ draw: ImageDraw.ImageDraw,
365
+ items: List[str],
366
+ font,
367
+ *,
368
+ first_width: int,
369
+ full_width: int,
370
+ max_lines: int = 2,
371
+ sep: str = " · ",
372
+ ) -> Tuple[List[str], int]:
373
+ """把若干条目铺成最多 max_lines 行,尽量塞满。
374
+
375
+ 返回 (每行文本, 被省略的条目数)。第一行可用宽度是 first_width
376
+ (因为前面要放「成就 N」标签),后续行用 full_width。
377
+ """
378
+ lines: List[str] = []
379
+ cur = ""
380
+ width = first_width
381
+ used = 0
382
+ for item in items:
383
+ candidate = item if not cur else cur + sep + item
384
+ if draw.textlength(candidate, font=font) <= width:
385
+ cur = candidate
386
+ used += 1
387
+ continue
388
+ # 当前行放不下了
389
+ if cur:
390
+ lines.append(cur)
391
+ if len(lines) >= max_lines:
392
+ return lines, len(items) - used
393
+ width = full_width
394
+ cur = item
395
+ used += 1
396
+ if len(lines) >= max_lines:
397
+ return lines, len(items) - used + 1
398
+ if cur:
399
+ lines.append(cur)
400
+ return lines, 0
401
+
402
+
403
+ # ---------------------------------------------------------------- 主流程
404
+
405
+
406
+ def build_card(
407
+ profile: Dict[str, Any],
408
+ *,
409
+ mode_key: str,
410
+ mode_label: str,
411
+ level_no: int,
412
+ gained: int,
413
+ need: int,
414
+ achievements: List[Tuple[str, float]],
415
+ character_png: Optional[bytes] = None,
416
+ hours: float = 0.0,
417
+ last_active: Optional[float] = None,
418
+ updated_ago: str = "",
419
+ aid: Optional[int] = None,
420
+ font_regular: Optional[str] = None,
421
+ font_bold: Optional[str] = None,
422
+ max_achievements: int = 6,
423
+ ) -> bytes:
424
+ """合成玩家卡片,返回 PNG 字节。"""
425
+ info = profile.get("info") or {}
426
+ faction = (info.get("side") or "").upper()
427
+ faction = "BEAR" if faction == "BEAR" else "USEC"
428
+ palette = MODE_PALETTES.get(mode_key, DEFAULT_PALETTE)
429
+ nickname = (info.get("nickname") or "").strip() or f"(无名账号 {aid})"
430
+
431
+ card = _gradient((CARD_W, CARD_H), palette.top, palette.bottom).convert("RGBA")
432
+
433
+ # ---- 背景装饰:斜向条纹 ----
434
+ stripes = Image.new("RGBA", (CARD_W, CARD_H), (0, 0, 0, 0))
435
+ sdraw = ImageDraw.Draw(stripes)
436
+ for x in range(-CARD_H, CARD_W, 46):
437
+ sdraw.polygon(
438
+ [(x, CARD_H), (x + 22, CARD_H), (x + 22 + CARD_H, 0), (x + CARD_H, 0)],
439
+ fill=(255, 255, 255, 6),
440
+ )
441
+ card = Image.alpha_composite(card, stripes)
442
+
443
+ # 立绘区域:底边必须停在分割线之上,否则角色会压到页脚
444
+ char_box = (36, 104, 536, 592)
445
+ char_w = char_box[2] - char_box[0]
446
+ char_h = char_box[3] - char_box[1]
447
+
448
+ # 角色背后只留一团同色光晕——整个卡片已经是模式配色,不需要再铺色块
449
+ glow_rgb, glow_mask = _radial_glow((char_w, char_h), palette.glow, char_w * 0.58)
450
+ glow_layer = Image.new("RGBA", (char_w, char_h), glow_rgb + (255,))
451
+ card.paste(glow_layer, char_box[:2], glow_mask)
452
+
453
+ # ---- 角色立绘 ----
454
+ if character_png:
455
+ try:
456
+ with Image.open(io.BytesIO(character_png)) as im:
457
+ char = im.convert("RGBA")
458
+ # 等比缩放到角色区高度
459
+ scale = min(char_w / char.width, char_h / char.height)
460
+ char = char.resize(
461
+ (max(1, int(char.width * scale)), max(1, int(char.height * scale))),
462
+ Image.LANCZOS,
463
+ )
464
+ px = char_box[0] + (char_w - char.width) // 2
465
+ py = char_box[3] - char.height # 底部对齐
466
+ card.alpha_composite(char, (px, py))
467
+ except Exception as exc: # noqa: BLE001 - 没有立绘也要出卡片
468
+ logger.warning("角色立绘合成失败:%s", exc)
469
+ _draw_character_placeholder(card, faction, char_box)
470
+ else:
471
+ # 上游 imagemagic 渲染服务挂掉时会走到这里(实测 503)。
472
+ # 卡片上其余信息都还在,绝不能因此退回纯文字。
473
+ _draw_character_placeholder(card, faction, char_box)
474
+
475
+ # ⚠️ 绝不能直接 ImageDraw.Draw(card, "RGBA")。
476
+ #
477
+ # 在 RGBA 图上 ImageDraw 不会按 alpha 混合,而是把 (r,g,b,a) 原样写进
478
+ # 缓冲区;随后 convert("RGB") 丢掉 alpha,于是所有半透明
479
+ # (进度条底槽、分隔线、统计块底色、描边)都会变成实色。
480
+ #
481
+ # 正确做法:画在一张全透明图层上,最后 alpha_composite 合回去。
482
+ overlay = Image.new("RGBA", (CARD_W, CARD_H), (0, 0, 0, 0))
483
+ draw = ImageDraw.Draw(overlay)
484
+
485
+ # ---- 右侧渐隐面板,保证文字可读 ----
486
+ panel_x = 528
487
+ fade = Image.new("RGBA", (CARD_W - panel_x, CARD_H), (0, 0, 0, 0))
488
+ fpx = fade.load()
489
+ for x in range(fade.width):
490
+ alpha = int(min(210, 40 + x * 1.9))
491
+ for y in range(CARD_H):
492
+ fpx[x, y] = (5, 10, 18, alpha)
493
+ card.alpha_composite(fade, (panel_x, 0))
494
+
495
+ fx = 560 # 右栏左边界
496
+ right_w = CARD_W - fx - 44
497
+
498
+ # ---- 阵营徽章作为右栏背景水印 ----
499
+ # 必须画在所有文字之前。位置偏右下,让右上角的模式徽章和昵称保持干净。
500
+ draw_faction_watermark(
501
+ card,
502
+ faction,
503
+ box=(
504
+ CARD_W - WATERMARK_LEFT_OFFSET,
505
+ WATERMARK_TOP,
506
+ CARD_W,
507
+ WATERMARK_BOTTOM,
508
+ ),
509
+ )
510
+
511
+ # ---- 模式徽章(右上角)----
512
+ # 样式与邪教圈卡片保持一致:面板底色 + 强调色描边 + 强调色文字,
513
+ # 靠描边和字色区分模式,而不是整块填色(填色块太重,会压过昵称)
514
+ tag = MODE_TAG.get(mode_key, mode_label.upper())
515
+ badge_font = load_font(19, bold=True, override=font_bold)
516
+ bw = int(_text_width(draw, tag, badge_font)) + 36
517
+ bh = 46
518
+ bx, by = CARD_W - 44 - bw, 40
519
+ draw.rounded_rectangle(
520
+ [bx, by, bx + bw, by + bh],
521
+ radius=14,
522
+ fill=palette.panel,
523
+ outline=palette.accent,
524
+ width=2,
525
+ )
526
+ _text(draw, (bx + bw / 2, by + bh / 2), tag, badge_font, palette.accent, "mm")
527
+
528
+ # ---- 昵称 ----
529
+ y = 52
530
+ shown_name, name_font = _fit_text(
531
+ draw, nickname, right_w - 160, 54, bold=True, min_size=26
532
+ )
533
+ _text(draw, (fx, y), shown_name, name_font, palette.text)
534
+ y += 68
535
+
536
+ # ---- 等级 / 声望 ----
537
+ # 阵营不再写在这里——它由下方的徽章图标表示
538
+ meta_font = load_font(26, override=font_regular)
539
+ meta = f"等级 {level_no}"
540
+ if info.get("prestigeLevel"):
541
+ meta += f" 转生 {info['prestigeLevel']}"
542
+ _text(draw, (fx, y), meta, meta_font, palette.accent)
543
+ y += 44
544
+
545
+ # ---- 结局 ----
546
+ # 只有打通剧情线的号才有这一项;没有就完全不多占一行,老布局保持原样。
547
+ ending = ending_label(profile)
548
+ if ending:
549
+ # 这里不用 _fit_text:它不吃 font_override,会给这一行换成别的字体
550
+ end_font = load_font(23, override=font_regular)
551
+ line = f"结局 {ending}"
552
+ while len(line) > 1 and _text_width(draw, line + "…", end_font) > right_w:
553
+ line = line[:-1]
554
+ if line != f"结局 {ending}":
555
+ line += "…"
556
+ _text(draw, (fx, y), line, end_font, palette.text_dim)
557
+ y += 36
558
+
559
+ # ---- 经验与进度条 ----
560
+ exp_font = load_font(22, override=font_regular)
561
+ _text(draw, (fx, y), f"EXP {info.get('experience', 0):,}", exp_font, palette.text_dim)
562
+ y += 34
563
+
564
+ bar_w = right_w
565
+ bar_h = 14
566
+ ratio = (gained / need) if need else 0.0
567
+ ratio = max(0.0, min(1.0, ratio))
568
+ draw.rounded_rectangle(
569
+ [fx, y, fx + bar_w, y + bar_h], radius=bar_h // 2, fill=(255, 255, 255, 34)
570
+ )
571
+ if ratio > 0:
572
+ draw.rounded_rectangle(
573
+ [fx, y, fx + max(bar_h, int(bar_w * ratio)), y + bar_h],
574
+ radius=bar_h // 2,
575
+ fill=palette.accent + (255,),
576
+ )
577
+ # 与上方「EXP xxx」到进度条的间距保持一致(文字墨迹到条的净空 7px),
578
+ # 这里只留 1px 偏移,剩下的由字形上沿吃掉。
579
+ y += bar_h + 1
580
+ pct_font = load_font(20, override=font_regular)
581
+ # 右端对齐到经验条末尾,和上方进度条收在一条线上
582
+ _text(
583
+ draw,
584
+ (fx + right_w, y),
585
+ f"{gained:,} / {need:,} ({ratio:.1%})",
586
+ pct_font,
587
+ palette.text_dim,
588
+ "ra",
589
+ )
590
+ y += 40
591
+
592
+ # ---- PMC / Scav 两个统计块 ----
593
+ stats = [
594
+ ("PMC", (profile.get("pmcStats") or {}).get("eft") or {}),
595
+ ("SCAV", (profile.get("scavStats") or {}).get("eft") or {}),
596
+ ]
597
+ col_w = (right_w - 20) // 2
598
+ # 装下 5 行统计后底部还要留出呼吸空间,172 会让「最长连活」贴边
599
+ block_h = 184
600
+ for idx, (label, raw) in enumerate(stats):
601
+ s = _side_stats(raw)
602
+ x0 = fx + idx * (col_w + 20)
603
+ draw.rounded_rectangle(
604
+ [x0, y, x0 + col_w, y + block_h], radius=12, fill=palette.panel + (190,)
605
+ )
606
+ draw.rounded_rectangle(
607
+ [x0, y, x0 + col_w, y + block_h],
608
+ radius=12,
609
+ outline=palette.accent + (70,),
610
+ width=1,
611
+ )
612
+ pad = 18
613
+ _text(
614
+ draw,
615
+ (x0 + pad, y + 12),
616
+ label,
617
+ load_font(24, bold=True, override=font_bold),
618
+ palette.accent,
619
+ )
620
+ rows = [
621
+ ("场次", f"{s['raids']}"),
622
+ # 括号用半角、且只留一个空格:双空格 + 字体侧边距会看成全角括号
623
+ ("存活", f"{s['surv_rate']:.1%} ({s['survived']}/{s['raids']})"),
624
+ ("死亡", f"{s['died_rate']:.1%} ({s['died']}/{s['raids']})"),
625
+ ("K/D", "N/A" if s["kd"] is None else f"{s['kd']:.2f}"),
626
+ ("最长连活", f"{s['streak']}"),
627
+ ]
628
+ ry = y + 42
629
+ kfont = load_font(20, override=font_regular)
630
+ vfont = load_font(21, bold=True, override=font_bold)
631
+ for key, val in rows:
632
+ _text(draw, (x0 + pad, ry), key, kfont, palette.text_dim)
633
+ _text(draw, (x0 + col_w - pad, ry), val, vfont, palette.text, "ra")
634
+ ry += 25
635
+ y += block_h + 18
636
+
637
+ # ---- 成就 ----
638
+ # 可用高度:到分割线为止。分割线在 foot_y - 10,下面不能再画东西。
639
+ ach_limit_y = CARD_H - 62 - 10 - 8
640
+ if achievements:
641
+ ach_label_font = load_font(23, bold=True, override=font_bold)
642
+ ach_font = load_font(21, override=font_regular)
643
+ label = f"成就 {len(achievements)}"
644
+ label_w = int(draw.textlength(label, font=ach_label_font))
645
+ _text(draw, (fx, y), label, ach_label_font, palette.accent)
646
+
647
+ max_lines = max(1, (ach_limit_y - y) // 30)
648
+
649
+ def flow(width: int):
650
+ return _flow_text(
651
+ draw,
652
+ [n for n, _ in achievements],
653
+ ach_font,
654
+ first_width=width - label_w - 18,
655
+ full_width=width,
656
+ max_lines=max_lines,
657
+ )
658
+
659
+ lines, hidden = flow(right_w)
660
+ if hidden:
661
+ # 给结尾的省略号留出位置后重新排一遍,避免最后一行顶出右边界
662
+ lines, hidden = flow(right_w - 34)
663
+ if lines:
664
+ lines[-1] += " …"
665
+
666
+ for i, line in enumerate(lines):
667
+ lx = fx + label_w + 18 if i == 0 else fx
668
+ if i == len(lines) - 1 and y + 24 > ach_limit_y:
669
+ break # 放不下就干脆不画,绝不压分割线
670
+ _text(draw, (lx, y + 4), line, ach_font, palette.text_dim)
671
+ y += 30
672
+
673
+ # ---- 底部信息条 ----
674
+ foot_y = CARD_H - 62
675
+ draw.line([(44, foot_y - 10), (CARD_W - 44, foot_y - 10)], fill=(255, 255, 255, 40), width=1)
676
+ foot_bits = []
677
+ if hours:
678
+ foot_bits.append(f"游戏时长 {hours} 小时")
679
+ if last_active:
680
+ import datetime
681
+
682
+ foot_bits.append(f"最后活跃 {datetime.datetime.fromtimestamp(last_active):%Y-%m-%d}")
683
+ if updated_ago:
684
+ foot_bits.append(f"数据更新于 {updated_ago}")
685
+ if aid:
686
+ foot_bits.append(f"ID {aid}")
687
+ foot_font = load_font(20, override=font_regular)
688
+ _text(draw, (44, foot_y), " | ".join(foot_bits), foot_font, palette.text_dim)
689
+
690
+ # 把绘制层合回卡片,这样半透明才是真的半透明
691
+ card.alpha_composite(overlay)
692
+
693
+ out = io.BytesIO()
694
+ card.convert("RGB").save(out, format="PNG", optimize=True)
695
+ return out.getvalue()
696
+
697
+
698
+ def _side_stats(raw: Dict[str, Any]) -> Dict[str, Any]:
699
+ """和 format.py 里同名函数保持一致的口径。"""
700
+ counters = ((raw or {}).get("overAllCounters") or {}).get("Items") or []
701
+
702
+ def pick(keyword: str) -> int:
703
+ for entry in counters:
704
+ if keyword in (entry.get("Key") or ""):
705
+ return int(entry.get("Value") or 0)
706
+ return 0
707
+
708
+ raids = pick("Sessions")
709
+ survived = pick("Survived")
710
+ died = pick("Killed")
711
+ kills = pick("Kills")
712
+ return {
713
+ "raids": raids,
714
+ "survived": survived,
715
+ "died": died,
716
+ "kills": kills,
717
+ "surv_rate": survived / raids if raids else 0.0,
718
+ "died_rate": died / raids if raids else 0.0,
719
+ "kd": (kills / died) if died else None,
720
+ "streak": pick("LongestWinStreak"),
721
+ }
722
+
723
+
724
+ def available() -> bool:
725
+ """卡片功能是否可用(需要 Pillow)。"""
726
+ return True
727
+
728
+
729
+ # ------------------------------------------------------------ 邪教圈卡片
730
+
731
+
732
+ def _text_width(draw: ImageDraw.ImageDraw, s: str, font) -> float:
733
+ """兼容老版本 Pillow(没有 textlength)。"""
734
+ try:
735
+ return float(draw.textlength(s, font=font))
736
+ except Exception: # noqa: BLE001
737
+ return float(font.getbbox(s)[2])
738
+
739
+
740
+ def _truncate(draw: ImageDraw.ImageDraw, s: str, font, max_w: int) -> str:
741
+ """按像素宽度截断,超出补省略号。"""
742
+ if max_w <= 0 or _text_width(draw, s, font) <= max_w:
743
+ return s
744
+ while len(s) > 1 and _text_width(draw, s + "…", font) > max_w:
745
+ s = s[:-1]
746
+ return s + "…"
747
+
748
+
749
+ def _wrap_lines(draw, s: str, font, max_w: int, max_lines: int = 2):
750
+ """按字符折行,返回最多 max_lines 行。用于完整显示物品全名。"""
751
+ if _text_width(draw, s, font) <= max_w:
752
+ return [s]
753
+ lines, cur = [], ""
754
+ for ch in s:
755
+ if _text_width(draw, cur + ch, font) <= max_w or not cur:
756
+ cur += ch
757
+ continue
758
+ lines.append(cur)
759
+ cur = ch
760
+ if len(lines) == max_lines - 1:
761
+ break
762
+ rest = s[sum(len(x) for x in lines):]
763
+ if rest:
764
+ lines.append(_truncate(draw, rest, font, max_w) if len(lines) >= max_lines else rest)
765
+ return lines[:max_lines]
766
+
767
+
768
+ def _money(v) -> str:
769
+ try:
770
+ return format(int(v), ",")
771
+ except (TypeError, ValueError):
772
+ return str(v)
773
+
774
+
775
+ _RUB_CACHE: Dict[str, bool] = {}
776
+
777
+ # 能画 ₽ 的字体。主字体(微软雅黑等 CJK 字体)往往缺这个字形,
778
+ # 所以单独找一个只用来画符号的字体,数字仍用主字体。
779
+ _RUB_FONT_CANDIDATES = [
780
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
781
+ "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
782
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
783
+ "C:/Windows/Fonts/segoeui.ttf",
784
+ "C:/Windows/Fonts/seguisym.ttf",
785
+ "C:/Windows/Fonts/arial.ttf",
786
+ "C:/Windows/Fonts/tahoma.ttf",
787
+ ]
788
+ _money_font_cache: Dict[int, Any] = {}
789
+
790
+
791
+ def _rub_ok(font) -> bool:
792
+ """这个字体有没有 ₽(U+20BD)。拿私用区字符做对照判断是不是缺字方块。"""
793
+ key = "%s:%s" % (getattr(font, "path", "?"), getattr(font, "size", "?"))
794
+ if key not in _RUB_CACHE:
795
+ try:
796
+ # ImagingCore 不吃 .tobytes(),用 bytes() 拿原始位图
797
+ _RUB_CACHE[key] = bytes(font.getmask("₽")) != bytes(font.getmask("\ue000"))
798
+ except Exception: # noqa: BLE001 - 探测失败就当不支持
799
+ _RUB_CACHE[key] = False
800
+ return _RUB_CACHE[key]
801
+
802
+
803
+ def _rub_font(size: int):
804
+ """挑一个能画 ₽ 的字体(按字号缓存)。找不到返回 None。"""
805
+ if size in _money_font_cache:
806
+ return _money_font_cache[size]
807
+ found = None
808
+ for path in _RUB_FONT_CANDIDATES:
809
+ try:
810
+ candidate = ImageFont.truetype(path, size)
811
+ except Exception: # noqa: BLE001 - 字体不存在就试下一个
812
+ continue
813
+ if _rub_ok(candidate):
814
+ found = candidate
815
+ break
816
+ _money_font_cache[size] = found
817
+ return found
818
+
819
+
820
+ def _money_rub(v) -> str:
821
+ """卢布金额:符号在前 + 千分位。"""
822
+ return "₽" + _money(v)
823
+
824
+
825
+ # 卢布符号固定用白色,不跟随模式配色
826
+ _RUB_COLOR = (255, 255, 255)
827
+ # 符号和数字之间留一点空,贴太紧会糊成一团
828
+ _RUB_GAP = 4
829
+
830
+
831
+ def _text_rub(draw, xy, s: str, font, fill, anchor: str = "la") -> None:
832
+ """画可能含 ₽ 的金额文本。
833
+
834
+ 两件事:
835
+ 1. 主字体缺 ₽ 字形时,把符号切到备用字体上画;
836
+ 2. 符号固定白色,不跟随传进来的配色。
837
+
838
+ 按锚点先量出总宽再依次推进,所以右对齐、居中都不会错位。
839
+ """
840
+ if "₽" not in s:
841
+ _text(draw, xy, s, font, fill, anchor)
842
+ return
843
+
844
+ rub_font = font if _rub_ok(font) else _rub_font(getattr(font, "size", 20))
845
+ if rub_font is None: # 实在找不到能画 ₽ 的字体,退回文字
846
+ _text(draw, xy, s.replace("₽", "卢布 "), font, fill, anchor)
847
+ return
848
+
849
+ runs: list = []
850
+ buf = ""
851
+ for ch in s:
852
+ if ch == "₽":
853
+ if buf:
854
+ runs.append((buf, font, fill))
855
+ buf = ""
856
+ runs.append((ch, rub_font, fill))
857
+ else:
858
+ buf += ch
859
+ if buf:
860
+ runs.append((buf, font, fill))
861
+
862
+ total = sum(_text_width(draw, text, f) for text, f, _c in runs)
863
+ total += _RUB_GAP * sum(1 for text, _f, _c in runs if text == "₽")
864
+ x, y = xy
865
+ horizontal, vertical = anchor[0], anchor[1] if len(anchor) > 1 else "a"
866
+ if horizontal == "r":
867
+ x -= total
868
+ elif horizontal == "m":
869
+ x -= total / 2
870
+
871
+ # 关键:两段文字用的是不同字体,ascent 不一样。如果按「上伸部对齐」画,
872
+ # 备用字体里的 ₽ 就会整体偏上/偏下。这里统一换算成基线,再全部按基线画,
873
+ # 数字和符号才会落在同一条线上(这是 Linux 上符号跑高了的根因)。
874
+ ascent, descent = font.getmetrics()
875
+ if vertical == "a":
876
+ baseline = y + ascent
877
+ elif vertical == "m":
878
+ baseline = y + (ascent - descent) / 2
879
+ elif vertical == "s":
880
+ baseline = y
881
+ elif vertical == "b":
882
+ baseline = y - descent
883
+ else: # "t" 等不常用锚点,按上伸部近似
884
+ baseline = y + ascent
885
+
886
+ for text, f, color in runs:
887
+ _text(draw, (x, baseline), text, f, color, "ls")
888
+ x += _text_width(draw, text, f)
889
+ if text == "₽":
890
+ x += _RUB_GAP
891
+
892
+
893
+ def _mix(color, other, t: float):
894
+ """线性混色,用来从面板色里调出一层更亮的底。"""
895
+ return tuple(int(color[i] + (other[i] - color[i]) * t) for i in range(3))
896
+
897
+
898
+ def _draw_circle_single_plan(
899
+ draw, palette, row, *, left, right, font_regular, font_bold, f_head, f_small
900
+ ) -> None:
901
+ """只算一种件数时的版面:大标题 + 四个数据块 + 单件明细。
902
+
903
+ 只有一行的时候表格排版会让卡片空掉一大半,这里换成信息密度更高的版式。
904
+ """
905
+ f_name = load_font(36, bold=True, override=font_bold)
906
+ f_count = load_font(26, bold=True, override=font_bold)
907
+ f_label = load_font(19, override=font_regular)
908
+ f_value = load_font(32, bold=True, override=font_bold)
909
+ f_part = load_font(21, override=font_regular)
910
+
911
+ top, bottom = 168, 402
912
+ draw.rounded_rectangle(
913
+ [left, top, right, bottom],
914
+ radius=18,
915
+ fill=palette.panel,
916
+ outline=palette.accent,
917
+ width=2,
918
+ )
919
+
920
+ names = row.get("names") or []
921
+ if len(names) == 1:
922
+ title = names[0][0]
923
+ elif names:
924
+ title = " + ".join(n for n, _ in names[:2])
925
+ if len(names) > 2:
926
+ title += " 等 %d 种" % len(names)
927
+ else:
928
+ title = "无解"
929
+ # 全名优先:先缩字号,缩到下限仍在可用宽度内就保持单行
930
+ title, title_font = _fit_text(draw, title, right - left - 170, 36, bold=True, min_size=18)
931
+ _text(draw, (left + 32, top + 26), title, title_font, palette.text)
932
+ _text(
933
+ draw,
934
+ (right - 32, top + 34),
935
+ "×%d" % int(row.get("count") or 1),
936
+ f_count,
937
+ palette.accent,
938
+ anchor="ra",
939
+ )
940
+
941
+ inner = _mix(palette.panel, (255, 255, 255), 0.10)
942
+ stats = [
943
+ ("献祭基准", _money_rub(row.get("base")), _RUB_COLOR),
944
+ ("购买成本", _money_rub(row.get("cost")), _RUB_COLOR),
945
+ ("节省", _money_rub(row.get("saved")), _RUB_COLOR),
946
+ ("价值倍率", "%.1f×" % float(row.get("ratio") or 0.0), palette.text),
947
+ ]
948
+ gap = 16
949
+ col_w = ((right - left) - 64 - gap * 3) // 4
950
+ sy = top + 96
951
+ sh = 104
952
+ for i, (label, value, color) in enumerate(stats):
953
+ x0 = left + 32 + i * (col_w + gap)
954
+ draw.rounded_rectangle([x0, sy, x0 + col_w, sy + sh], radius=12, fill=inner)
955
+ _text(draw, (x0 + 16, sy + 12), label, f_label, palette.text_dim)
956
+ _text_rub(draw, (x0 + 16, sy + 42), value, f_value, color)
957
+
958
+ dy = bottom + 34
959
+ _text(draw, (left, dy), "单件明细", f_head, palette.text_dim)
960
+ dy += 40
961
+ for part in row.get("parts") or []:
962
+ mark = "商人" if part.get("source") == "trader" else "跳蚤"
963
+ line = "%s ×%d 基准 %s %s %s" % (
964
+ part.get("name", ""),
965
+ int(part.get("n") or 1),
966
+ _money_rub(part.get("base")),
967
+ mark,
968
+ _money_rub(part.get("cost")),
969
+ )
970
+ line = _truncate(draw, line, f_part, right - left - 20)
971
+ _text_rub(draw, (left + 24, dy), line, f_part, palette.text_dim)
972
+ dy += 34
973
+
974
+
975
+ def build_circle_card(
976
+ *,
977
+ mode_key: str,
978
+ mode_label: str,
979
+ threshold: int,
980
+ subtitle: str,
981
+ rows: List[Dict[str, Any]],
982
+ built: str = "",
983
+ font_regular: Optional[str] = None,
984
+ font_bold: Optional[str] = None,
985
+ ) -> bytes:
986
+ """邪教圈献祭推荐卡片,返回 PNG 字节。
987
+
988
+ rows 结构见 circle.summary_rows():
989
+ {"count": int, "names": [(名, 份数)], "cost": int, "base": int,
990
+ "saved": int, "ratio": float, "best": bool}
991
+ """
992
+ palette = MODE_PALETTES.get(mode_key, DEFAULT_PALETTE)
993
+ card = _gradient((CARD_W, CARD_H), palette.top, palette.bottom).convert("RGBA")
994
+
995
+ # 斜向条纹,和玩家卡片保持同一质感
996
+ stripes = Image.new("RGBA", (CARD_W, CARD_H), (0, 0, 0, 0))
997
+ sdraw = ImageDraw.Draw(stripes)
998
+ for x in range(-CARD_H, CARD_W, 46):
999
+ sdraw.polygon(
1000
+ [(x, CARD_H), (x + 22, CARD_H), (x + 22 + CARD_H, 0), (x + CARD_H, 0)],
1001
+ fill=(255, 255, 255, 6),
1002
+ )
1003
+ card = Image.alpha_composite(card, stripes)
1004
+
1005
+ # 左上角落一团同色光晕
1006
+ glow_rgb, glow_mask = _radial_glow((560, 560), palette.glow, 300)
1007
+ glow_layer = Image.new("RGBA", (560, 560), glow_rgb + (255,))
1008
+ card.paste(glow_layer, (-150, 30), glow_mask)
1009
+
1010
+ draw = ImageDraw.Draw(card)
1011
+ f_title = load_font(44, bold=True, override=font_bold)
1012
+ f_sub = load_font(21, override=font_regular)
1013
+ f_head = load_font(19, bold=True, override=font_bold)
1014
+ f_row = load_font(24, override=font_regular)
1015
+ f_num = load_font(23, bold=True, override=font_bold)
1016
+ f_small = load_font(17, override=font_regular)
1017
+
1018
+ left, right = 56, CARD_W - 56
1019
+
1020
+ _text(draw, (left, 44), "邪教圈献祭推荐", f_title, palette.text)
1021
+ _text_rub(draw, (left, 108), subtitle, f_sub, palette.text_dim)
1022
+
1023
+ tag = MODE_TAG.get(mode_key, mode_label)
1024
+ tag_w = int(_text_width(draw, tag, f_head)) + 36
1025
+ draw.rounded_rectangle(
1026
+ [right - tag_w, 42, right, 88],
1027
+ radius=14,
1028
+ fill=palette.panel,
1029
+ outline=palette.accent,
1030
+ width=2,
1031
+ )
1032
+ _text(draw, (right - tag_w / 2, 65), tag, f_head, palette.accent, anchor="mm")
1033
+
1034
+ if len(rows) == 1:
1035
+ _draw_circle_single_plan(
1036
+ draw,
1037
+ palette,
1038
+ rows[0],
1039
+ left=left,
1040
+ right=right,
1041
+ font_regular=font_regular,
1042
+ font_bold=font_bold,
1043
+ f_head=f_head,
1044
+ f_small=f_small,
1045
+ )
1046
+ else:
1047
+ # 表头
1048
+ head_y = 188
1049
+ _text(draw, (96, head_y), "件数", f_head, palette.text_dim, anchor="mm")
1050
+ _text(draw, (170, head_y), "献祭物品", f_head, palette.text_dim, anchor="lm")
1051
+ _text(draw, (900, head_y), "购买成本", f_head, palette.text_dim, anchor="rm")
1052
+ _text(draw, (1128, head_y), "节省", f_head, palette.text_dim, anchor="rm")
1053
+
1054
+ y = 232
1055
+ step = 74
1056
+ for row in rows:
1057
+ best = bool(row.get("best"))
1058
+ if best:
1059
+ draw.rounded_rectangle(
1060
+ [left - 18, y - 32, right + 18, y + 32],
1061
+ radius=16,
1062
+ fill=palette.panel,
1063
+ outline=palette.accent,
1064
+ width=2,
1065
+ )
1066
+ color = palette.accent if best else palette.text
1067
+ dim = palette.accent if best else palette.text_dim
1068
+
1069
+ _text(draw, (96, y), "%d 件" % int(row.get("count") or 0), f_row, color, anchor="mm")
1070
+
1071
+ names = row.get("names") or []
1072
+ if len(names) == 1:
1073
+ label = "%s ×%d" % (names[0][0], names[0][1])
1074
+ elif names:
1075
+ label = " + ".join("%s×%d" % (n, c) for n, c in names[:2])
1076
+ if len(names) > 2:
1077
+ label += " 等 %d 种" % len(names)
1078
+ else:
1079
+ label = "无解"
1080
+ # 名字完整显示:先缩字号,还放不下就折成两行
1081
+ name_font = f_row
1082
+ if _text_width(draw, label, name_font) > 560:
1083
+ if _text_width(draw, label, load_font(20, override=font_regular)) <= 560:
1084
+ name_font = load_font(20, override=font_regular)
1085
+ name_lines = _wrap_lines(draw, label, name_font, 560, 2)
1086
+ if len(name_lines) == 1:
1087
+ _text(draw, (170, y), name_lines[0], name_font, color, anchor="lm")
1088
+ else:
1089
+ _text(draw, (170, y - 16), name_lines[0], name_font, color, anchor="lm")
1090
+ _text(draw, (170, y + 16), name_lines[1], name_font, color, anchor="lm")
1091
+
1092
+ _text_rub(draw, (900, y), _money_rub(row.get("cost")), f_num, _RUB_COLOR, "rm")
1093
+ _text_rub(
1094
+ draw,
1095
+ (1128, y),
1096
+ "省 " + _money_rub(row.get("saved")),
1097
+ f_num,
1098
+ _RUB_COLOR,
1099
+ "rm",
1100
+ )
1101
+ y += step
1102
+
1103
+
1104
+ foot = "数据来源 tarkov.dev"
1105
+ if built:
1106
+ foot += " · 行情 " + built
1107
+ _text(draw, (left, 634), foot, f_small, palette.text_dim)
1108
+ _text(draw, (right, 634), "节省 = 基准价值 − 购买成本", f_small, palette.text_dim, anchor="ra")
1109
+
1110
+ buf = io.BytesIO()
1111
+ card.convert("RGB").save(buf, format="PNG", optimize=True)
1112
+ return buf.getvalue()