exporter.py 29 KB

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