exporter.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. """把某个 game 的产物打包成「可直接拖进 Cocos 的整合包」。
  2. 被 server.py 的 /api/export 调用,也可命令行单独跑:
  3. python exporter.py jelly-candy-slot
  4. 产物在 out/<game>/cocos-pack/ ,结构:
  5. 把素材接进Cocos-零基础教程.md
  6. assets/
  7. resources/characters/*.json|.atlas|.png
  8. resources/vfx/*.json + particle.png
  9. scripts/JellyDemo.ts ParticleConfig.ts TweenPresets.ts
  10. """
  11. import json
  12. import math
  13. import os
  14. import shutil
  15. import asset_quality
  16. HERE = os.path.dirname(os.path.abspath(__file__))
  17. def _symbol_fit_from_library(lib):
  18. slot_config = lib.get("slot_config") or {}
  19. symbol_cfg = (slot_config.get("layout") or {}).get("symbols") or {}
  20. fill = float(symbol_cfg.get("targetCellFill", 0.92) or 0.92)
  21. default_s = float(symbol_cfg.get("defaultScalePerCell", 0.00093) or 0.00093)
  22. default_oyf = float(symbol_cfg.get("defaultOriginYOffsetPerCell", 0.5) or 0.5)
  23. fits = {}
  24. symbol_ids = {s.get("id") for s in (slot_config.get("symbols") or [])}
  25. for item in lib.get("characters", []):
  26. cid = item.get("id")
  27. if symbol_ids and cid not in symbol_ids:
  28. continue
  29. w = float(item.get("w") or 0)
  30. h = float(item.get("h") or 0)
  31. if not cid or w <= 0 or h <= 0:
  32. continue
  33. max_dim = max(w, h)
  34. s = fill / max_dim
  35. if w < h * 0.72:
  36. s *= 1.12
  37. if h < w * 0.72:
  38. s *= 1.08
  39. # Spine 原点在素材底部中心,节点要下移半个实际显示高度才会视觉居中。
  40. oyf = (h * s) / 2.0
  41. fits[cid] = {"s": round(s, 6), "oyf": round(oyf, 4)}
  42. return fits, {"s": round(default_s, 6), "oyf": round(default_oyf, 4)}
  43. def _math_report_md(slot_config):
  44. model = slot_config.get("mathModel") or {}
  45. sim = model.get("simulation") or {}
  46. rng = model.get("rng") or {}
  47. reels = model.get("reelStrips") or []
  48. lines = [
  49. "# Slot Math Report",
  50. "",
  51. "This is a certification-candidate math package, not a third-party lab certificate.",
  52. "",
  53. "## Identity",
  54. f"- Game: `{slot_config.get('game', {}).get('id', '')}`",
  55. f"- Model hash: `{model.get('modelHash', '')}`",
  56. f"- Status: `{model.get('status', '')}`",
  57. "",
  58. "## RTP Summary",
  59. f"- Target RTP: `{sim.get('targetRtp', '')}`",
  60. f"- Estimated RTP: `{sim.get('estimatedRtp', '')}`",
  61. f"- Payout scale: `{model.get('payoutScale', '')}`",
  62. f"- Hit frequency: `{sim.get('hitFrequency', '')}`",
  63. f"- Std dev per spin: `{sim.get('stdDevPerSpin', '')}`",
  64. f"- Base spins: `{sim.get('baseSpins', '')}`",
  65. f"- Total resolved spins: `{sim.get('totalResolvedSpins', '')}`",
  66. "",
  67. "## RNG",
  68. f"- Simulation RNG: `{rng.get('algorithm', '')}`",
  69. f"- Seed: `{rng.get('seed', '')}`",
  70. f"- Production requirement: `{rng.get('productionRequirement', '')}`",
  71. "",
  72. "## Reel Strips",
  73. ]
  74. for i, reel in enumerate(reels):
  75. lines.append(f"- Reel {i + 1} ({len(reel)} stops): `{','.join(reel)}`")
  76. lines.extend([
  77. "",
  78. "## Required Before Real Certification",
  79. "- Freeze source code and generated math config.",
  80. "- Replace prototype random calls with approved production RNG integration.",
  81. "- Run lab-required long simulation volume and edge-case tests.",
  82. "- Submit PAR sheet, reel strips, paytable, feature rules, RNG proof, and game binary.",
  83. ])
  84. return "\n".join(lines) + "\n"
  85. def _image_alpha_stats(path):
  86. try:
  87. from PIL import Image
  88. with Image.open(path) as img:
  89. rgba = img.convert("RGBA")
  90. alpha = rgba.getchannel("A")
  91. bbox = alpha.getbbox()
  92. if not bbox:
  93. return {"ok": False, "reason": "empty_alpha", "size": rgba.size}
  94. pix = list(alpha.getdata())
  95. transparent = sum(1 for v in pix if v == 0)
  96. opaque = sum(1 for v in pix if v > 16)
  97. area = rgba.width * rgba.height
  98. return {
  99. "ok": True,
  100. "size": rgba.size,
  101. "bbox": bbox,
  102. "transparentRatio": round(transparent / max(1, area), 4),
  103. "opaqueRatio": round(opaque / max(1, area), 4),
  104. "bboxRatio": round(((bbox[2] - bbox[0]) * (bbox[3] - bbox[1])) / max(1, area), 4),
  105. }
  106. except Exception as e:
  107. return {"ok": False, "reason": str(e), "size": [0, 0]}
  108. def _qa_add(report, level, code, message, target="", suggestion=""):
  109. report["items"].append({
  110. "level": level,
  111. "code": code,
  112. "target": target,
  113. "message": message,
  114. "suggestion": suggestion,
  115. })
  116. def _qa_report(lib, base, slot_src):
  117. slot_config = lib.get("slot_config") or {}
  118. report = {
  119. "game": lib.get("game"),
  120. "summary": {"error": 0, "warning": 0, "info": 0},
  121. "items": [],
  122. }
  123. chars = {c.get("id"): c for c in lib.get("characters", [])}
  124. ui_art = {a.get("id"): a for a in lib.get("ui_art", [])}
  125. required_art = ["bg_main", "logo", "reel_frame", "btn_spin", "hud_pill"]
  126. for aid in required_art:
  127. path = os.path.join(base, "ui_art", f"{aid}.png")
  128. if aid not in ui_art or not os.path.isfile(path):
  129. _qa_add(report, "error", "missing_ui_art", f"关键 UI 资源缺失:{aid}", aid, "在 UI 美术任务卡片里补生成或重新生成。")
  130. logo_path = os.path.join(base, "ui_art", "logo.png")
  131. if os.path.isfile(logo_path):
  132. st = _image_alpha_stats(logo_path)
  133. if not st.get("ok"):
  134. _qa_add(report, "error", "bad_logo_alpha", "Logo 图片没有有效 Alpha 内容", "logo", "重新生成 logo。")
  135. elif st["opaqueRatio"] < 0.03:
  136. _qa_add(report, "warning", "logo_too_empty", "Logo 有效像素很少,可能是空框或文字缺失。", "logo", "重新生成 logo,并要求真实可读标题文字。")
  137. frame_path = os.path.join(base, "ui_art", "reel_frame.png")
  138. if os.path.isfile(frame_path):
  139. st = _image_alpha_stats(frame_path)
  140. if st.get("ok") and st["transparentRatio"] < 0.25:
  141. _qa_add(report, "warning", "reel_frame_not_hollow", "卷轴框透明区域偏少,可能不是空心框。", "reel_frame", "重新生成空心透明中心的 reel_frame。")
  142. boss = slot_config.get("boss") or {}
  143. if boss.get("enabled"):
  144. boss_id = boss.get("id") or "boss_demon_lord"
  145. row = chars.get(boss_id)
  146. if not row:
  147. _qa_add(report, "error", "missing_boss", f"关主资源缺失:{boss_id}", boss_id, "在角色库补生成关主。")
  148. else:
  149. preview = row.get("preview")
  150. if not preview or not os.path.isfile(os.path.join(base, preview)):
  151. _qa_add(report, "error", "missing_boss_preview", "关主缺少完整预览图,页面会误把 atlas 当角色。", boss_id, "重新生成关主,或让系统补完整 preview。")
  152. else:
  153. ok, reason, detail = asset_quality.boss_preview_quality(os.path.join(base, preview))
  154. if not ok:
  155. _qa_add(
  156. report,
  157. "error",
  158. "bad_boss_preview",
  159. f"关主预览不可用:{reason}",
  160. boss_id,
  161. f"重新生成完整关主预览;当前最大主体占比 {detail.get('largestShare', 0):.0%},明显分离大块 {len(detail.get('significantComponents', []))} 个。",
  162. )
  163. if row.get("type") != "spine_parts":
  164. _qa_add(report, "warning", "boss_not_parts", "关主不是 spine_parts,爆炸拆件动作会受限。", boss_id, "重新生成关主拆件。")
  165. for part in row.get("parts") or []:
  166. pfile = part.get("file", "")
  167. ppath = os.path.join(base, pfile)
  168. if not pfile or not os.path.isfile(ppath):
  169. _qa_add(report, "error", "missing_boss_part", f"关主拆件缺失:{part.get('id', '')}", boss_id, "重新生成关主拆件。")
  170. continue
  171. ok, reason, detail = asset_quality.boss_part_quality(part.get("id", ""), ppath)
  172. if not ok:
  173. _qa_add(
  174. report,
  175. "error",
  176. "bad_boss_part",
  177. f"关主拆件 {part.get('id', '')} 不可用:{reason}",
  178. boss_id,
  179. f"重新生成或重切关主拆件;最大主体 {detail.get('largestShare', 0):.0%},第二主体 {detail.get('secondShare', 0):.0%}。",
  180. )
  181. theme = (slot_config.get("theme") or {}).get("key", "")
  182. title = boss.get("title", "")
  183. if theme in ("jelly", "pirate_jelly") and ("恶魔" in title or "魔王" in title):
  184. _qa_add(report, "warning", "boss_theme_mismatch", "关主名称/设定仍偏暗黑,可能不贴合当前糖果主题。", boss_id, "点击重新生成,使用主题化 boss prompt。")
  185. layout = slot_config.get("layout") or {}
  186. reel = layout.get("reel") or {}
  187. rows = int(reel.get("rows") or 0)
  188. cols = int(reel.get("cols") or 0)
  189. if rows and cols and rows <= 3:
  190. _qa_add(report, "info", "compact_reel_layout", "低行数盘面已使用紧凑布局,避免中间空行过大。", "SlotGame.ts")
  191. if "fillColor = new Color(255, 255, 255, 0)" not in slot_src:
  192. _qa_add(report, "warning", "symbol_card_background", "符号格子仍可能有白色底板。", "SlotGame.ts", "检查 buildGrid,格子底板应为透明或极弱描边。")
  193. if "BOSS_CONFIG.logoSide" not in slot_src:
  194. _qa_add(report, "warning", "boss_logo_position", "关主没有按 logo 旁边定位,可能挤进盘面。", "SlotGame.ts", "检查 buildBoss 的位置。")
  195. for item in report["items"]:
  196. report["summary"][item["level"]] += 1
  197. return report
  198. def _qa_report_md(report):
  199. lines = [
  200. "# Asset QA Report",
  201. "",
  202. f"- Game: `{report.get('game')}`",
  203. f"- Errors: `{report['summary']['error']}`",
  204. f"- Warnings: `{report['summary']['warning']}`",
  205. f"- Info: `{report['summary']['info']}`",
  206. "",
  207. "## Findings",
  208. ]
  209. if not report["items"]:
  210. lines.append("- No QA findings.")
  211. for item in report["items"]:
  212. lines.append(
  213. f"- **{item['level'].upper()}** `{item['code']}` `{item.get('target','')}`: "
  214. f"{item['message']}" + (f" 建议:{item['suggestion']}" if item.get("suggestion") else "")
  215. )
  216. return "\n".join(lines) + "\n"
  217. # ---------------------------------------------------------------- 粒子贴图
  218. def _write_particle_png(path):
  219. """生成一张柔光圆点透明 PNG(粒子配置引用的 particle.png)。"""
  220. try:
  221. from PIL import Image
  222. except ImportError:
  223. return False
  224. S = 64
  225. im = Image.new("RGBA", (S, S), (0, 0, 0, 0))
  226. px = im.load()
  227. c = (S - 1) / 2.0
  228. r = c
  229. for y in range(S):
  230. for x in range(S):
  231. d = math.hypot(x - c, y - c) / r
  232. a = max(0.0, 1.0 - d)
  233. a = a * a
  234. px[x, y] = (255, 255, 255, int(255 * a))
  235. im.save(path)
  236. return True
  237. # ---------------------------------------------------------------- 静态脚本:ParticleConfig.ts
  238. PARTICLE_CONFIG_TS = r"""// 自动生成 by anim_studio —— 把 *.json 粒子配置应用到 Cocos ParticleSystem2D
  239. // 这个文件你不用改。
  240. import { ParticleSystem2D, Color, Vec2, SpriteFrame, gfx } from 'cc';
  241. function toBlend(gl: number): number {
  242. switch (gl) {
  243. case 0: return gfx.BlendFactor.ZERO;
  244. case 1: return gfx.BlendFactor.ONE;
  245. case 768: return gfx.BlendFactor.SRC_COLOR;
  246. case 769: return gfx.BlendFactor.ONE_MINUS_SRC_COLOR;
  247. case 770: return gfx.BlendFactor.SRC_ALPHA;
  248. case 771: return gfx.BlendFactor.ONE_MINUS_SRC_ALPHA;
  249. case 772: return gfx.BlendFactor.DST_ALPHA;
  250. case 773: return gfx.BlendFactor.ONE_MINUS_DST_ALPHA;
  251. default: return gfx.BlendFactor.ONE;
  252. }
  253. }
  254. function col(arr: number[] | undefined, def: number[]): Color {
  255. const a = arr && arr.length >= 3 ? arr : def;
  256. return new Color(a[0] | 0, a[1] | 0, a[2] | 0, a.length > 3 ? (a[3] | 0) : 255);
  257. }
  258. export function applyParticleConfig(ps: ParticleSystem2D, c: any, spriteFrame: SpriteFrame) {
  259. ps.spriteFrame = spriteFrame;
  260. ps.emitterMode = ParticleSystem2D.EmitterMode.GRAVITY;
  261. ps.duration = c.duration ?? -1;
  262. ps.totalParticles = c.totalParticles ?? 200;
  263. ps.emissionRate = c.emissionRate ?? 60;
  264. ps.life = c.life ?? 2;
  265. ps.lifeVar = c.lifeVar ?? 0;
  266. ps.angle = c.angle ?? 90;
  267. ps.angleVar = c.angleVar ?? 0;
  268. ps.speed = c.speed ?? 100;
  269. ps.speedVar = c.speedVar ?? 0;
  270. ps.gravity = new Vec2(c.gravityX ?? 0, c.gravityY ?? 0);
  271. ps.posVar = new Vec2(c.posVarX ?? 0, c.posVarY ?? 0);
  272. ps.startSize = c.startSize ?? 30;
  273. ps.startSizeVar = c.startSizeVar ?? 0;
  274. ps.endSize = c.endSize ?? -1;
  275. ps.startSpin = c.startSpin ?? 0;
  276. ps.startSpinVar = c.startSpinVar ?? 0;
  277. ps.endSpin = c.endSpin ?? 0;
  278. ps.endSpinVar = c.endSpinVar ?? 0;
  279. ps.startColor = col(c.startColor, [255, 255, 255, 255]);
  280. ps.startColorVar = col(c.startColorVar, [0, 0, 0, 0]);
  281. ps.endColor = col(c.endColor, [255, 255, 255, 0]);
  282. ps.endColorVar = col(c.endColorVar, [0, 0, 0, 0]);
  283. if (c.blendFunc) {
  284. ps.srcBlendFactor = toBlend(c.blendFunc.src);
  285. ps.dstBlendFactor = toBlend(c.blendFunc.dst);
  286. }
  287. ps.resetSystem();
  288. }
  289. """
  290. # ---------------------------------------------------------------- 模板脚本:JellyDemo.ts
  291. # __CHARACTERS__ / __VFX__ 会被替换成该 game 真实的资源 id 列表
  292. JELLY_DEMO_TS = r"""// =============================================================
  293. // JellyDemo.ts —— 一键演示:加载全部角色 + 按钮触发 WIN / 特效
  294. // by anim_studio(按本 game 的资源自动生成)
  295. // 用法:把本脚本拖到场景里一个空节点上,点播放。
  296. // =============================================================
  297. import {
  298. _decorator, Component, Node, sp, resources, JsonAsset, SpriteFrame,
  299. ParticleSystem2D, UITransform, Label, Graphics, Button, Color,
  300. view, EventTouch,
  301. } from 'cc';
  302. import { applyParticleConfig } from './ParticleConfig';
  303. // 需要 UI 动效时:import { TweenPresets } from './TweenPresets';
  304. // TweenPresets.play('scale_bounce', someNode).start();
  305. const { ccclass } = _decorator;
  306. const CHARACTERS = __CHARACTERS__;
  307. const VFX = __VFX__;
  308. const CHAR_SCALE = 0.11;
  309. @ccclass('JellyDemo')
  310. export class JellyDemo extends Component {
  311. private skeletons: sp.Skeleton[] = [];
  312. private particleTex: SpriteFrame | null = null;
  313. onLoad() {
  314. const ut = this.node.getComponent(UITransform) || this.node.addComponent(UITransform);
  315. const size = view.getVisibleSize();
  316. ut.setContentSize(size.width, size.height);
  317. this.loadParticleTexture(() => { this.buildCharacterGrid(); this.buildButtons(); });
  318. }
  319. private loadParticleTexture(done: () => void) {
  320. resources.load('vfx/particle/spriteFrame', SpriteFrame, (err, sf) => {
  321. if (!err) this.particleTex = sf;
  322. else console.warn('[JellyDemo] 粒子贴图未加载到:', err);
  323. done();
  324. });
  325. }
  326. private buildCharacterGrid() {
  327. const cols = 5, cellW = 175, cellH = 200;
  328. const rows = Math.ceil(CHARACTERS.length / cols);
  329. const startX = -((cols - 1) * cellW) / 2;
  330. const startY = ((rows - 1) * cellH) / 2 + 40;
  331. CHARACTERS.forEach((id, i) => {
  332. resources.load(`characters/${id}`, sp.SkeletonData, (err, data) => {
  333. if (err) { console.error('[JellyDemo] 角色加载失败:', id, err); return; }
  334. const node = new Node(id); node.parent = this.node;
  335. const sk = node.addComponent(sp.Skeleton);
  336. sk.skeletonData = data;
  337. sk.premultipliedAlpha = false;
  338. sk.setAnimation(0, 'idle', true);
  339. node.setScale(CHAR_SCALE, CHAR_SCALE, 1);
  340. const c = i % cols, r = Math.floor(i / cols);
  341. node.setPosition(startX + c * cellW, startY - r * cellH, 0);
  342. this.skeletons.push(sk);
  343. this.makeLabel(this.node, id, startX + c * cellW, startY - r * cellH - 70, 16);
  344. });
  345. });
  346. }
  347. private buildButtons() {
  348. const y = -view.getVisibleSize().height / 2 + 60;
  349. this.makeButton('▶ 全部 WIN', -300, y, new Color(255, 120, 60, 255), () => {
  350. this.skeletons.forEach((sk) => { sk.setAnimation(0, 'win', false); sk.addAnimation(0, 'idle', true, 0); });
  351. });
  352. VFX.forEach((id, i) => {
  353. const x = -90 + i * 165;
  354. this.makeButton(id, x, y, new Color(80, 150, 255, 255), () => this.playVfx(id));
  355. });
  356. }
  357. private playVfx(id: string) {
  358. resources.load(`vfx/${id}`, JsonAsset, (err, asset) => {
  359. if (err) { console.error('[JellyDemo] 特效配置加载失败:', id, err); return; }
  360. const node = new Node('vfx_' + id); node.parent = this.node; node.setPosition(0, 80, 0);
  361. const ps = node.addComponent(ParticleSystem2D);
  362. applyParticleConfig(ps, asset.json, this.particleTex as SpriteFrame);
  363. this.scheduleOnce(() => { ps.stopSystem(); }, 1.5);
  364. this.scheduleOnce(() => { node.destroy(); }, 5);
  365. });
  366. }
  367. private makeButton(text: string, x: number, y: number, color: Color, onClick: () => void) {
  368. const node = new Node('btn_' + text); node.parent = this.node; node.setPosition(x, y, 0);
  369. const w = 150, h = 52;
  370. const ut = node.addComponent(UITransform); ut.setContentSize(w, h);
  371. const g = node.addComponent(Graphics); g.fillColor = color;
  372. this.roundRect(g, -w / 2, -h / 2, w, h, 12); g.fill();
  373. this.makeLabel(node, text, 0, 0, 22, new Color(255, 255, 255, 255));
  374. const btn = node.addComponent(Button);
  375. btn.transition = Button.Transition.SCALE; btn.zoomScale = 0.92;
  376. node.on(Node.EventType.TOUCH_END, (_e: EventTouch) => onClick());
  377. }
  378. private makeLabel(parent: Node, text: string, x: number, y: number, size: number, color?: Color) {
  379. const n = new Node('label'); n.parent = parent; n.setPosition(x, y, 0);
  380. const lab = n.addComponent(Label);
  381. lab.string = text; lab.fontSize = size; lab.lineHeight = size + 2;
  382. lab.color = color || new Color(60, 60, 60, 255);
  383. const ps = parent.scale;
  384. if (ps.x !== 0 && ps.x !== 1) n.setScale(1 / ps.x, 1 / ps.y, 1);
  385. }
  386. private roundRect(g: Graphics, x: number, y: number, w: number, h: number, r: number) {
  387. g.moveTo(x + r, y); g.lineTo(x + w - r, y);
  388. g.arc(x + w - r, y + r, r, -Math.PI / 2, 0, false);
  389. g.lineTo(x + w, y + h - r); g.arc(x + w - r, y + h - r, r, 0, Math.PI / 2, false);
  390. g.lineTo(x + r, y + h); g.arc(x + r, y + h - r, r, Math.PI / 2, Math.PI, false);
  391. g.lineTo(x, y + r); g.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5, false); g.close();
  392. }
  393. }
  394. """
  395. # ---------------------------------------------------------------- 模板脚本:SlotGame.ts
  396. # __SYMBOLS__ 会被替换成本 game 的符号列表
  397. SLOT_GAME_TS = r"""// =============================================================
  398. // SlotGame.ts —— 果冻老虎机(可玩原型)by anim_studio(按本 game 资源生成)
  399. // 用法:把本脚本挂到 Canvas 下的一个空节点上,点播放。
  400. // =============================================================
  401. import {
  402. _decorator, Component, Node, sp, resources, JsonAsset, SpriteFrame,
  403. ParticleSystem2D, UITransform, Label, Graphics, Button, Color, Vec3,
  404. view, EventTouch, tween, profiler,
  405. } from 'cc';
  406. import { applyParticleConfig } from './ParticleConfig';
  407. const { ccclass } = _decorator;
  408. const SYMBOLS = __SYMBOLS__;
  409. const COLS = 5, ROWS = 3;
  410. const CELL = 118;
  411. const SYM_SCALE = 0.085;
  412. const BET = 50;
  413. const START_BALANCE = 1000;
  414. @ccclass('SlotGame')
  415. export class SlotGame extends Component {
  416. private dataMap: Record<string, sp.SkeletonData> = {};
  417. private cells: sp.Skeleton[][] = [];
  418. private cur: string[][] = [];
  419. private finalGrid: string[][] = [];
  420. private spinning = false;
  421. private elapsed = 0;
  422. private colStopAt: number[] = [];
  423. private colStopped: boolean[] = [];
  424. private swapTimer: number[] = [];
  425. private balance = START_BALANCE;
  426. private displayBalance = START_BALANCE;
  427. private balanceLabel!: Label;
  428. private winLabel!: Label;
  429. private spinBtn!: Node;
  430. private particleTex: SpriteFrame | null = null;
  431. private gridY = 30;
  432. private startX = -((COLS - 1) * CELL) / 2;
  433. onLoad() {
  434. profiler && profiler.hideStats();
  435. this.node.setPosition(0, 0, 0);
  436. const ut = this.node.getComponent(UITransform) || this.node.addComponent(UITransform);
  437. ut.setAnchorPoint(0.5, 0.5);
  438. const s = view.getVisibleSize();
  439. ut.setContentSize(s.width, s.height);
  440. this.buildBackground(s.width, s.height);
  441. this.buildPanel();
  442. this.buildHud(s.width, s.height);
  443. this.buildSpinButton(s.height);
  444. let left = SYMBOLS.length;
  445. resources.load('vfx/particle/spriteFrame', SpriteFrame, (_e, sf) => { if (sf) this.particleTex = sf; });
  446. SYMBOLS.forEach((id) => {
  447. resources.load(`characters/${id}`, sp.SkeletonData, (err, data) => {
  448. if (!err) this.dataMap[id] = data;
  449. if (--left === 0) this.buildGrid();
  450. });
  451. });
  452. }
  453. private buildBackground(W: number, H: number) {
  454. const n = new Node('bg'); n.parent = this.node; n.setSiblingIndex(0);
  455. const g = n.addComponent(Graphics);
  456. g.fillColor = new Color(40, 24, 64, 255);
  457. g.rect(-W / 2, -H / 2, W, H); g.fill();
  458. g.fillColor = new Color(58, 34, 92, 255);
  459. g.rect(-W / 2, H / 2 - 90, W, 90); g.fill();
  460. const t = new Node('title'); t.parent = this.node; t.setPosition(0, H / 2 - 45, 0);
  461. const lab = t.addComponent(Label);
  462. lab.string = '🍬 JELLY SLOT 🍬'; lab.fontSize = 34; lab.lineHeight = 38;
  463. lab.color = new Color(255, 235, 160, 255);
  464. }
  465. private buildPanel() {
  466. const w = COLS * CELL + 30, h = ROWS * CELL + 30;
  467. const n = new Node('panel'); n.parent = this.node; n.setPosition(0, this.gridY, 0);
  468. const g = n.addComponent(Graphics);
  469. g.fillColor = new Color(24, 14, 38, 255);
  470. this.roundRect(g, -w / 2, -h / 2, w, h, 18); g.fill();
  471. const tile = CELL - 12;
  472. for (let c = 0; c < COLS; c++) {
  473. for (let r = 0; r < ROWS; r++) {
  474. const cx = this.startX + c * CELL;
  475. const cy = (1 - r) * CELL;
  476. g.fillColor = new Color(247, 243, 252, 255);
  477. this.roundRect(g, cx - tile / 2, cy - tile / 2, tile, tile, 14); g.fill();
  478. g.lineWidth = 3; g.strokeColor = new Color(255, 205, 110, 200);
  479. this.roundRect(g, cx - tile / 2, cy - tile / 2, tile, tile, 14); g.stroke();
  480. }
  481. }
  482. g.lineWidth = 6; g.strokeColor = new Color(255, 200, 90, 255);
  483. this.roundRect(g, -w / 2, -h / 2, w, h, 18); g.stroke();
  484. }
  485. private buildHud(W: number, H: number) {
  486. const b = new Node('balance'); b.parent = this.node; b.setPosition(-W / 2 + 130, H / 2 - 130, 0);
  487. this.balanceLabel = b.addComponent(Label);
  488. this.balanceLabel.fontSize = 26; this.balanceLabel.color = new Color(180, 240, 255, 255);
  489. const w = new Node('win'); w.parent = this.node; w.setPosition(0, H / 2 - 130, 0);
  490. this.winLabel = w.addComponent(Label);
  491. this.winLabel.fontSize = 30; this.winLabel.color = new Color(255, 220, 120, 255);
  492. this.winLabel.string = '';
  493. this.refreshBalance();
  494. }
  495. private refreshBalance() { this.balanceLabel.string = `💰 ${Math.floor(this.displayBalance)}`; }
  496. private buildSpinButton(H: number) {
  497. const node = new Node('spin'); node.parent = this.node;
  498. node.setPosition(0, -H / 2 + 70, 0);
  499. const w = 210, h = 64;
  500. node.addComponent(UITransform).setContentSize(w, h);
  501. const g = node.addComponent(Graphics);
  502. g.fillColor = new Color(255, 110, 70, 255);
  503. this.roundRect(g, -w / 2, -h / 2, w, h, 16); g.fill();
  504. const ln = new Node('t'); ln.parent = node;
  505. const lab = ln.addComponent(Label);
  506. lab.string = '▶ SPIN'; lab.fontSize = 30; lab.color = new Color(255, 255, 255, 255);
  507. const btn = node.addComponent(Button);
  508. btn.transition = Button.Transition.SCALE; btn.zoomScale = 0.93;
  509. node.on(Node.EventType.TOUCH_END, (_e: EventTouch) => this.spin());
  510. this.spinBtn = node;
  511. }
  512. private buildGrid() {
  513. for (let c = 0; c < COLS; c++) {
  514. this.cells[c] = []; this.cur[c] = []; this.finalGrid[c] = [];
  515. for (let r = 0; r < ROWS; r++) {
  516. const id = this.rand();
  517. const node = new Node(`cell_${c}_${r}`); node.parent = this.node;
  518. node.setPosition(this.startX + c * CELL, this.cellY(r), 0);
  519. node.setScale(SYM_SCALE, SYM_SCALE, 1);
  520. const sk = node.addComponent(sp.Skeleton);
  521. sk.skeletonData = this.dataMap[id];
  522. sk.premultipliedAlpha = false;
  523. sk.setAnimation(0, 'idle', true);
  524. this.cells[c][r] = sk; this.cur[c][r] = id;
  525. }
  526. }
  527. }
  528. private cellY(r: number) { return this.gridY + (1 - r) * CELL; }
  529. private spin() {
  530. if (this.spinning) return;
  531. if (this.balance < BET) { this.flashWin('余额不足!'); return; }
  532. this.balance -= BET; this.displayBalance = this.balance; this.refreshBalance();
  533. this.winLabel.string = '';
  534. this.decideResult();
  535. this.spinning = true; this.elapsed = 0;
  536. for (let c = 0; c < COLS; c++) { this.colStopped[c] = false; this.colStopAt[c] = 0.6 + c * 0.28; this.swapTimer[c] = 0; }
  537. this.setSpinEnabled(false);
  538. }
  539. private decideResult() {
  540. for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++) this.finalGrid[c][r] = this.rand();
  541. if (Math.random() < 0.4) {
  542. const r = Math.floor(Math.random() * ROWS);
  543. const sym = this.rand();
  544. const len = Math.random() < 0.4 ? 4 : 3;
  545. for (let c = 0; c < len && c < COLS; c++) this.finalGrid[c][r] = sym;
  546. }
  547. }
  548. update(dt: number) {
  549. if (!this.spinning) {
  550. if (Math.abs(this.displayBalance - this.balance) > 0.5) {
  551. this.displayBalance += (this.balance - this.displayBalance) * Math.min(1, dt * 6);
  552. this.refreshBalance();
  553. }
  554. return;
  555. }
  556. this.elapsed += dt;
  557. let allStopped = true;
  558. for (let c = 0; c < COLS; c++) {
  559. if (this.colStopped[c]) continue;
  560. if (this.elapsed >= this.colStopAt[c]) {
  561. for (let r = 0; r < ROWS; r++) this.setSymbol(c, r, this.finalGrid[c][r]);
  562. this.colStopped[c] = true; this.popColumn(c);
  563. } else {
  564. this.swapTimer[c] -= dt;
  565. if (this.swapTimer[c] <= 0) { this.swapTimer[c] = 0.06; for (let r = 0; r < ROWS; r++) this.setSymbol(c, r, this.rand()); }
  566. allStopped = false;
  567. }
  568. }
  569. if (allStopped) { this.spinning = false; this.evaluate(); this.setSpinEnabled(true); }
  570. }
  571. private setSymbol(c: number, r: number, id: string) {
  572. const sk = this.cells[c][r];
  573. if (this.cur[c][r] !== id) { sk.skeletonData = this.dataMap[id]; sk.premultipliedAlpha = false; this.cur[c][r] = id; }
  574. sk.setAnimation(0, 'idle', true);
  575. }
  576. private popColumn(c: number) {
  577. for (let r = 0; r < ROWS; r++) {
  578. const n = this.cells[c][r].node;
  579. n.setScale(SYM_SCALE * 1.25, SYM_SCALE * 1.25, 1);
  580. tween(n).to(0.12, { scale: new Vec3(SYM_SCALE, SYM_SCALE, 1) }, { easing: 'backOut' }).start();
  581. }
  582. }
  583. private evaluate() {
  584. let totalWin = 0; const winners: sp.Skeleton[] = [];
  585. for (let r = 0; r < ROWS; r++) {
  586. const first = this.finalGrid[0][r]; let count = 1;
  587. while (count < COLS && this.finalGrid[count][r] === first) count++;
  588. if (count >= 3) {
  589. totalWin += BET * (count - 2) * 2;
  590. for (let c = 0; c < count; c++) winners.push(this.cells[c][r]);
  591. }
  592. }
  593. if (totalWin > 0) {
  594. this.balance += totalWin; this.flashWin(`WIN +${totalWin}`);
  595. winners.forEach((sk) => { sk.setAnimation(0, 'win', false); sk.addAnimation(0, 'idle', true, 0); });
  596. this.playCoinRain();
  597. } else { this.winLabel.string = ''; }
  598. }
  599. private flashWin(text: string) {
  600. this.winLabel.string = text;
  601. const n = this.winLabel.node; n.setScale(0.6, 0.6, 1);
  602. tween(n).to(0.35, { scale: new Vec3(1, 1, 1) }, { easing: 'elasticOut' }).start();
  603. }
  604. private playCoinRain() {
  605. resources.load('vfx/coin_rain', JsonAsset, (err, asset) => {
  606. if (err) return;
  607. const n = new Node('coins'); n.parent = this.node; n.setPosition(0, 120, 0);
  608. const ps = n.addComponent(ParticleSystem2D);
  609. applyParticleConfig(ps, asset.json, this.particleTex as SpriteFrame);
  610. this.scheduleOnce(() => ps.stopSystem(), 1.6);
  611. this.scheduleOnce(() => n.destroy(), 5);
  612. });
  613. }
  614. private rand() { return SYMBOLS[Math.floor(Math.random() * SYMBOLS.length)]; }
  615. private setSpinEnabled(on: boolean) {
  616. const btn = this.spinBtn.getComponent(Button); if (btn) btn.interactable = on;
  617. this.spinBtn.getChildByName('t')!.getComponent(Label)!.string = on ? '▶ SPIN' : '转动中…';
  618. }
  619. private roundRect(g: Graphics, x: number, y: number, w: number, h: number, r: number) {
  620. g.moveTo(x + r, y); g.lineTo(x + w - r, y);
  621. g.arc(x + w - r, y + r, r, -Math.PI / 2, 0, false);
  622. g.lineTo(x + w, y + h - r); g.arc(x + w - r, y + h - r, r, 0, Math.PI / 2, false);
  623. g.lineTo(x + r, y + h); g.arc(x + r, y + h - r, r, Math.PI / 2, Math.PI, false);
  624. g.lineTo(x, y + r); g.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5, false); g.close();
  625. }
  626. }
  627. """
  628. # ---------------------------------------------------------------- 教程
  629. def _tutorial_md(game):
  630. return f"""# 把「{game}」素材接进 Cocos —— 零基础教程
  631. 这个文件夹是你点「导出 Cocos 整合包」自动生成的,可以直接进 Cocos Creator。
  632. 全程不用写代码:装软件 → 新建项目 → 拖文件 → 挂一个脚本 → 点播放。
  633. ## 包里有什么
  634. ```
  635. cocos-pack/
  636. ├─ 本教程.md
  637. └─ assets/ ← 整个拖进 Cocos
  638. ├─ resources/characters/ 角色三件套(.json/.atlas/.png)
  639. ├─ resources/vfx/ 粒子配置 .json + particle.png
  640. └─ scripts/ JellyDemo.ts / ParticleConfig.ts / TweenPresets.ts
  641. ```
  642. > `resources` 文件夹名不能改,Cocos 靠它动态加载资源。
  643. ## 步骤
  644. 1. 装 **Cocos Creator 3.8.x**:https://www.cocos.com/creator-download
  645. 2. 新建一个 **空项目(Empty / 2D)** 并打开。
  646. 3. 把本包 `assets/` 里的 **resources、scripts 两个文件夹**一起拖进 Cocos 资源管理器的 `assets` 上,等导入进度条走完。
  647. 4. 在 `assets` 右键 → 新建 Scene,双击打开;确保有个 **Canvas** 节点,在它下面新建一个**空节点**。
  648. 5. 把 `scripts/JellyDemo.ts` 拖到那个空节点的属性检查器上(或「添加组件 → JellyDemo」)。
  649. 6. 点正上方 **▶ 播放**:角色排队果冻抖动,底部按钮可触发「全部 WIN」和各粒子特效。
  650. ## 常见问题
  651. - 角色没出来:多半素材没导完或 resources 被改名;确认能在资源管理器把角色展开成 SkeletonData。
  652. - 角色发黑/白边:脚本已设 premultipliedAlpha=false;仍有则在贴图设置关掉 PremultiplyAlpha 重新导入。
  653. - 太大/太小:改 `JellyDemo.ts` 顶部 `CHAR_SCALE`。
  654. - 特效看不见:确认 `resources/vfx/particle.png` 在。
  655. """
  656. # ---------------------------------------------------------------- 主函数
  657. def export(game, out_root, log=print):
  658. base = os.path.join(out_root, game)
  659. if not os.path.isfile(os.path.join(base, "library.json")):
  660. raise FileNotFoundError(f"找不到 game「{game}」的 library.json")
  661. lib = json.load(open(os.path.join(base, "library.json"), encoding="utf-8"))
  662. boss = lib.get("slot_config", {}).get("boss", {})
  663. if boss.get("enabled"):
  664. boss_id = boss.get("id") or "boss_demon_lord"
  665. lib_char_ids = {c.get("id") for c in lib.get("characters", [])}
  666. missing_files = [
  667. f"characters/{boss_id}.{ext}"
  668. for ext in ("json", "atlas", "png")
  669. if not os.path.isfile(os.path.join(base, "characters", f"{boss_id}.{ext}"))
  670. ]
  671. if boss_id not in lib_char_ids or missing_files:
  672. raise RuntimeError(
  673. f"当前资源库缺少关主大魔王资源:{boss_id}。请先在角色库任务卡片里补生成该资源,"
  674. "成功后才会包含 idle/watch/coin_throw/taunt/stomp/explode 等动作。"
  675. )
  676. pack = os.path.join(base, "cocos-pack")
  677. if os.path.exists(pack):
  678. shutil.rmtree(pack)
  679. res_ch = os.path.join(pack, "assets", "resources", "characters")
  680. res_vfx = os.path.join(pack, "assets", "resources", "vfx")
  681. scripts = os.path.join(pack, "assets", "scripts")
  682. for d in (res_ch, res_vfx, scripts):
  683. os.makedirs(d, exist_ok=True)
  684. # 角色三件套
  685. char_ids = []
  686. src_ch = os.path.join(base, "characters")
  687. if os.path.isdir(src_ch):
  688. for f in sorted(os.listdir(src_ch)):
  689. src_path = os.path.join(src_ch, f)
  690. dst_path = os.path.join(res_ch, f)
  691. if os.path.isdir(src_path):
  692. shutil.copytree(src_path, dst_path, dirs_exist_ok=True)
  693. continue
  694. shutil.copy2(src_path, dst_path)
  695. if f.endswith(".json"):
  696. char_ids.append(f[:-5])
  697. log(f"📦 角色 {len(char_ids)} 个")
  698. # 粒子配置:去掉 .particle 后缀,路径更干净
  699. vfx_ids = []
  700. src_vfx = os.path.join(base, "vfx")
  701. if os.path.isdir(src_vfx):
  702. for f in sorted(os.listdir(src_vfx)):
  703. if f.endswith(".particle.json"):
  704. vid = f[: -len(".particle.json")]
  705. shutil.copy2(os.path.join(src_vfx, f), os.path.join(res_vfx, vid + ".json"))
  706. vfx_ids.append(vid)
  707. elif f.endswith(".json"):
  708. shutil.copy2(os.path.join(src_vfx, f), os.path.join(res_vfx, f))
  709. vfx_ids.append(f[:-5])
  710. log(f"📦 特效 {len(vfx_ids)} 个")
  711. # UI 美术(背景 / 外框 / 按钮 / Logo 等整图)
  712. src_art = os.path.join(base, "ui_art")
  713. art_ids = []
  714. if os.path.isdir(src_art):
  715. res_art = os.path.join(pack, "assets", "resources", "ui_art")
  716. os.makedirs(res_art, exist_ok=True)
  717. for f in sorted(os.listdir(src_art)):
  718. if f.endswith(".png"):
  719. shutil.copy2(os.path.join(src_art, f), os.path.join(res_art, f))
  720. art_ids.append(f[:-4])
  721. log(f"📦 UI 美术 {len(art_ids)} 张" if art_ids else "📦 无 UI 美术")
  722. # 粒子贴图
  723. if _write_particle_png(os.path.join(res_vfx, "particle.png")):
  724. log("📦 粒子贴图 particle.png 已生成")
  725. else:
  726. log("⚠️ 未装 Pillow,未能生成 particle.png(特效会发射但看不见)")
  727. # 脚本
  728. demo = (JELLY_DEMO_TS
  729. .replace("__CHARACTERS__", json.dumps(char_ids, ensure_ascii=False))
  730. .replace("__VFX__", json.dumps(vfx_ids, ensure_ascii=False)))
  731. open(os.path.join(scripts, "JellyDemo.ts"), "w", encoding="utf-8").write(demo)
  732. open(os.path.join(scripts, "ParticleConfig.ts"), "w", encoding="utf-8").write(PARTICLE_CONFIG_TS)
  733. slot_tmpl = os.path.join(HERE, "templates", "SlotGame.ts")
  734. slot_src = open(slot_tmpl, encoding="utf-8").read() if os.path.isfile(slot_tmpl) else SLOT_GAME_TS
  735. slot_config = lib.get("slot_config") or {}
  736. configured_symbols = [s.get("id") for s in (slot_config.get("symbols") or []) if s.get("id")]
  737. slot_symbol_ids = [sid for sid in configured_symbols if sid in char_ids] or char_ids
  738. symbol_fit, symbol_fit_default = _symbol_fit_from_library(lib)
  739. game_config_ts = (
  740. "export const SLOT_CONFIG = "
  741. + json.dumps(slot_config, ensure_ascii=False, indent=2)
  742. + " as const;\n"
  743. + "export const SYMBOLS = "
  744. + json.dumps(slot_symbol_ids, ensure_ascii=False, indent=2)
  745. + " as const;\n"
  746. + "export const SYMBOL_FIT = "
  747. + json.dumps(symbol_fit, ensure_ascii=False, indent=2)
  748. + " as const;\n"
  749. )
  750. open(os.path.join(scripts, "GameConfig.ts"), "w", encoding="utf-8").write(game_config_ts)
  751. open(os.path.join(pack, "SlotMathReport.md"), "w", encoding="utf-8").write(_math_report_md(slot_config))
  752. slot = (slot_src
  753. .replace("__SYMBOLS__", json.dumps(slot_symbol_ids, ensure_ascii=False))
  754. .replace("__GAME_CONFIG__", json.dumps(slot_config, ensure_ascii=False))
  755. .replace("__SYMBOL_FIT__", json.dumps(symbol_fit, ensure_ascii=False))
  756. .replace("__SYMBOL_FIT_DEFAULT__", json.dumps(symbol_fit_default, ensure_ascii=False)))
  757. open(os.path.join(scripts, "SlotGame.ts"), "w", encoding="utf-8").write(slot)
  758. qa = _qa_report(lib, base, slot_src)
  759. open(os.path.join(pack, "QAReport.json"), "w", encoding="utf-8").write(
  760. json.dumps(qa, ensure_ascii=False, indent=2)
  761. )
  762. open(os.path.join(pack, "QAReport.md"), "w", encoding="utf-8").write(_qa_report_md(qa))
  763. if qa["summary"]["error"] or qa["summary"]["warning"]:
  764. log(f"🧪 QA:{qa['summary']['error']} 个错误,{qa['summary']['warning']} 个警告;详见 QAReport.md")
  765. for item in qa["items"][:6]:
  766. if item["level"] in ("error", "warning"):
  767. log(f"🧪 [{item['level']}] {item['target']} · {item['message']}")
  768. if qa["summary"]["error"]:
  769. raise RuntimeError(f"导出 QA 未通过:{qa['summary']['error']} 个错误。请查看 {os.path.join(pack, 'QAReport.md')}")
  770. else:
  771. log("🧪 QA:通过,未发现错误或警告")
  772. src_tween = os.path.join(base, "ui", "TweenPresets.ts")
  773. if os.path.isfile(src_tween):
  774. shutil.copy2(src_tween, os.path.join(scripts, "TweenPresets.ts"))
  775. log("📦 脚本 JellyDemo.ts / SlotGame.ts / GameConfig.ts / ParticleConfig.ts / TweenPresets.ts 已写入")
  776. # 教程
  777. open(os.path.join(pack, "把素材接进Cocos-零基础教程.md"), "w",
  778. encoding="utf-8").write(_tutorial_md(game))
  779. log(f"✅ 整合包完成:out/{game}/cocos-pack/")
  780. return pack
  781. if __name__ == "__main__":
  782. import sys
  783. g = sys.argv[1] if len(sys.argv) > 1 else "game"
  784. export(g, os.path.join(HERE, "out"))