exporter.py 28 KB

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