board_play.dart 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'dart:math';
  4. import 'dart:ui' as ui;
  5. import 'package:flutter/material.dart';
  6. import 'package:flutter/services.dart';
  7. import 'package:fluttertoast/fluttertoast.dart';
  8. import 'package:logging/logging.dart';
  9. import 'package:provider/provider.dart';
  10. import 'package:puzzleweave/audio/jc_audio_controller.dart';
  11. import 'package:puzzleweave/config/device.dart';
  12. import 'package:puzzleweave/firebase/adjust_helper.dart';
  13. import 'package:puzzleweave/firebase/firebase_helper.dart';
  14. import 'package:puzzleweave/l10n/app_localizations.dart';
  15. import 'package:puzzleweave/models/data.dart';
  16. import 'package:puzzleweave/models/download.dart';
  17. import 'package:puzzleweave/models/items.dart';
  18. import 'package:puzzleweave/persistence/persistence.dart';
  19. import 'package:puzzleweave/play/board.dart';
  20. import 'package:puzzleweave/play/board_painter.dart';
  21. import 'package:puzzleweave/play/confetti_layer.dart';
  22. import 'package:puzzleweave/play/overlayer.dart';
  23. import 'package:puzzleweave/play/piece.dart';
  24. import 'package:puzzleweave/rating/rating_helper.dart';
  25. import 'package:puzzleweave/rating/rating_utils.dart';
  26. import 'package:puzzleweave/settings/settings_controller.dart';
  27. import 'package:puzzleweave/settings/settings_dialog.dart';
  28. import 'package:puzzleweave/skin/skin.dart';
  29. import 'package:puzzleweave/statistics/statistics.dart';
  30. import 'package:puzzleweave/utils/mybutton.dart';
  31. import 'package:puzzleweave/utils/utils.dart';
  32. import 'package:vector_math/vector_math.dart' as vmath;
  33. import 'package:vibration/vibration.dart';
  34. import '../ads/ads_state.dart';
  35. final Logger _log = Logger('board_play.dart');
  36. // 移动类型 (不再需要,但保留枚举以防止其他文件引用报错)
  37. enum MoveType {
  38. group, // 整个群组一起移动
  39. single, // 单个碎片移动
  40. }
  41. // 操作类型
  42. enum Action {
  43. revert, // 回归
  44. swap, // 交换
  45. }
  46. class BoardPlay extends StatefulWidget {
  47. final ListItem item;
  48. final bool firstRun;
  49. final bool reset;
  50. final String tag;
  51. const BoardPlay({super.key, required this.item, this.firstRun = false, this.reset = false, this.tag = 'home'});
  52. @override
  53. State<StatefulWidget> createState() {
  54. return _BoardPlayState();
  55. }
  56. static PageRouteBuilder buildRoute(ListItem item, {bool firstRun = false, bool reset = false}) {
  57. return PageRouteBuilder(
  58. pageBuilder: (context, animation, secondaryAnimation) {
  59. return BoardPlay(item: item, firstRun: firstRun, reset: reset);
  60. },
  61. transitionsBuilder: (context, animation, secondaryAnimation, child) {
  62. return FadeTransition(opacity: animation, child: child);
  63. // return SlideTransition(
  64. // position: Tween(begin: const Offset(1, 0), end: Offset.zero).animate(animation),
  65. // child: child,
  66. // );
  67. },
  68. );
  69. }
  70. }
  71. class _BoardPlayState extends AdsState<BoardPlay> with TickerProviderStateMixin {
  72. final GlobalKey boardKey = GlobalKey();
  73. Board? board;
  74. bool _isLoading = true;
  75. int progress = 0;
  76. bool isDownloadSlow = false;
  77. late Timer timer;
  78. late ItemLoader itemLoader;
  79. // late AudioController audio;
  80. late JcAudioController audio;
  81. late Data data;
  82. late SettingsController settings;
  83. late ConfettiLayer confettiLayer;
  84. ui.Image? _fingerImage; // 手指形状图片,用于制作引导动画
  85. OverLayer? _overLayer; // 用于展示手势指引的layer层,采用OverlayEntry方案,置于顶层
  86. Piece? _draggingPiece;
  87. // 记录所有动画中的移动项 (位移/交换/归位)
  88. List<MoveItem>? moveItems;
  89. // 动画控制器
  90. late AnimationController _moveAnimationController; // 移动动画(位移)
  91. late AnimationController _mergeAnimationController; // merge动画(scale)
  92. // merge 动画的缩放值
  93. late Animation<double> _mergeScaleAnimation;
  94. List<PieceGroup>? _mergeGroups; // 记录当前merge的group
  95. bool showDealing = true; // 是否需要发牌
  96. late AnimationController _prepareAnimationController; // 预备动画, Opacity透明动画展示核心绘制区
  97. late AnimationController dealingAnimationController; // 发牌动画
  98. late AnimationController flipAnimationController; // 翻牌动画
  99. // 发牌动画相关
  100. late Animation<double> _dealingAnimation;
  101. // 发牌动画参数
  102. // 发牌间隔(ms)
  103. int get _dealingPieceInterval {
  104. if (board!.rows <= 3) return 120;
  105. if (board!.rows == 4) return 100;
  106. if (board!.rows == 5) return 80;
  107. if (board!.rows == 6) return 60;
  108. return 50;
  109. }
  110. // 每个卡片移动时间(ms)
  111. int get _dealingPieceDuration {
  112. if (board!.rows <= 3) return 500;
  113. if (board!.rows == 4) return 400;
  114. if (board!.rows == 5) return 300;
  115. if (board!.rows == 6) return 200;
  116. return 100;
  117. }
  118. // 发牌动画总时长
  119. int get _totalDealingDuration => (board!.pieces.length - 1) * _dealingPieceInterval + _dealingPieceDuration; // 发牌动画总时长(ms)
  120. Timer? _dealingPeriodicTimer;
  121. int _dealingCount = 0; // 计数:记录执行次数
  122. // 成功动画控制器
  123. late AnimationController _successAnimationController;
  124. late Animation<double> _offsetAnimation; // 用于控制核心绘制区上移
  125. late Animation<double> _bottomSlideAnimation; // 用于控制next按钮从屏幕下方移动上来
  126. late Animation<double> _topSlideAnimation; // 用于控制通关banner从屏幕上方移动上来
  127. // Hard Mode Banner 动画控制器
  128. late AnimationController _hardModeBannerController;
  129. // 缩放动画
  130. late Animation<double> _bannerScaleAnimation;
  131. // 透明度动画
  132. late Animation<double> _bannerFadeAnimation;
  133. // 是否显示 Hard Mode Banner 的标志
  134. bool _showHardModeBanner = false;
  135. @override
  136. initState() {
  137. super.initState();
  138. itemLoader = ItemLoader.load(widget.item);
  139. _onProgressUpdate();
  140. itemLoader.progress.addListener(_onProgressUpdate);
  141. timer = Timer(const Duration(seconds: 5), () {
  142. if (mounted && progress < 50) {
  143. if (progress <= 1) {
  144. //啥都没下载到, 直接弹toast然后退出
  145. Fluttertoast.showToast(
  146. msg: AppLocalizations.of(context)!.networkNotGood,
  147. toastLength: Toast.LENGTH_SHORT,
  148. gravity: ToastGravity.CENTER,
  149. timeInSecForIosWeb: 1,
  150. backgroundColor: SkinHelper.slotBorderColor,
  151. textColor: Colors.white,
  152. fontSize: 16.0,
  153. );
  154. Navigator.pop(context);
  155. } else {
  156. // 有下载只是慢
  157. setState(() {
  158. isDownloadSlow = true;
  159. });
  160. }
  161. }
  162. });
  163. Device device = context.read<Device>();
  164. // audio = context.read<AudioController>();
  165. audio = context.read<JcAudioController>();
  166. data = context.read<Data>();
  167. settings = context.read<SettingsController>();
  168. confettiLayer = ConfettiLayer(this);
  169. Future.delayed(Duration.zero, () {
  170. if (mounted) {
  171. confettiLayer.setup(context);
  172. }
  173. });
  174. // 初始化移动动画,在dragging结束松手后的swap或evert操作都需要用到移动
  175. _moveAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
  176. _moveAnimationController.addListener(_moveAnimationListener);
  177. _moveAnimationController.addStatusListener(_moveAnimationStatusListener);
  178. // 初始化 Merge 动画
  179. _mergeAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300)); // 0.4s for scale up/down
  180. _mergeAnimationController.addListener(_mergeAnimationListener);
  181. _mergeAnimationController.addStatusListener(_mergeAnimationStatusListener);
  182. // 缩放值从 1.0 -> 1.1 -> 1.0 (使用 TweenSequence 实现放大再缩小)
  183. _mergeScaleAnimation =
  184. TweenSequence<double>([
  185. TweenSequenceItem(tween: Tween<double>(begin: 1.0, end: 1.06), weight: 50),
  186. TweenSequenceItem(tween: Tween<double>(begin: 1.06, end: 1.0), weight: 50),
  187. ]).animate(
  188. // 应用曲线:用 CurvedAnimation 包装控制器
  189. CurvedAnimation(
  190. parent: _mergeAnimationController, // 动画控制器
  191. curve: Curves.easeInOut, // 曲线类型(先加速后减速)
  192. ),
  193. );
  194. _prepareAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 800));
  195. _prepareAnimationController.addListener(_prepareAnimationListener);
  196. _prepareAnimationController.addStatusListener(_prepareAnimationStatusListener);
  197. // 初始化发牌动画
  198. dealingAnimationController = AnimationController(vsync: this);
  199. _dealingAnimation = CurvedAnimation(parent: dealingAnimationController, curve: Curves.linear);
  200. dealingAnimationController.addListener(_dealingAnimationListener);
  201. dealingAnimationController.addStatusListener(_dealingAnimationStatusListener);
  202. // 初始化翻转动画
  203. flipAnimationController = AnimationController(vsync: this, duration: Duration(milliseconds: 500));
  204. flipAnimationController.addListener(_flipAnimationListener);
  205. flipAnimationController.addStatusListener(_flipAnimationStatusListener);
  206. // 初始化成功动画
  207. _successAnimationController = AnimationController(vsync: this, duration: Duration(milliseconds: 500));
  208. final deltaY = (device.targetRect.top - device.appBarHeight) / 3;
  209. _offsetAnimation = Tween<double>(begin: 0.0, end: -deltaY).animate(_successAnimationController);
  210. _bottomSlideAnimation =
  211. Tween<double>(
  212. begin: -500, // 初始在屏幕外
  213. end: device.screenSize.height - device.targetRect.bottom + deltaY - 60,
  214. ).animate(
  215. CurvedAnimation(
  216. parent: _successAnimationController,
  217. curve: Curves.easeOut, // 缓出曲线,滑入更自然
  218. ),
  219. );
  220. _topSlideAnimation =
  221. Tween<double>(
  222. begin: -200, // 初始在屏幕外
  223. end: device.targetRect.top - deltaY - 70,
  224. ).animate(
  225. CurvedAnimation(
  226. parent: _successAnimationController,
  227. curve: Curves.easeOut, // 缓出曲线,滑入更自然
  228. ),
  229. );
  230. _successAnimationController.addListener(_successAnimationListener);
  231. _successAnimationController.addStatusListener(_successAnimationStatusListener);
  232. // 初始化 Hard Mode Banner 动画
  233. _hardModeBannerController = AnimationController(vsync: this, duration: const Duration(milliseconds: 1500));
  234. // 缩放:0.0 -> 1.0 (前 40% 时间快速放大)
  235. _bannerScaleAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
  236. CurvedAnimation(
  237. parent: _hardModeBannerController,
  238. curve: const Interval(0.0, 0.4, curve: Curves.easeOut),
  239. ),
  240. );
  241. // 透明度:1.0 -> 0.0 (后 70% 时间逐渐淡出)
  242. _bannerFadeAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(
  243. CurvedAnimation(
  244. parent: _hardModeBannerController,
  245. curve: const Interval(0.3, 1.0, curve: Curves.easeIn),
  246. ),
  247. );
  248. // 监听器用于触发重绘
  249. _hardModeBannerController.addListener(() {
  250. // if (mounted) setState(() {}); // 效率较低,改用AnimatedBuilder来实现局部重绘
  251. });
  252. // 动画完成时,设置标志为 false,完全隐藏
  253. _hardModeBannerController.addStatusListener((status) {
  254. if (status == AnimationStatus.completed) {
  255. if (mounted) setState(() => _showHardModeBanner = false);
  256. }
  257. });
  258. try {
  259. _init();
  260. } catch (error) {
  261. _log.info('board init error: $error');
  262. Fluttertoast.showToast(
  263. msg: AppLocalizations.of(context)!.networkNotGood,
  264. toastLength: Toast.LENGTH_SHORT,
  265. gravity: ToastGravity.CENTER,
  266. timeInSecForIosWeb: 1,
  267. backgroundColor: SkinHelper.slotBorderColor,
  268. textColor: Colors.white,
  269. fontSize: 16.0,
  270. );
  271. Navigator.pop(context);
  272. }
  273. }
  274. _onProgressUpdate() {
  275. // progress = (downloadItem.progress.value * 100).ceil();
  276. progress = (itemLoader.progress.value * 100).ceil();
  277. _log.info('onProgressUpdate: progress=$progress');
  278. setState(() {});
  279. }
  280. // 保存状态,本来是不用保存的,竞品也没有保存
  281. void saveProgress() async {
  282. _log.info('saveProgress');
  283. // 没有完成才需要保存
  284. if (board != null && board!.isAllDone == false) {
  285. await saveJson(widget.item.jsonPath, board!.toJson());
  286. }
  287. }
  288. void _successAnimationListener() {
  289. final delta = _offsetAnimation.value;
  290. board!.finalRect = board!.targetRect.translate(0, delta);
  291. board!.invalidate();
  292. }
  293. void _successAnimationStatusListener(AnimationStatus status) async {
  294. if (status == AnimationStatus.completed) {
  295. // delay 一下,等待撒花基本消失
  296. Future.delayed(Duration(seconds: 1), () async {
  297. if (!mounted) return;
  298. // 关卡完成判断是否需要评分
  299. final bool shouldShowRateDialog = await RatingHelper.shouldShowRateDialog(data.currentLevel);
  300. if (shouldShowRateDialog) {
  301. if (mounted) {
  302. showRateDialog(context);
  303. }
  304. }
  305. });
  306. }
  307. }
  308. void _dealingAnimationListener() {
  309. if (board == null) return;
  310. // 当前动画已运行的时间(ms)
  311. final currentTime = _dealingAnimation.value * _totalDealingDuration;
  312. // 逐个更新卡片位置(最后一张不需要动)
  313. for (int i = 0; i < board!.pieces.length - 1; i++) {
  314. final piece = board!.pieces[i];
  315. final startTime = i * _dealingPieceInterval;
  316. final duration = _dealingPieceDuration;
  317. // 尚未到启动时间:保持在起点
  318. if (currentTime < startTime) {
  319. continue;
  320. }
  321. // 计算移动进度(0~1):已移动时间 / 总持续时间
  322. double progress = (currentTime - startTime) / duration;
  323. progress = progress.clamp(0.0, 1.0); // 限制进度不超过1(防止超调)
  324. // 计算当前位置(起点到终点的插值)
  325. final startTransform = board!.getBottomRightTransform();
  326. final endTransform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  327. final tween = Matrix4Tween(begin: startTransform, end: endTransform);
  328. piece.transform = tween.lerp(progress);
  329. }
  330. board!.invalidate();
  331. }
  332. // 发牌动画状态监听器
  333. void _dealingAnimationStatusListener(AnimationStatus status) {
  334. if (status == AnimationStatus.completed) {
  335. board!.resetAllPieces();
  336. board!.shuffle(ShuffleStep.flipping);
  337. flipAnimationController.forward(from: 0.0);
  338. audio.playSfx(SfxType.flip);
  339. }
  340. }
  341. // 翻转动画监听器
  342. void _flipAnimationListener() {
  343. if (board == null) return;
  344. final flipValue = flipAnimationController.value;
  345. for (final piece in board!.pieces) {
  346. // 1. 计算翻转角度(0→π,180度翻转)
  347. final angle = flipValue * pi;
  348. // 2. 获取卡片的固定目标位置(基于curRow/curCol,不依赖动态transform)
  349. final targetTranslate = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  350. // 3. 执行翻转动画(传入固定目标位置)
  351. piece.updateFlipTransform(angle, targetTranslate);
  352. }
  353. board!.invalidate();
  354. }
  355. // 翻转动画状态监听器
  356. void _flipAnimationStatusListener(AnimationStatus status) {
  357. if (status == AnimationStatus.completed) {
  358. // 翻转完成,开始游戏
  359. board!.resetAllPieces();
  360. board!.rebuildAllGroups();
  361. // 检查是否初始化就已经merge的group
  362. final mergeGroups = board!.compareAllGroups();
  363. // 有新的区块合成,执行 merge 动画,稍稍放大然后再复原
  364. if (mergeGroups.isNotEmpty) {
  365. _log.info('Merge animation start for ${mergeGroups.length} groups.');
  366. // 启动 Merge 动画
  367. _mergeGroups = mergeGroups;
  368. _mergeAnimationController.forward(from: 0.0);
  369. audio.playSfx(SfxType.pop);
  370. }
  371. board!.start();
  372. }
  373. }
  374. // 关键修正:动画监听器,只注册一次
  375. void _moveAnimationListener() {
  376. if (moveItems == null || moveItems!.isEmpty) {
  377. return;
  378. }
  379. for (var item in moveItems!) {
  380. item.move();
  381. }
  382. board!.invalidate();
  383. }
  384. void _moveAnimationStatusListener(AnimationStatus status) {
  385. if (status == AnimationStatus.completed) {
  386. // 动画完成,确保所有 piece 都在它们的最终位置(endTransform)
  387. if (moveItems != null) {
  388. bool needRebuildGroup = moveItems!.any((item) => item.action == Action.swap);
  389. // 确保所有 piece 的 transform 最终停留在 endTransform
  390. for (var item in moveItems!) {
  391. item.stop();
  392. }
  393. if (needRebuildGroup) {
  394. board!.backupAllGroups();
  395. board!.rebuildAllGroups();
  396. final mergeGroups = board!.compareAllGroups();
  397. // 有新的区块合成,执行 merge 动画,稍稍放大然后再复原
  398. if (mergeGroups.isNotEmpty) {
  399. _log.info('Merge animation start for ${mergeGroups.length} groups.');
  400. // 启动 Merge 动画
  401. _mergeGroups = mergeGroups;
  402. _mergeAnimationController.forward(from: 0.0);
  403. audio.playSfx(SfxType.pop);
  404. // 如果执行了 merge 动画,将胜利条件检查推迟到 merge 动画完成时
  405. moveItems = null;
  406. return;
  407. }
  408. }
  409. moveItems = null;
  410. }
  411. }
  412. }
  413. // 新增:Merge 动画监听器
  414. void _mergeAnimationListener() {
  415. if (_mergeGroups == null || _mergeGroups!.isEmpty || board == null) {
  416. return;
  417. }
  418. // 当前缩放值 (从 1.0 -> 1.1 -> 1.0)
  419. final double scale = _mergeScaleAnimation.value;
  420. for (var group in _mergeGroups!) {
  421. final groupCenter = group.center;
  422. for (var piece in group.pieces) {
  423. // 1. 获取碎片归位后的基础位置(纯平移)
  424. final baseTransform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  425. // 2. 计算碎片左上角到群组中心的偏移量
  426. final pieceTopLeft = Offset(baseTransform.storage[12], baseTransform.storage[13]);
  427. final offsetToCenter = groupCenter - pieceTopLeft;
  428. // 3. 创建围绕群组中心的缩放矩阵
  429. final scaleMatrix = vmath.Matrix4.identity()
  430. ..translate(offsetToCenter.dx, offsetToCenter.dy) // 移到群组中心
  431. ..scale(scale, scale, 1.0) // 缩放
  432. ..translate(-offsetToCenter.dx, -offsetToCenter.dy); // 移回原位
  433. // 4. 应用最终变换
  434. piece.transform = baseTransform * scaleMatrix;
  435. }
  436. }
  437. board!.invalidate();
  438. }
  439. // 新增:Merge 动画状态监听器
  440. void _mergeAnimationStatusListener(AnimationStatus status) {
  441. if (status == AnimationStatus.completed) {
  442. if (_mergeGroups != null && _mergeGroups!.isNotEmpty) {
  443. for (var group in _mergeGroups!) {
  444. for (var piece in group.pieces) {
  445. piece.transform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  446. }
  447. }
  448. }
  449. _mergeGroups = null;
  450. // 检查胜利条件
  451. if (board!.checkWinCondition()) {
  452. _onSuccess();
  453. }
  454. board!.invalidate();
  455. }
  456. }
  457. void _prepareAnimationListener() {
  458. board!.invalidate();
  459. }
  460. // prepare动画结束,进入洗牌动画
  461. void _prepareAnimationStatusListener(AnimationStatus status) {
  462. if (status == AnimationStatus.completed) {
  463. if (board != null && board!.hard == true) {
  464. setState(() => _showHardModeBanner = true);
  465. _hardModeBannerController.forward(from: 0.0);
  466. }
  467. board!.setAllPieceToBottomRight();
  468. board!.shuffle(ShuffleStep.dealing);
  469. dealingAnimationController.duration = Duration(milliseconds: _totalDealingDuration);
  470. dealingAnimationController.forward(from: 0.0);
  471. audio.playSfx(SfxType.card);
  472. _dealingPeriodicTimer = Timer.periodic(Duration(milliseconds: 150), (timer) {
  473. if (mounted) {
  474. _dealingCount++;
  475. if (_dealingCount >= (_totalDealingDuration / 150) - 2) {
  476. timer.cancel();
  477. } else {
  478. audio.playSfx(SfxType.card);
  479. }
  480. }
  481. });
  482. }
  483. }
  484. _onSuccess() {
  485. _log.info('success! 游戏完成!');
  486. data.workDone(widget.item);
  487. board!.success();
  488. audio.playSfx(SfxType.success);
  489. confettiLayer.play();
  490. _successAnimationController.forward(from: 0.0);
  491. setState(() {});
  492. // 数据上报
  493. FirebaseHelper.logEvent("level_done", {'id': widget.item.id, 'level': data.currentLevel});
  494. AdjustHelper.trackEvent(AdjustHelper.levelDoneToken);
  495. Statistics.postEvent({
  496. "project_id": Persistence().projectId,
  497. "user_id": Persistence().uuid,
  498. "library_name": Persistence().libraryName,
  499. "library_version": Persistence().packageVersion,
  500. "name": 'level_done',
  501. "tab_source": widget.tag,
  502. "sku_id": widget.item.id,
  503. });
  504. if (data.currentLevel == 3) {
  505. FirebaseHelper.logEvent("level_done_3", {});
  506. AdjustHelper.trackEvent(AdjustHelper.levelDone3Token);
  507. Statistics.postEvent({
  508. "project_id": Persistence().projectId,
  509. "user_id": Persistence().uuid,
  510. "library_name": Persistence().libraryName,
  511. "library_version": Persistence().packageVersion,
  512. "name": 'level_done_3',
  513. "tab_source": widget.tag,
  514. "sku_id": widget.item.id,
  515. });
  516. } else if (data.currentLevel == 10) {
  517. FirebaseHelper.logEvent("level_done_10", {});
  518. AdjustHelper.trackEvent(AdjustHelper.levelDone10Token);
  519. Statistics.postEvent({
  520. "project_id": Persistence().projectId,
  521. "user_id": Persistence().uuid,
  522. "library_name": Persistence().libraryName,
  523. "library_version": Persistence().packageVersion,
  524. "name": 'level_done_10',
  525. "tab_source": widget.tag,
  526. "sku_id": widget.item.id,
  527. });
  528. } else if (data.currentLevel == 20) {
  529. FirebaseHelper.logEvent("level_done_20", {});
  530. AdjustHelper.trackEvent(AdjustHelper.levelDone20Token);
  531. Statistics.postEvent({
  532. "project_id": Persistence().projectId,
  533. "user_id": Persistence().uuid,
  534. "library_name": Persistence().libraryName,
  535. "library_version": Persistence().packageVersion,
  536. "name": 'level_done_20',
  537. "tab_source": widget.tag,
  538. "sku_id": widget.item.id,
  539. });
  540. } else if (data.currentLevel == 30) {
  541. FirebaseHelper.logEvent("level_done_30", {});
  542. AdjustHelper.trackEvent(AdjustHelper.levelDone30Token);
  543. Statistics.postEvent({
  544. "project_id": Persistence().projectId,
  545. "user_id": Persistence().uuid,
  546. "library_name": Persistence().libraryName,
  547. "library_version": Persistence().packageVersion,
  548. "name": 'level_done_30',
  549. "tab_source": widget.tag,
  550. "sku_id": widget.item.id,
  551. });
  552. }
  553. }
  554. _init() async {
  555. Device device = context.read<Device>();
  556. setState(() {
  557. _isLoading = true;
  558. });
  559. final dpr = device.devicePixelRatio;
  560. final targetRect = device.targetRect;
  561. final bestImageSize = device.bestImageSize;
  562. final image = await itemLoader.getImageBySize(bestImageSize.width.round(), bestImageSize.height.round());
  563. // final image = await itemLoader.getImage();
  564. _log.info('imageSize: (${image.width},${image.height}), bestImageSize: ($bestImageSize)');
  565. // 加载图片,后续改为从远程服务器加载, 目前demo从本地assets读取
  566. // final ByteData data = await rootBundle.load('assets/images/test.jpeg');
  567. // final ByteData data = await rootBundle.load(widget.item.image);
  568. // final ui.Codec codec = await ui.instantiateImageCodec(
  569. // data.buffer.asUint8List(),
  570. // targetWidth: bestImageSize.width.round(),
  571. // targetHeight: bestImageSize.height.round(),
  572. // );
  573. // final ui.FrameInfo frameInfo = await codec.getNextFrame();
  574. // final image = frameInfo.image;
  575. // 加载扑克背面图片,用于制作发牌动画
  576. final Size bestCardImageSize = Size(targetRect.width * dpr / widget.item.rows, targetRect.height * dpr / widget.item.cols);
  577. final ByteData cardData = await rootBundle.load(widget.item.hard ? 'assets/images/backcard_red.png' : 'assets/images/backcard_blue.png');
  578. final ui.Codec cardCodec = await ui.instantiateImageCodec(
  579. cardData.buffer.asUint8List(),
  580. targetWidth: bestCardImageSize.width.round(),
  581. targetHeight: bestCardImageSize.height.round(),
  582. );
  583. final ui.FrameInfo cardFrameInfo = await cardCodec.getNextFrame();
  584. final cardImage = cardFrameInfo.image;
  585. // 看看有没有缓存
  586. if (widget.reset) {
  587. board = await Board.create(this, image, cardImage, widget.item.rows, widget.item.cols, widget.item.hard, targetRect, device);
  588. } else {
  589. final jsonFile = await localFile(widget.item.jsonPath);
  590. if (await jsonFile.exists()) {
  591. showDealing = false; // 恢复状态不必发牌
  592. board = await Board.restore(this, image, cardImage, widget.item.rows, widget.item.cols, widget.item.hard, targetRect, device, widget.item.jsonPath);
  593. } else {
  594. board = await Board.create(this, image, cardImage, widget.item.rows, widget.item.cols, widget.item.hard, targetRect, device);
  595. FirebaseHelper.logEvent("level_start", {'id': widget.item.id, 'level': data.currentLevel + 1});
  596. AdjustHelper.trackEvent(AdjustHelper.levelStartToken);
  597. Statistics.postEvent({
  598. "project_id": Persistence().projectId,
  599. "user_id": Persistence().uuid,
  600. "library_name": Persistence().libraryName,
  601. "library_version": Persistence().packageVersion,
  602. "name": 'level_start',
  603. "tab_source": widget.tag,
  604. "sku_id": widget.item.id,
  605. });
  606. }
  607. }
  608. board!.prepare();
  609. // 首次打开应用,需要新手指引
  610. _loadFingerImageAndSetupHint();
  611. // **修正:在调用 AnimationController 之前检查 `mounted` 状态**
  612. if (!mounted) return;
  613. if (showDealing == false) {
  614. board!.start();
  615. } else {
  616. _prepareAnimationController.forward(from: 0.0);
  617. }
  618. setState(() {
  619. _isLoading = false;
  620. });
  621. }
  622. // board_play.dart (在 _BoardPlayState 中新增)
  623. // !!! 新增:加载手势图片并设置 Overlay
  624. Future<void> _loadFingerImageAndSetupHint() async {
  625. // 仅在首次运行时或用户需要提示时才加载图片和设置 OverLayer
  626. if (!widget.firstRun) return;
  627. try {
  628. // 假设您将 fingerImage 命名为 _fingerImage
  629. _fingerImage = await loadUiImageFromAsset('assets/images/finger.png');
  630. } catch (e) {
  631. _log.severe('Failed to load assets/images/finger.png: $e');
  632. return;
  633. }
  634. if (!mounted || board == null) return;
  635. // 初始化 OverLayer
  636. _overLayer = OverLayer(board!, this);
  637. _overLayer!.setup(context);
  638. // 首次打开应用或设置开启提示时,启动自动提示计时器
  639. if (widget.firstRun) {
  640. Future.delayed(const Duration(seconds: 1), () {
  641. hint();
  642. });
  643. Future.delayed(const Duration(seconds: 3), () {
  644. if (!mounted) return;
  645. if (_overLayer != null && _overLayer!.isHinting) {
  646. Fluttertoast.showToast(
  647. msg: AppLocalizations.of(context)!.moveToComplete,
  648. toastLength: Toast.LENGTH_SHORT,
  649. gravity: ToastGravity.BOTTOM,
  650. timeInSecForIosWeb: 1,
  651. backgroundColor: SkinHelper.slotBorderColor,
  652. textColor: Colors.white,
  653. fontSize: 16.0,
  654. );
  655. }
  656. });
  657. }
  658. }
  659. hint() async {
  660. // 使用私有字段 _fingerImage, _overLayer, _hintCount
  661. if (_fingerImage == null || _overLayer == null || board == null || board!.status != BoardStatus.playing) return;
  662. double fingerSize = board!.pieceLogicalWidth / 2.5;
  663. // 固定的位置提示,因为首关我们已经编排好了, 不是随机排序
  664. final Offset centerStart = Offset(
  665. board!.targetRect.topLeft.dx + board!.pieceLogicalWidth,
  666. board!.targetRect.topLeft.dy + board!.pieceLogicalHeight * 5 / 2,
  667. );
  668. final Offset centerEnd = Offset(board!.targetRect.topLeft.dx + board!.pieceLogicalWidth, board!.targetRect.topLeft.dy + board!.pieceLogicalHeight * 3 / 2);
  669. final rectStart = Rect.fromCenter(center: centerStart, width: fingerSize, height: fingerSize);
  670. final rectEnd = Rect.fromCenter(center: centerEnd, width: fingerSize, height: fingerSize);
  671. final hintItem = HintItem(_fingerImage!, rectStart, rectEnd);
  672. _overLayer?.doHint(hintItem);
  673. }
  674. @override
  675. void didChangeDependencies() async {
  676. super.didChangeDependencies();
  677. _log.info("didChangeDependencies");
  678. }
  679. @override
  680. dispose() {
  681. _log.info('dispose');
  682. timer.cancel();
  683. itemLoader.progress.removeListener(_onProgressUpdate);
  684. _moveAnimationController.removeListener(_moveAnimationListener);
  685. _moveAnimationController.removeStatusListener(_moveAnimationStatusListener);
  686. _moveAnimationController.dispose();
  687. _mergeAnimationController.removeListener(_mergeAnimationListener);
  688. _mergeAnimationController.removeStatusListener(_mergeAnimationStatusListener);
  689. _mergeAnimationController.dispose();
  690. _prepareAnimationController.removeListener(_prepareAnimationListener);
  691. _prepareAnimationController.removeStatusListener(_prepareAnimationStatusListener);
  692. _prepareAnimationController.dispose();
  693. dealingAnimationController.removeListener(_dealingAnimationListener);
  694. dealingAnimationController.removeStatusListener(_dealingAnimationStatusListener);
  695. dealingAnimationController.dispose();
  696. flipAnimationController.removeListener(_flipAnimationListener);
  697. flipAnimationController.removeStatusListener(_flipAnimationStatusListener);
  698. flipAnimationController.dispose();
  699. _successAnimationController.removeListener(_successAnimationListener);
  700. _successAnimationController.removeStatusListener(_successAnimationStatusListener);
  701. _hardModeBannerController.dispose();
  702. _dealingPeriodicTimer?.cancel();
  703. confettiLayer.dispose();
  704. board?.dispose();
  705. _overLayer?.destroy();
  706. super.dispose();
  707. }
  708. @override
  709. onInactive() {
  710. super.onInactive();
  711. // 游戏进入后台,保存一下状态
  712. saveProgress();
  713. }
  714. /// gallery页面加载的时候,可能广告模块还没有初始化完毕
  715. Future<bool> _bannerReadyAndShouldShow() async {
  716. bool ready = await adSDKReady();
  717. return ready && shouldShowBannerAd(data.currentLevel);
  718. }
  719. void _onWillPop(bool didPop, dynamic result) async {
  720. _log.info('board play will pop, dipPop=$didPop, result=$result');
  721. if (didPop) {
  722. // 页面已经退出了
  723. } else {
  724. // 页面尚未退出
  725. Future.delayed(const Duration(milliseconds: 100)).then((_) {
  726. saveProgress();
  727. });
  728. if (!mounted) return;
  729. Navigator.of(context).pop();
  730. }
  731. }
  732. @override
  733. Widget build(BuildContext context) {
  734. Device device = context.read<Device>();
  735. return PopScope(
  736. canPop: false,
  737. onPopInvokedWithResult: _onWillPop,
  738. child: Scaffold(
  739. body: Stack(
  740. children: <Widget>[
  741. if (!_isLoading) Positioned.fill(child: _buildPuzzleCanvas(device.screenSize.width, device.screenSize.height)),
  742. if (board == null || board!.status != BoardStatus.success) Positioned(top: 0, left: 0, right: 0, child: appBar),
  743. // Positioned(top: 0, left: 0, right: 0, child: appBar),
  744. Positioned(
  745. bottom: 0,
  746. left: 0,
  747. right: 0,
  748. child: SafeArea(
  749. child: SizedBox(
  750. // 始终预留一个固定的高度,防止布局跳变
  751. height: context.read<Device>().bannerHeight,
  752. width: double.infinity,
  753. child: FutureBuilder<bool>(
  754. future: _bannerReadyAndShouldShow(),
  755. builder: (context, snapshot) {
  756. if (snapshot.hasData && snapshot.data == true) {
  757. return adBanner;
  758. }
  759. return Container(
  760. // color: Colors.grey.shade100,
  761. );
  762. },
  763. ),
  764. ),
  765. ),
  766. ),
  767. successBanner,
  768. nextButton,
  769. if (_isLoading)
  770. Positioned.fill(
  771. child: Container(
  772. color: SkinHelper.wholeBgColor,
  773. child: const Center(child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(Colors.white))),
  774. ),
  775. ),
  776. ],
  777. ),
  778. ),
  779. );
  780. }
  781. Widget get appBar => SafeArea(
  782. child: Padding(
  783. padding: const EdgeInsets.symmetric(horizontal: 30.0, vertical: 10.0),
  784. child: Row(
  785. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  786. crossAxisAlignment: CrossAxisAlignment.center,
  787. children: [
  788. // 左侧占位(保持标题居中)
  789. const SizedBox(width: 30),
  790. // 中间标题
  791. Text(
  792. board != null && board!.status == BoardStatus.success
  793. ? AppLocalizations.of(context)!.levelPass
  794. : '${AppLocalizations.of(context)!.level} ${data.currentLevel + 1}',
  795. style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w600),
  796. ),
  797. // 右侧设置按钮(30x30 圆形、深绿色背景、白色图标)
  798. SizedBox(
  799. width: 30,
  800. height: 30,
  801. child: IconButton(
  802. icon: const Icon(Icons.settings, color: Colors.white, size: 22),
  803. iconSize: 22,
  804. padding: EdgeInsets.zero, // 清除默认内边距,确保按钮尺寸准确
  805. onPressed: () {
  806. audio.playSfx(SfxType.click);
  807. saveProgress(); // 有可能会返回,保存一下进度
  808. Navigator.push(context, SettingsDialog.buildRoute(showReturn: true, showRestart: true, item: widget.item));
  809. },
  810. style: ButtonStyle(
  811. // 深绿色背景(与你之前的按钮风格一致,使用 Color(0xff26600c) 深绿色)
  812. backgroundColor: WidgetStateProperty.all(SkinHelper.slotBorderColor),
  813. // 圆形形状
  814. shape: WidgetStateProperty.all(
  815. RoundedRectangleBorder(
  816. borderRadius: BorderRadius.circular(15), // 30x30 按钮对应 15 圆角
  817. ),
  818. ),
  819. // 固定按钮尺寸(30x30)
  820. minimumSize: WidgetStateProperty.all(const Size(30, 30)),
  821. maximumSize: WidgetStateProperty.all(const Size(30, 30)),
  822. ),
  823. ),
  824. ),
  825. ],
  826. ),
  827. ),
  828. );
  829. Widget _buildPuzzleCanvas(double width, double height) {
  830. return RepaintBoundary(
  831. child: CustomPaint(
  832. painter: BoardPainter(board: board!, prepareAnimation: _prepareAnimationController),
  833. size: Size(width, height),
  834. child: GestureDetector(
  835. key: boardKey,
  836. onPanStart: _onPanStart,
  837. onPanUpdate: _onPanUpdate,
  838. onPanEnd: _onPanEnd,
  839. child: // 根据游戏状态动态显示提示动画或透明容器
  840. board != null && board!.hard && _showHardModeBanner
  841. ? _hardModeBanner
  842. : Container(color: Colors.transparent), // 非显示条件时,使用透明容器
  843. ),
  844. ),
  845. );
  846. }
  847. // 困难模式提示动画组件
  848. Widget get _hardModeBanner => Center(
  849. // 使用 AnimatedBuilder 包裹需要动画的组件
  850. child: AnimatedBuilder(
  851. animation: _hardModeBannerController, // 监听控制器
  852. builder: (context, child) {
  853. return FadeTransition(
  854. opacity: _bannerFadeAnimation, // 使用控制器驱动的动画值
  855. child: ScaleTransition(
  856. scale: _bannerScaleAnimation, // 使用控制器驱动的动画值
  857. child: child, // 不随动画重建的子组件
  858. ),
  859. );
  860. },
  861. // child 是不依赖动画状态变化的组件,只会构建一次
  862. child: Container(
  863. width: double.infinity,
  864. height: 60,
  865. margin: const EdgeInsets.symmetric(horizontal: 10),
  866. decoration: BoxDecoration(
  867. color: Colors.red,
  868. borderRadius: BorderRadius.circular(10),
  869. border: Border.all(color: const Color.fromARGB(255, 247, 143, 135), width: 2),
  870. boxShadow: [BoxShadow(color: Color.fromRGBO(0, 0, 0, 0.3), blurRadius: 5, offset: const Offset(0, 3))],
  871. ),
  872. child: Center(
  873. child: Text(
  874. AppLocalizations.of(context)!.hardMode,
  875. style: TextStyle(color: Colors.white, fontSize: 30, fontWeight: FontWeight.bold),
  876. ),
  877. ),
  878. ),
  879. ),
  880. );
  881. Widget get nextButton {
  882. Device device = context.read<Device>();
  883. return AnimatedBuilder(
  884. // 监听显式动画 _bottomSlideAnimation
  885. animation: _bottomSlideAnimation,
  886. builder: (context, child) {
  887. return AnimatedPositioned(
  888. duration: _successAnimationController.duration!,
  889. // 从动画中获取实时 value,赋值给 bottom
  890. bottom: _bottomSlideAnimation.value,
  891. left: (device.screenSize.width - 200) / 2,
  892. child: child!, // 固定子组件,优化性能
  893. );
  894. },
  895. // 固定的按钮组件(仅构建一次,优化性能)
  896. child: MyElevatedButton(
  897. width: 200,
  898. borderRadius: BorderRadius.circular(20),
  899. gradient: LinearGradient(colors: [SkinHelper.coreBgColor, SkinHelper.slotBorderColor]),
  900. onPressed: () async {
  901. audio.playSfx(SfxType.click);
  902. bool adResult = false;
  903. if (data.currentLevel % 25 != 0) {
  904. // 如果是合集最后的关卡, 这个时候不要展示插屏,因为接下来的合集解锁动画比较密集
  905. adResult = await showInterstitialAd('level_done', widget.item.id, data.currentLevel - 1);
  906. }
  907. if (!mounted) return;
  908. if (adResult) {
  909. // 广告播放结束,延迟一下再返回
  910. Future.delayed(Duration(milliseconds: 100), () {
  911. if (mounted) {
  912. Navigator.pop(context, true);
  913. }
  914. });
  915. } else {
  916. Navigator.pop(context, true);
  917. }
  918. },
  919. child: Text(AppLocalizations.of(context)!.next, style: TextStyle(color: Colors.white, fontSize: 20)),
  920. ),
  921. );
  922. }
  923. Widget get successBanner {
  924. Device device = context.read<Device>();
  925. // 计算banner宽高
  926. final bannerWidth = device.screenSize.width - 40 * 2; // 左右各30间距
  927. final bannerHeight = 60.0;
  928. return AnimatedBuilder(
  929. animation: _bottomSlideAnimation,
  930. builder: (context, child) {
  931. return AnimatedPositioned(
  932. duration: _successAnimationController.duration!,
  933. top: _topSlideAnimation.value, // 固定底部位置
  934. left: 40, // 左间距30,与bannerWidth配合实现水平居中
  935. child: child!,
  936. );
  937. },
  938. // 核心:用Container固定尺寸,Stack填充Container,确保图片和文字尺寸对齐
  939. child: SizedBox(
  940. width: bannerWidth, // 容器宽=图片宽
  941. height: bannerHeight, // 容器高=图片高
  942. child: Stack(
  943. children: [
  944. // 1. 图片充满容器(与容器尺寸一致)
  945. Image.asset(
  946. 'assets/images/banner.png',
  947. width: double.infinity, // 图片宽=容器宽
  948. height: double.infinity, // 图片高=容器高
  949. fit: BoxFit.cover, // 图片填充容器(不拉伸,超出部分裁剪)
  950. cacheWidth: (context.watch<Device>().devicePixelRatio * bannerWidth).toInt(),
  951. cacheHeight: (context.watch<Device>().devicePixelRatio * bannerHeight).toInt(),
  952. ),
  953. Center(
  954. child: Padding(
  955. padding: EdgeInsets.only(top: 16.0),
  956. child: Text(
  957. AppLocalizations.of(context)!.levelPass,
  958. style: TextStyle(
  959. color: Colors.white,
  960. fontSize: 22,
  961. fontWeight: FontWeight.bold,
  962. shadows: [Shadow(color: Colors.black54, offset: Offset(1, 1), blurRadius: 2)],
  963. ),
  964. ),
  965. ),
  966. ),
  967. ],
  968. ),
  969. ),
  970. );
  971. }
  972. Offset _globalToLocal(Offset globalPosition) {
  973. final RenderBox renderBox = boardKey.currentContext!.findRenderObject() as RenderBox;
  974. return renderBox.globalToLocal(globalPosition);
  975. }
  976. void _onPanStart(DragStartDetails details) {
  977. _log.info('_onPanStart');
  978. _overLayer?.stopHint();
  979. if (board!.status != BoardStatus.playing) {
  980. _log.info('不是playing状态,不响应onPanStart');
  981. return;
  982. }
  983. if (board!.checkWinCondition()) {
  984. _log.info('游戏已经完成,不再响应onPanStart');
  985. return;
  986. }
  987. // 动画中断逻辑:如果动画正在进行,立即停止并强制所有 pieces 归位到最终位置
  988. if (_moveAnimationController.isAnimating && moveItems != null) {
  989. _log.info('移动动画中断,强制归位/交换');
  990. for (var item in moveItems!) {
  991. item.stop();
  992. }
  993. bool needRebuildGroup = moveItems!.any((item) => item.action == Action.swap);
  994. if (needRebuildGroup) {
  995. board!.backupAllGroups();
  996. board!.rebuildAllGroups();
  997. final mergeGroups = board!.compareAllGroups();
  998. if (mergeGroups.isNotEmpty) {
  999. // 此时不需要触发 merge 动画,只需确保数据结构正确
  1000. }
  1001. }
  1002. moveItems = null; // 清空动画列表
  1003. _moveAnimationController.stop();
  1004. board!.invalidate(); // 触发一次重绘来显示最终位置
  1005. }
  1006. // 如果 merge 动画正在进行,也应该中断并立即归位
  1007. if (_mergeAnimationController.isAnimating && _mergeGroups != null) {
  1008. _log.info('合并动画中断,强制归位');
  1009. for (var group in _mergeGroups!) {
  1010. for (var piece in group.pieces) {
  1011. piece.transform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  1012. }
  1013. }
  1014. _mergeGroups = null;
  1015. _mergeAnimationController.stop();
  1016. board!.invalidate();
  1017. }
  1018. // 停止所有正在运行的动画(如果尚未停止)
  1019. _moveAnimationController.stop();
  1020. _mergeAnimationController.stop();
  1021. moveItems = null;
  1022. final localPosition = _globalToLocal(details.globalPosition);
  1023. final touchedPiece = board?.findPieceAt(localPosition);
  1024. if (touchedPiece != null) {
  1025. audio.playSfx(SfxType.panstart);
  1026. if (settings.vibrate.value) {
  1027. if (Platform.isAndroid) {
  1028. Vibration.vibrate(duration: 60, amplitude: 50);
  1029. } else {
  1030. HapticFeedback.mediumImpact();
  1031. }
  1032. }
  1033. _draggingPiece = touchedPiece;
  1034. final draggingGroup = _draggingPiece!.group;
  1035. if (draggingGroup != null) {
  1036. // 将拖拽群组置于 pieces 列表末尾,确保它在 CustomPainter 中被最后绘制(在最上层)
  1037. board!.pieces.removeWhere((p) => draggingGroup.contains(p));
  1038. board!.pieces.addAll(draggingGroup.pieces);
  1039. } else {
  1040. board!.pieces.remove(_draggingPiece);
  1041. board!.pieces.add(_draggingPiece!);
  1042. }
  1043. board!.invalidate();
  1044. }
  1045. }
  1046. void _onPanUpdate(DragUpdateDetails details) {
  1047. _overLayer?.stopHint();
  1048. if (_draggingPiece == null) return;
  1049. final Offset delta = details.delta;
  1050. final draggingGroup = _draggingPiece!.group;
  1051. if (draggingGroup != null) {
  1052. // 拖拽过程中,所有群组成员共享相同的位移
  1053. for (var piece in draggingGroup.pieces) {
  1054. piece.applyDelta(delta);
  1055. }
  1056. } else {
  1057. _draggingPiece!.applyDelta(delta);
  1058. }
  1059. board!.invalidate();
  1060. }
  1061. void _onPanEnd(DragEndDetails details) {
  1062. _log.info('_onPanEnd');
  1063. _overLayer?.stopHint();
  1064. if (_draggingPiece == null) {
  1065. return;
  1066. }
  1067. audio.playSfx(SfxType.tap);
  1068. // 保存当前拖拽结束的碎片,以备动画使用
  1069. Piece leaderPiece = _draggingPiece!;
  1070. _draggingPiece = null; // 结束拖拽
  1071. board!.invalidate();
  1072. /// 交换或归位
  1073. // 获取碎片的中心点,判断中心点是否落到某个piece上
  1074. Piece? targetPiece = board!.findPieceAtExclude(leaderPiece.currentCenter, leaderPiece);
  1075. // 群组特殊处理:如果 leaderPiece 没有落在其他碎片上,检查群组其他成员
  1076. if (targetPiece == null && leaderPiece.group != null) {
  1077. for (var p in leaderPiece.group!.pieces) {
  1078. targetPiece = board!.findPieceAtExclude(p.currentCenter, p);
  1079. if (targetPiece != null) {
  1080. _log.info('推举 ${p.toString()} 为新leader');
  1081. leaderPiece = p; // p 落在有效的其他piece上,推举为leaderPiece
  1082. break;
  1083. }
  1084. }
  1085. }
  1086. // 判断是否可以交换
  1087. if (targetPiece != null && targetPiece != leaderPiece && leaderPiece.canPlaceTo(targetPiece)) {
  1088. _log.info("swap animation start");
  1089. _animateSwap(leaderPiece, targetPiece);
  1090. } else {
  1091. _log.info("revert animation start");
  1092. _animateRevert(leaderPiece);
  1093. }
  1094. }
  1095. // 为所有涉及移动的 piece 创建独立的 MoveItem
  1096. void _animateSwap(Piece leaderPiece, Piece targetPiece) {
  1097. List<MoveItem> items = [];
  1098. // 1. 确定涉及移动的所有碎片
  1099. final List<Piece> draggingPieces = leaderPiece.group != null ? leaderPiece.group!.pieces : [leaderPiece];
  1100. final int dr = targetPiece.curRow - leaderPiece.curRow; // 目标位置的行位移
  1101. final int dc = targetPiece.curCol - leaderPiece.curCol; // 目标位置的列位移
  1102. // 2. 识别被替换/推开的碎片
  1103. List<Piece> displacedPieces = [];
  1104. if (leaderPiece.group != null) {
  1105. // 群组交换:找到群组新目标位置上的所有非自身群组的碎片
  1106. for (var p in draggingPieces) {
  1107. final int targetRow = p.curRow + dr;
  1108. final int targetCol = p.curCol + dc;
  1109. final Piece? other = board!.getPieceByCoordinate(targetRow, targetCol);
  1110. if (other != null && !p.isSameGroup(other)) {
  1111. displacedPieces.add(other);
  1112. }
  1113. }
  1114. } else {
  1115. // 单碎片交换:被替换的碎片就是 targetPiece
  1116. displacedPieces.add(targetPiece);
  1117. }
  1118. // 3. 更新逻辑坐标 (curRow, curCol) - 必须在创建动画前完成
  1119. // a. 更新拖拽群组/碎片的位置
  1120. for (var p in draggingPieces) {
  1121. p.curRow += dr;
  1122. p.curCol += dc;
  1123. }
  1124. // b. 更新被推开的碎片的位置 (移入拖拽群组腾出的槽位)
  1125. if (leaderPiece.group == null) {
  1126. // 单碎片交换:targetPiece 移入 leaderPiece 的旧槽位
  1127. targetPiece.curRow -= dr;
  1128. targetPiece.curCol -= dc;
  1129. } else {
  1130. // 群组交换:被推开的碎片向后退 dr/dc 距离,找到空槽位
  1131. for (var p in displacedPieces) {
  1132. int newRow = p.curRow - dr;
  1133. int newCol = p.curCol - dc;
  1134. do {
  1135. final Piece? pieceInSlot = board!.getPieceByCoordinate(newRow, newCol);
  1136. if (pieceInSlot == null) {
  1137. p.curRow = newRow;
  1138. p.curCol = newCol;
  1139. break;
  1140. } else {
  1141. newRow -= dr;
  1142. newCol -= dc;
  1143. }
  1144. } while (newRow >= 0 && newRow < p.rows && newCol >= 0 && newCol < p.cols);
  1145. }
  1146. }
  1147. // 4. 为所有涉及移动的碎片创建 MoveItem
  1148. // a. 被推开的碎片
  1149. for (var p in displacedPieces) {
  1150. // 动画起点:旧的逻辑网格坐标 (p.transform)
  1151. final startTransform = p.transform;
  1152. // 动画终点:新的逻辑网格坐标
  1153. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  1154. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  1155. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.swap));
  1156. board!.pieces.remove(p);
  1157. board!.pieces.add(p);
  1158. }
  1159. // b. 拖拽群组/碎片
  1160. for (var p in draggingPieces) {
  1161. // 动画起点:拖拽结束时的实际 Canvas 坐标 (p.transform)
  1162. final startTransform = p.transform;
  1163. // 动画终点:新的逻辑网格坐标
  1164. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  1165. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  1166. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.swap));
  1167. board!.pieces.remove(p);
  1168. board!.pieces.add(p);
  1169. }
  1170. // 5. 启动动画
  1171. moveItems = items;
  1172. _moveAnimationController.forward(from: 0.0);
  1173. }
  1174. // 关键重构:为所有涉及归位的 piece 创建独立的 MoveItem
  1175. void _animateRevert(Piece piece) {
  1176. List<MoveItem> items = [];
  1177. final List<Piece> groupPieces = piece.group != null ? piece.group!.pieces : [piece];
  1178. for (var p in groupPieces) {
  1179. // 动画起点:拖拽结束时的实际 Canvas 坐标 (p.transform)
  1180. final startTransform = p.transform;
  1181. // 动画终点:归位位置(即拖拽前所在的逻辑网格坐标)
  1182. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  1183. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  1184. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.revert));
  1185. }
  1186. moveItems = items;
  1187. _moveAnimationController.forward(from: 0.0);
  1188. }
  1189. }
  1190. // 辅助类:用于对 vmath.Matrix4 进行线性插值 (lerp),实现平滑动画
  1191. class Matrix4Tween extends Tween<vmath.Matrix4> {
  1192. Matrix4Tween({required vmath.Matrix4 begin, required vmath.Matrix4 end}) : super(begin: begin, end: end);
  1193. @override
  1194. vmath.Matrix4 lerp(double t) {
  1195. if (begin == null || end == null) return begin ?? end ?? vmath.Matrix4.identity();
  1196. final List<double> lerpedStorage = List.generate(16, (i) {
  1197. // 确保使用 ui.lerpDouble 进行插值
  1198. return ui.lerpDouble(begin!.storage[i], end!.storage[i], t)!;
  1199. });
  1200. return vmath.Matrix4.fromList(lerpedStorage.cast<double>());
  1201. }
  1202. }
  1203. // 动画辅助类,记录移动信息
  1204. class MoveItem {
  1205. // 要移动的piece
  1206. final Piece piece;
  1207. // 动画animation
  1208. final Animation<vmath.Matrix4> animation;
  1209. // 起始位置(拖拽结束时的实际 Canvas 坐标)
  1210. final vmath.Matrix4 startTransform;
  1211. // 结束位置(目标网格槽位的 Canvas 坐标)
  1212. final vmath.Matrix4 endTransform;
  1213. // 移除了 MoveType,因为现在每个 piece 都有自己的 MoveItem
  1214. // final MoveType moveType;
  1215. final Action action;
  1216. MoveItem({required this.piece, required this.animation, required this.startTransform, required this.endTransform, required this.action});
  1217. // 关键修正:直接设置 piece 的 transform 为动画插值
  1218. void move() {
  1219. // 关键修正:直接设置piece的transform为动画插值,而不是累加delta
  1220. piece.transform = animation.value;
  1221. }
  1222. void stop() {
  1223. // 关键修正:动画中断时,直接设置到最终目标位置 (endTransform)
  1224. // 此时 piece 的 curRow/curCol 已经是目标网格坐标
  1225. piece.transform = endTransform;
  1226. }
  1227. }