board_play.dart 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  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/download.dart';
  16. import 'package:puzzleweave/models/items.dart';
  17. import 'package:puzzleweave/persistence/persistence.dart';
  18. import 'package:puzzleweave/play/board.dart';
  19. import 'package:puzzleweave/play/board_painter.dart';
  20. import 'package:puzzleweave/play/confetti_layer.dart';
  21. import 'package:puzzleweave/play/overlayer.dart';
  22. import 'package:puzzleweave/play/piece.dart';
  23. import 'package:puzzleweave/rating/rating_helper.dart';
  24. import 'package:puzzleweave/rating/rating_utils.dart';
  25. import 'package:puzzleweave/settings/settings_controller.dart';
  26. import 'package:puzzleweave/settings/settings_dialog.dart';
  27. import 'package:puzzleweave/skin/skin.dart';
  28. import 'package:puzzleweave/statistics/statistics.dart';
  29. import 'package:puzzleweave/utils/memory_monitor.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. import '../config/config.dart';
  36. final Logger _log = Logger('board_play.dart');
  37. enum MoveType { group, single }
  38. enum Action { revert, swap }
  39. class BoardPlay extends StatefulWidget {
  40. final ListItem item;
  41. final bool firstRun;
  42. final bool reset;
  43. final String tag;
  44. const BoardPlay({super.key, required this.item, this.firstRun = false, this.reset = false, this.tag = 'home'});
  45. @override
  46. State<StatefulWidget> createState() => _BoardPlayState();
  47. static PageRouteBuilder buildRoute(ListItem item, {bool firstRun = false, bool reset = false}) {
  48. return PageRouteBuilder(
  49. pageBuilder: (context, animation, secondaryAnimation) => BoardPlay(item: item, firstRun: firstRun, reset: reset),
  50. transitionsBuilder: (context, animation, secondaryAnimation, child) => FadeTransition(opacity: animation, child: child),
  51. );
  52. }
  53. }
  54. class _BoardPlayState extends AdsState<BoardPlay> with TickerProviderStateMixin {
  55. final GlobalKey boardKey = GlobalKey();
  56. Board? board;
  57. bool _isLoading = true;
  58. int progress = 0;
  59. bool isDownloadSlow = false;
  60. late Timer timer;
  61. // ⚠️ 新增:banner 延迟加载标记
  62. bool _bannerDelayedLoad = false;
  63. late ItemLoader itemLoader;
  64. late JcAudioController audio;
  65. late SettingsController settings;
  66. late ConfettiLayer confettiLayer;
  67. ui.Image? _fingerImage;
  68. OverLayer? _overLayer;
  69. Piece? _draggingPiece;
  70. List<MoveItem>? moveItems;
  71. // ✅ 优化:资源清理定时器
  72. Timer? _resourceCleanupTimer;
  73. // 动画控制器
  74. late AnimationController _moveAnimationController;
  75. late AnimationController _mergeAnimationController;
  76. late Animation<double> _mergeScaleAnimation;
  77. List<PieceGroup>? _mergeGroups;
  78. bool showDealing = true;
  79. late AnimationController _prepareAnimationController;
  80. late AnimationController dealingAnimationController;
  81. late AnimationController flipAnimationController;
  82. late Animation<double> _dealingAnimation;
  83. Timer? _dealingPeriodicTimer;
  84. int _dealingCount = 0;
  85. // Precomputed transforms for dealing animation to avoid per-frame allocations
  86. List<vmath.Matrix4>? _dealingStartTransforms;
  87. List<vmath.Matrix4>? _dealingEndTransforms;
  88. late AnimationController _successAnimationController;
  89. late Animation<double> _offsetAnimation;
  90. late Animation<double> _bottomSlideAnimation;
  91. late Animation<double> _topSlideAnimation;
  92. late AnimationController _hardModeBannerController;
  93. late Animation<double> _bannerScaleAnimation;
  94. late Animation<double> _bannerFadeAnimation;
  95. bool _showHardModeBanner = false;
  96. // ✅ 保留:重试标记,防止无限循环
  97. bool _hasRetried = false;
  98. @override
  99. initState() {
  100. super.initState();
  101. MemoryMonitor.logMemoryUsage('BoardPlay initState');
  102. final Device device = context.read<Device>();
  103. itemLoader = ItemLoader.load(widget.item, device.suggestedQuality);
  104. _onProgressUpdate();
  105. itemLoader.progress.addListener(_onProgressUpdate);
  106. timer = Timer(const Duration(seconds: 5), () {
  107. if (mounted && progress < 50) {
  108. if (progress <= 1) {
  109. Fluttertoast.showToast(
  110. msg: AppLocalizations.of(context)!.networkNotGood,
  111. toastLength: Toast.LENGTH_SHORT,
  112. gravity: ToastGravity.CENTER,
  113. timeInSecForIosWeb: 1,
  114. backgroundColor: SkinHelper.slotBorderColor,
  115. textColor: Colors.white,
  116. fontSize: 16.0,
  117. );
  118. Navigator.pop(context);
  119. } else {
  120. setState(() => isDownloadSlow = true);
  121. }
  122. }
  123. });
  124. audio = context.read<JcAudioController>();
  125. settings = context.read<SettingsController>();
  126. confettiLayer = ConfettiLayer(this);
  127. Future.delayed(Duration.zero, () {
  128. if (mounted) confettiLayer.setup(context);
  129. });
  130. _initAnimations();
  131. try {
  132. _init();
  133. } catch (error) {
  134. _log.info('board init error: $error');
  135. Fluttertoast.showToast(
  136. msg: AppLocalizations.of(context)!.networkNotGood,
  137. toastLength: Toast.LENGTH_SHORT,
  138. gravity: ToastGravity.CENTER,
  139. timeInSecForIosWeb: 1,
  140. backgroundColor: SkinHelper.slotBorderColor,
  141. textColor: Colors.white,
  142. fontSize: 16.0,
  143. );
  144. Navigator.pop(context);
  145. }
  146. }
  147. void _initAnimations() {
  148. final Device device = context.read<Device>();
  149. // ⚠️ 优化:只初始化必要的动画控制器,其他延迟创建
  150. _moveAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
  151. _moveAnimationController.addListener(_moveAnimationListener);
  152. _moveAnimationController.addStatusListener(_moveAnimationStatusListener);
  153. _mergeAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));
  154. _mergeAnimationController.addListener(_mergeAnimationListener);
  155. _mergeAnimationController.addStatusListener(_mergeAnimationStatusListener);
  156. _mergeScaleAnimation = TweenSequence<double>([
  157. TweenSequenceItem(tween: Tween<double>(begin: 1.0, end: 1.06), weight: 50),
  158. TweenSequenceItem(tween: Tween<double>(begin: 1.06, end: 1.0), weight: 50),
  159. ]).animate(CurvedAnimation(parent: _mergeAnimationController, curve: Curves.easeInOut));
  160. _prepareAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 800));
  161. _prepareAnimationController.addListener(_prepareAnimationListener);
  162. _prepareAnimationController.addStatusListener(_prepareAnimationStatusListener);
  163. dealingAnimationController = AnimationController(vsync: this);
  164. _dealingAnimation = CurvedAnimation(parent: dealingAnimationController, curve: Curves.linear);
  165. dealingAnimationController.addListener(_dealingAnimationListener);
  166. dealingAnimationController.addStatusListener(_dealingAnimationStatusListener);
  167. flipAnimationController = AnimationController(vsync: this, duration: Duration(milliseconds: 500));
  168. flipAnimationController.addListener(_flipAnimationListener);
  169. flipAnimationController.addStatusListener(_flipAnimationStatusListener);
  170. // ⚠️ success 和 hardModeBanner 动画延迟创建(在需要时创建)
  171. _initSuccessAnimation(device);
  172. _initHardModeBannerAnimation();
  173. }
  174. void _initSuccessAnimation(Device device) {
  175. _successAnimationController = AnimationController(vsync: this, duration: Duration(milliseconds: 500));
  176. final deltaY = (device.targetRect.top - device.appBarHeight) / 3;
  177. _offsetAnimation = Tween<double>(begin: 0.0, end: -deltaY).animate(_successAnimationController);
  178. _bottomSlideAnimation = Tween<double>(
  179. begin: -500,
  180. end: device.screenSize.height - device.targetRect.bottom + deltaY - 60,
  181. ).animate(CurvedAnimation(parent: _successAnimationController, curve: Curves.easeOut));
  182. _topSlideAnimation = Tween<double>(
  183. begin: -200,
  184. end: device.targetRect.top - deltaY - 70,
  185. ).animate(CurvedAnimation(parent: _successAnimationController, curve: Curves.easeOut));
  186. _successAnimationController.addListener(_successAnimationListener);
  187. _successAnimationController.addStatusListener(_successAnimationStatusListener);
  188. }
  189. void _initHardModeBannerAnimation() {
  190. _hardModeBannerController = AnimationController(vsync: this, duration: const Duration(milliseconds: 1500));
  191. _bannerScaleAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
  192. CurvedAnimation(
  193. parent: _hardModeBannerController,
  194. curve: const Interval(0.0, 0.4, curve: Curves.easeOut),
  195. ),
  196. );
  197. _bannerFadeAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(
  198. CurvedAnimation(
  199. parent: _hardModeBannerController,
  200. curve: const Interval(0.3, 1.0, curve: Curves.easeIn),
  201. ),
  202. );
  203. _hardModeBannerController.addStatusListener((status) {
  204. if (status == AnimationStatus.completed) {
  205. if (mounted) setState(() => _showHardModeBanner = false);
  206. }
  207. });
  208. }
  209. _onProgressUpdate() {
  210. progress = (itemLoader.progress.value * 100).ceil();
  211. _log.info('onProgressUpdate: progress=$progress');
  212. setState(() {});
  213. }
  214. void saveProgress() async {
  215. _log.info('saveProgress');
  216. if (board != null && board!.isAllDone == false) {
  217. await saveJson(widget.item.jsonPath, board!.toJson());
  218. }
  219. }
  220. // ✅ 优化后的 _init() 方法 - 保留图片损坏检测和重试逻辑
  221. _init() async {
  222. if (!mounted) return;
  223. Device device = context.read<Device>();
  224. setState(() => _isLoading = true);
  225. // 如果是低端设备,跳过发牌动画以节省资源(借鉴 homepage 优化)
  226. if (device.isLowEndDevice) {
  227. showDealing = false;
  228. _log.info('Low-end device detected, skipping dealing animation');
  229. }
  230. try {
  231. final dpr = device.effectivePixelRatio;
  232. final targetRect = device.targetRect;
  233. final bestImageSize = device.bestImageSize;
  234. // ✅ 1. 尝试获取并解码图片(保留原有的错误处理逻辑)
  235. ui.Image image;
  236. try {
  237. image = await itemLoader.getImageBySize(bestImageSize.width.round(), bestImageSize.height.round());
  238. } catch (e) {
  239. _log.severe('Image decode failed: $e. Possible corrupted file.');
  240. // ✅ 保留:如果解码失败且还没重试过,尝试删除缓存重来
  241. if (!_hasRetried) {
  242. _hasRetried = true;
  243. final file = await localFile(widget.item.cachePath);
  244. if (await file.exists()) {
  245. await file.delete();
  246. _log.warning('Deleted corrupted cache file: ${widget.item.cachePath}');
  247. }
  248. // 重新初始化下载逻辑
  249. itemLoader = ItemLoader.load(widget.item, device.suggestedQuality);
  250. // 递归调用一次
  251. return _init();
  252. } else {
  253. // 已经重试过还是失败,抛出异常进入 catch 块
  254. throw Exception("Image data invalid after retry");
  255. }
  256. }
  257. _log.info('imageSize: (${image.width},${image.height}), bestImageSize: ($bestImageSize)');
  258. // ✅ 2. 加载扑克背面图片
  259. final Size bestCardImageSize = Size(targetRect.width * dpr / widget.item.rows, targetRect.height * dpr / widget.item.cols);
  260. final ByteData cardData = await rootBundle.load(widget.item.hard ? 'assets/images/backcard_red.png' : 'assets/images/backcard_blue.png');
  261. ui.Image cardImage;
  262. final ui.Codec cardCodec = await ui.instantiateImageCodec(
  263. cardData.buffer.asUint8List(),
  264. targetWidth: bestCardImageSize.width.round(),
  265. targetHeight: bestCardImageSize.height.round(),
  266. );
  267. final ui.FrameInfo cardFrameInfo = await cardCodec.getNextFrame();
  268. cardImage = cardFrameInfo.image;
  269. // ✅ 3. 构建或恢复 Board 实例
  270. if (widget.reset) {
  271. board = await Board.create(this, image, cardImage, widget.item.rows, widget.item.cols, widget.item.hard, targetRect, device);
  272. } else {
  273. final jsonFile = await localFile(widget.item.jsonPath);
  274. if (await jsonFile.exists()) {
  275. showDealing = false;
  276. board = await Board.restore(this, image, cardImage, widget.item.rows, widget.item.cols, widget.item.hard, targetRect, device, widget.item.jsonPath);
  277. } else {
  278. board = await Board.create(this, image, cardImage, widget.item.rows, widget.item.cols, widget.item.hard, targetRect, device);
  279. _reportLevelStart();
  280. }
  281. }
  282. // 4. 初始化准备
  283. board!.prepare();
  284. _loadFingerImageAndSetupHint();
  285. if (mounted) {
  286. setState(() => _isLoading = false);
  287. }
  288. // 5. 启动入场动画
  289. if (showDealing) {
  290. _prepareAnimationController.forward(from: 0.0);
  291. } else {
  292. board!.start();
  293. }
  294. } catch (error) {
  295. _log.severe('Board _init critical error: $error');
  296. if (mounted) {
  297. Fluttertoast.showToast(
  298. msg: AppLocalizations.of(context)!.networkNotGood,
  299. toastLength: Toast.LENGTH_LONG,
  300. gravity: ToastGravity.CENTER,
  301. backgroundColor: SkinHelper.slotBorderColor,
  302. textColor: Colors.white,
  303. );
  304. Navigator.pop(context);
  305. }
  306. }
  307. }
  308. _reportLevelStart() {
  309. FirebaseHelper.logEvent("level_start", {'id': widget.item.id, 'level': data.currentLevel + 1});
  310. AdjustHelper.trackEvent(AdjustHelper.levelStartToken);
  311. Statistics.postEvent({
  312. "project_id": Persistence().projectId,
  313. "user_id": Persistence().uuid,
  314. "library_name": Persistence().libraryName,
  315. "library_version": Persistence().packageVersion,
  316. "name": 'level_start',
  317. "tab_source": widget.tag,
  318. "sku_id": widget.item.id,
  319. });
  320. }
  321. Future<void> _loadFingerImageAndSetupHint() async {
  322. if (!widget.firstRun) return;
  323. try {
  324. _fingerImage = await loadUiImageFromAsset('assets/images/finger.png');
  325. } catch (e) {
  326. _log.severe('Failed to load assets/images/finger.png: $e');
  327. return;
  328. }
  329. if (!mounted || board == null) return;
  330. _overLayer = OverLayer(board!, this);
  331. _overLayer!.setup(context);
  332. if (widget.firstRun) {
  333. Future.delayed(const Duration(seconds: 1), () => hint());
  334. Future.delayed(const Duration(seconds: 3), () {
  335. if (!mounted) return;
  336. if (_overLayer != null && _overLayer!.isHinting) {
  337. Fluttertoast.showToast(
  338. msg: AppLocalizations.of(context)!.moveToComplete,
  339. toastLength: Toast.LENGTH_SHORT,
  340. gravity: ToastGravity.BOTTOM,
  341. timeInSecForIosWeb: 1,
  342. backgroundColor: SkinHelper.slotBorderColor,
  343. textColor: Colors.white,
  344. fontSize: 16.0,
  345. );
  346. }
  347. });
  348. }
  349. }
  350. hint() async {
  351. if (_fingerImage == null || _overLayer == null || board == null || board!.status != BoardStatus.playing) return;
  352. double fingerSize = board!.pieceLogicalWidth / 2.5;
  353. final Offset centerStart = Offset(
  354. board!.targetRect.topLeft.dx + board!.pieceLogicalWidth,
  355. board!.targetRect.topLeft.dy + board!.pieceLogicalHeight * 5 / 2,
  356. );
  357. final Offset centerEnd = Offset(board!.targetRect.topLeft.dx + board!.pieceLogicalWidth, board!.targetRect.topLeft.dy + board!.pieceLogicalHeight * 3 / 2);
  358. final rectStart = Rect.fromCenter(center: centerStart, width: fingerSize, height: fingerSize);
  359. final rectEnd = Rect.fromCenter(center: centerEnd, width: fingerSize, height: fingerSize);
  360. final hintItem = HintItem(_fingerImage!, rectStart, rectEnd);
  361. _overLayer?.doHint(hintItem);
  362. }
  363. // 🔥 关键修复:成功回调,延迟资源清理到页面退出时
  364. _onSuccess() {
  365. _log.info('success! 游戏完成!');
  366. MemoryMonitor.logMemoryUsage('Level completed');
  367. data.workDone(widget.item);
  368. board!.success();
  369. audio.playSfx(SfxType.success);
  370. confettiLayer.play();
  371. _successAnimationController.forward(from: 0.0);
  372. setState(() {});
  373. // 数据上报
  374. FirebaseHelper.logEvent("level_done", {'id': widget.item.id, 'level': data.currentLevel});
  375. AdjustHelper.trackEvent(AdjustHelper.levelDoneToken);
  376. Statistics.postEvent({
  377. "project_id": Persistence().projectId,
  378. "user_id": Persistence().uuid,
  379. "library_name": Persistence().libraryName,
  380. "library_version": Persistence().packageVersion,
  381. "name": 'level_done',
  382. "tab_source": widget.tag,
  383. "sku_id": widget.item.id,
  384. "level": data.currentLevel,
  385. });
  386. // 里程碑上报
  387. if (data.currentLevel == 3) {
  388. FirebaseHelper.logEvent("level_done_3", {});
  389. AdjustHelper.trackEvent(AdjustHelper.levelDone3Token);
  390. } else if (data.currentLevel == 10) {
  391. FirebaseHelper.logEvent("level_done_10", {});
  392. AdjustHelper.trackEvent(AdjustHelper.levelDone10Token);
  393. } else if (data.currentLevel == 20) {
  394. FirebaseHelper.logEvent("level_done_20", {});
  395. AdjustHelper.trackEvent(AdjustHelper.levelDone20Token);
  396. } else if (data.currentLevel == 30) {
  397. FirebaseHelper.logEvent("level_done_30", {});
  398. AdjustHelper.trackEvent(AdjustHelper.levelDone30Token);
  399. }
  400. }
  401. // 动画监听器方法(保持原有逻辑)
  402. void _successAnimationListener() {
  403. if (board == null) return;
  404. final delta = _offsetAnimation.value;
  405. board!.finalRect = board!.targetRect.translate(0, delta);
  406. board!.invalidate();
  407. }
  408. void _successAnimationStatusListener(AnimationStatus status) async {
  409. if (status == AnimationStatus.completed) {
  410. Future.delayed(Duration(seconds: 1), () async {
  411. if (!mounted) return;
  412. final bool shouldShowRateDialog = await RatingHelper.shouldShowRateDialog(data.currentLevel);
  413. if (shouldShowRateDialog && mounted) {
  414. showRateDialog(context);
  415. }
  416. });
  417. }
  418. }
  419. // 其他动画监听器方法保持原有逻辑...
  420. void _dealingAnimationListener() {
  421. if (board == null) return;
  422. final currentTime = _dealingAnimation.value * _totalDealingDuration;
  423. final pieces = board!.pieces;
  424. // 使用预计算的起始/结束变换进行插值,避免在帧中创建大量 Matrix4Tween/Matrix4 对象
  425. if (_dealingStartTransforms != null && _dealingEndTransforms != null) {
  426. for (int i = 0; i < pieces.length; i++) {
  427. final piece = pieces[i];
  428. final startTime = i * _dealingPieceInterval;
  429. final duration = _dealingPieceDuration;
  430. if (currentTime < startTime) continue;
  431. double progress = (currentTime - startTime) / duration;
  432. progress = progress.clamp(0.0, 1.0);
  433. final begin = _dealingStartTransforms![i];
  434. final end = _dealingEndTransforms![i];
  435. // 直接在 double 数组上做线性插值,减少中间对象分配
  436. final List<double> lerped = List<double>.filled(16, 0.0);
  437. for (int k = 0; k < 16; k++) {
  438. lerped[k] = ui.lerpDouble(begin.storage[k], end.storage[k], progress)!;
  439. }
  440. piece.transform = vmath.Matrix4.fromList(lerped);
  441. }
  442. } else {
  443. // 兼容回退:老逻辑(尽量不会走到这里)
  444. for (int i = 0; i < board!.pieces.length - 1; i++) {
  445. final piece = board!.pieces[i];
  446. final startTime = i * _dealingPieceInterval;
  447. final duration = _dealingPieceDuration;
  448. if (currentTime < startTime) continue;
  449. double progress = (currentTime - startTime) / duration;
  450. progress = progress.clamp(0.0, 1.0);
  451. final startTransform = board!.getBottomRightTransform();
  452. final endTransform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  453. final tween = Matrix4Tween(begin: startTransform, end: endTransform);
  454. piece.transform = tween.lerp(progress);
  455. }
  456. }
  457. board!.invalidate();
  458. }
  459. void _dealingAnimationStatusListener(AnimationStatus status) {
  460. if (status == AnimationStatus.completed) {
  461. if (board == null) return;
  462. board!.resetAllPieces();
  463. board!.shuffle(ShuffleStep.flipping);
  464. flipAnimationController.forward(from: 0.0);
  465. audio.playSfx(SfxType.flip);
  466. // 清理预计算的 transform 缓存
  467. _dealingStartTransforms = null;
  468. _dealingEndTransforms = null;
  469. }
  470. }
  471. void _flipAnimationListener() {
  472. if (board == null) return;
  473. final flipValue = flipAnimationController.value;
  474. for (final piece in board!.pieces) {
  475. final angle = flipValue * pi;
  476. final targetTranslate = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  477. piece.updateFlipTransform(angle, targetTranslate);
  478. }
  479. board!.invalidate();
  480. }
  481. void _flipAnimationStatusListener(AnimationStatus status) {
  482. if (status == AnimationStatus.completed) {
  483. if (board == null) return;
  484. board!.resetAllPieces();
  485. board!.rebuildAllGroups();
  486. final mergeGroups = board!.compareAllGroups();
  487. if (mergeGroups.isNotEmpty) {
  488. _log.info('Merge animation start for ${mergeGroups.length} groups.');
  489. _mergeGroups = mergeGroups;
  490. _mergeAnimationController.forward(from: 0.0);
  491. audio.playSfx(SfxType.pop);
  492. }
  493. board!.start();
  494. }
  495. }
  496. void _moveAnimationListener() {
  497. if (moveItems == null || moveItems!.isEmpty || board == null) return;
  498. for (var item in moveItems!) {
  499. item.move();
  500. }
  501. board!.invalidate();
  502. }
  503. void _moveAnimationStatusListener(AnimationStatus status) {
  504. if (status == AnimationStatus.completed) {
  505. if (moveItems != null && board != null) {
  506. bool needRebuildGroup = moveItems!.any((item) => item.action == Action.swap);
  507. for (var item in moveItems!) {
  508. item.stop();
  509. }
  510. if (needRebuildGroup) {
  511. board!.backupAllGroups();
  512. board!.rebuildAllGroups();
  513. final mergeGroups = board!.compareAllGroups();
  514. if (mergeGroups.isNotEmpty) {
  515. _log.info('Merge animation start for ${mergeGroups.length} groups.');
  516. _mergeGroups = mergeGroups;
  517. _mergeAnimationController.forward(from: 0.0);
  518. audio.playSfx(SfxType.pop);
  519. moveItems = null;
  520. return;
  521. }
  522. }
  523. moveItems = null;
  524. }
  525. }
  526. }
  527. void _mergeAnimationListener() {
  528. if (_mergeGroups == null || _mergeGroups!.isEmpty || board == null) return;
  529. final double scale = _mergeScaleAnimation.value;
  530. for (var group in _mergeGroups!) {
  531. final groupCenter = group.center;
  532. for (var piece in group.pieces) {
  533. final baseTransform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  534. final pieceTopLeft = Offset(baseTransform.storage[12], baseTransform.storage[13]);
  535. final offsetToCenter = groupCenter - pieceTopLeft;
  536. final scaleMatrix = vmath.Matrix4.identity()
  537. ..translate(offsetToCenter.dx, offsetToCenter.dy)
  538. ..scale(scale, scale, 1.0)
  539. ..translate(-offsetToCenter.dx, -offsetToCenter.dy);
  540. piece.transform = baseTransform * scaleMatrix;
  541. }
  542. }
  543. board!.invalidate();
  544. }
  545. void _mergeAnimationStatusListener(AnimationStatus status) {
  546. if (status == AnimationStatus.completed) {
  547. if (board == null) return;
  548. if (_mergeGroups != null && _mergeGroups!.isNotEmpty) {
  549. for (var group in _mergeGroups!) {
  550. for (var piece in group.pieces) {
  551. piece.transform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  552. }
  553. }
  554. }
  555. _mergeGroups = null;
  556. if (board!.checkWinCondition()) {
  557. _onSuccess();
  558. }
  559. board!.invalidate();
  560. }
  561. }
  562. void _prepareAnimationListener() {
  563. if (board == null) return;
  564. board!.invalidate();
  565. }
  566. void _prepareAnimationStatusListener(AnimationStatus status) {
  567. if (status == AnimationStatus.completed) {
  568. if (board == null) return;
  569. if (board!.hard == true) {
  570. setState(() => _showHardModeBanner = true);
  571. _hardModeBannerController.forward(from: 0.0);
  572. }
  573. board!.setAllPieceToBottomRight();
  574. board!.shuffle(ShuffleStep.dealing);
  575. // 如果发牌动画需要播放,预计算每个碎片的起始/结束变换,避免在动画回调中大量分配对象
  576. if (showDealing) {
  577. _dealingStartTransforms = [];
  578. _dealingEndTransforms = [];
  579. final vmath.Matrix4 startTransform = board!.getBottomRightTransform();
  580. for (final piece in board!.pieces) {
  581. _dealingStartTransforms!.add(startTransform);
  582. _dealingEndTransforms!.add(board!.getTransformByCoordinate(piece.curRow, piece.curCol));
  583. }
  584. dealingAnimationController.duration = Duration(milliseconds: _totalDealingDuration);
  585. dealingAnimationController.forward(from: 0.0);
  586. } else {
  587. // 如果跳过发牌,直接进入翻牌/播放状态
  588. board!.start();
  589. }
  590. final currentTotalDealingDuration = _totalDealingDuration;
  591. audio.playSfx(SfxType.card);
  592. _dealingPeriodicTimer = Timer.periodic(Duration(milliseconds: 130), (timer) {
  593. if (mounted) {
  594. _dealingCount++;
  595. if (_dealingCount >= (currentTotalDealingDuration / 130) - 2) {
  596. timer.cancel();
  597. } else {
  598. audio.playSfx(SfxType.card);
  599. }
  600. } else {
  601. timer.cancel();
  602. }
  603. });
  604. // ⚠️ 关键优化:发牌动画开始后 2 秒再加载 Banner
  605. Future.delayed(const Duration(seconds: 2), () {
  606. if (mounted) {
  607. setState(() => _bannerDelayedLoad = true);
  608. }
  609. });
  610. }
  611. }
  612. // 发牌动画参数
  613. int get _dealingPieceInterval {
  614. if (board!.rows <= 3) return 90;
  615. if (board!.rows == 4) return 80;
  616. if (board!.rows == 5) return 70;
  617. if (board!.rows == 6) return 50;
  618. return 50;
  619. }
  620. int get _dealingPieceDuration {
  621. if (board!.rows <= 3) return 400;
  622. if (board!.rows == 4) return 300;
  623. if (board!.rows == 5) return 200;
  624. if (board!.rows == 6) return 150;
  625. return 100;
  626. }
  627. int get _totalDealingDuration {
  628. if (board == null) return 0;
  629. return (board!.pieces.length - 1) * _dealingPieceInterval + _dealingPieceDuration;
  630. }
  631. @override
  632. void didChangeDependencies() async {
  633. super.didChangeDependencies();
  634. _log.info("didChangeDependencies");
  635. }
  636. // ✅ 优化:增强资源释放顺序和完整性
  637. @override
  638. dispose() {
  639. MemoryMonitor.logMemoryUsage('BoardPlay dispose (before)');
  640. _log.info('dispose - starting cleanup');
  641. // ✅ 1. 先停止所有动画(防止回调访问已销毁的资源)
  642. _moveAnimationController.stop();
  643. _mergeAnimationController.stop();
  644. _prepareAnimationController.stop();
  645. dealingAnimationController.stop();
  646. flipAnimationController.stop();
  647. _successAnimationController.stop();
  648. _hardModeBannerController.stop();
  649. // ✅ 2. 取消所有定时器
  650. timer.cancel();
  651. _dealingPeriodicTimer?.cancel();
  652. _resourceCleanupTimer?.cancel();
  653. // ✅ 3. 清理原生 Banner
  654. cleanBanner();
  655. // ✅ 4. 移除监听器
  656. itemLoader.progress.removeListener(_onProgressUpdate);
  657. _moveAnimationController.removeListener(_moveAnimationListener);
  658. _moveAnimationController.removeStatusListener(_moveAnimationStatusListener);
  659. _mergeAnimationController.removeListener(_mergeAnimationListener);
  660. _mergeAnimationController.removeStatusListener(_mergeAnimationStatusListener);
  661. _prepareAnimationController.removeListener(_prepareAnimationListener);
  662. _prepareAnimationController.removeStatusListener(_prepareAnimationStatusListener);
  663. dealingAnimationController.removeListener(_dealingAnimationListener);
  664. dealingAnimationController.removeStatusListener(_dealingAnimationStatusListener);
  665. flipAnimationController.removeListener(_flipAnimationListener);
  666. flipAnimationController.removeStatusListener(_flipAnimationStatusListener);
  667. _successAnimationController.removeListener(_successAnimationListener);
  668. _successAnimationController.removeStatusListener(_successAnimationStatusListener);
  669. // ✅ 5. 释放动画控制器
  670. _moveAnimationController.dispose();
  671. _mergeAnimationController.dispose();
  672. _prepareAnimationController.dispose();
  673. dealingAnimationController.dispose();
  674. flipAnimationController.dispose();
  675. _successAnimationController.dispose();
  676. _hardModeBannerController.dispose();
  677. // ✅ 6. 清空动画数据
  678. moveItems = null;
  679. _mergeGroups = null;
  680. // ✅ 7. 释放其他资源
  681. confettiLayer.dispose();
  682. _overLayer?.destroy();
  683. _overLayer = null;
  684. // ✅ 8. 最后释放 Board(最大的内存占用)
  685. board?.dispose();
  686. board = null;
  687. MemoryMonitor.logMemoryUsage('BoardPlay dispose (after)');
  688. _log.info('dispose - cleanup complete');
  689. super.dispose();
  690. }
  691. @override
  692. onInactive() {
  693. super.onInactive();
  694. saveProgress();
  695. }
  696. // 🔥 优化:页面退出时先保存再清理
  697. void _onWillPop(bool didPop, dynamic result) async {
  698. _log.info('board play will pop, didPop=$didPop, result=$result');
  699. if (didPop) return;
  700. // 立即停止所有动画,防止在销毁过程中动画还在执行 setState
  701. _moveAnimationController.stop();
  702. _mergeAnimationController.stop();
  703. _prepareAnimationController.stop();
  704. dealingAnimationController.stop();
  705. // 🔥 先清理 banner 广告资源,再清理其他资源
  706. cleanBanner();
  707. // 🔥 先保存进度,再清理资源
  708. saveProgress();
  709. // 延迟清理,确保保存完成
  710. Future.delayed(const Duration(milliseconds: 100)).then((_) {
  711. if (board != null) {
  712. _log.info('Cleaning up board resources on page exit');
  713. board!.dispose();
  714. board = null;
  715. }
  716. });
  717. if (!mounted) return;
  718. Navigator.of(context).pop(result);
  719. }
  720. @override
  721. Widget build(BuildContext context) {
  722. Device device = context.read<Device>();
  723. return PopScope(
  724. canPop: false,
  725. onPopInvokedWithResult: _onWillPop,
  726. child: Scaffold(
  727. body: Stack(
  728. children: <Widget>[
  729. if (!_isLoading) Positioned.fill(child: _buildPuzzleCanvas(device.screenSize.width, device.screenSize.height)),
  730. if (board == null || board!.status != BoardStatus.success) Positioned(top: 0, left: 0, right: 0, child: appBar),
  731. Positioned(
  732. bottom: 0,
  733. left: 0,
  734. right: 0,
  735. child: SafeArea(
  736. child: SizedBox(
  737. height: context.read<Device>().bannerHeight,
  738. width: double.infinity,
  739. // ⚠️ 关键优化:只有在延迟加载标记为 true 时才渲染 Banner
  740. child: (isBannerVisible && _bannerDelayedLoad) ? getBanner('playBottom') : const SizedBox.shrink(),
  741. ),
  742. ),
  743. ),
  744. successBanner,
  745. nextButton,
  746. // Release模式下显示内存信息
  747. if (Config.isDebug) Positioned(top: 100, right: 10, child: MemoryMonitor.getMemoryWidget()),
  748. if (_isLoading)
  749. Positioned.fill(
  750. child: Container(
  751. color: SkinHelper.wholeBgColor,
  752. child: const Center(child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(Colors.white))),
  753. ),
  754. ),
  755. ],
  756. ),
  757. ),
  758. );
  759. }
  760. Widget get appBar => SafeArea(
  761. child: Padding(
  762. padding: const EdgeInsets.symmetric(horizontal: 30.0, vertical: 10.0),
  763. child: Row(
  764. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  765. crossAxisAlignment: CrossAxisAlignment.center,
  766. children: [
  767. const SizedBox(width: 30),
  768. Text(
  769. board != null && board!.status == BoardStatus.success
  770. ? AppLocalizations.of(context)!.levelPass
  771. : '${AppLocalizations.of(context)!.level} ${data.currentLevel + 1}',
  772. style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w600),
  773. ),
  774. SizedBox(
  775. width: 30,
  776. height: 30,
  777. child: IconButton(
  778. icon: const Icon(Icons.settings, color: Colors.white, size: 22),
  779. iconSize: 22,
  780. padding: EdgeInsets.zero,
  781. onPressed: () {
  782. audio.playSfx(SfxType.click);
  783. saveProgress();
  784. Navigator.push(context, SettingsDialog.buildRoute(showReturn: true, showRestart: true, item: widget.item));
  785. },
  786. style: ButtonStyle(
  787. backgroundColor: WidgetStateProperty.all(SkinHelper.slotBorderColor),
  788. shape: WidgetStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(15))),
  789. minimumSize: WidgetStateProperty.all(const Size(30, 30)),
  790. maximumSize: WidgetStateProperty.all(const Size(30, 30)),
  791. ),
  792. ),
  793. ),
  794. ],
  795. ),
  796. ),
  797. );
  798. Widget _buildPuzzleCanvas(double width, double height) {
  799. // ✅ 此时如果为了播广告已经把 board 释放了,直接返回空,避免任何 GPU 绘制指令
  800. if (board == null) {
  801. return Container(color: SkinHelper.wholeBgColor);
  802. }
  803. return RepaintBoundary(
  804. child: CustomPaint(
  805. painter: BoardPainter(board: board!, prepareAnimation: _prepareAnimationController),
  806. size: Size(width, height),
  807. child: GestureDetector(
  808. key: boardKey,
  809. onPanStart: _onPanStart,
  810. onPanUpdate: _onPanUpdate,
  811. onPanEnd: _onPanEnd,
  812. child: board != null && board!.hard && _showHardModeBanner ? _hardModeBanner : Container(color: Colors.transparent),
  813. ),
  814. ),
  815. );
  816. }
  817. Widget get _hardModeBanner => Center(
  818. child: AnimatedBuilder(
  819. animation: _hardModeBannerController,
  820. builder: (context, child) {
  821. return FadeTransition(
  822. opacity: _bannerFadeAnimation,
  823. child: ScaleTransition(scale: _bannerScaleAnimation, child: child),
  824. );
  825. },
  826. child: Container(
  827. width: double.infinity,
  828. height: 60,
  829. margin: const EdgeInsets.symmetric(horizontal: 10),
  830. decoration: BoxDecoration(
  831. color: Colors.red,
  832. borderRadius: BorderRadius.circular(10),
  833. border: Border.all(color: const Color.fromARGB(255, 247, 143, 135), width: 2),
  834. boxShadow: [BoxShadow(color: Color.fromRGBO(0, 0, 0, 0.3), blurRadius: 5, offset: const Offset(0, 3))],
  835. ),
  836. child: Center(
  837. child: Text(
  838. AppLocalizations.of(context)!.hardMode,
  839. style: TextStyle(color: Colors.white, fontSize: 30, fontWeight: FontWeight.bold),
  840. ),
  841. ),
  842. ),
  843. ),
  844. );
  845. bool _isExiting = false;
  846. Widget get nextButton {
  847. Device device = context.read<Device>();
  848. return AnimatedBuilder(
  849. animation: _bottomSlideAnimation,
  850. builder: (context, child) {
  851. return AnimatedPositioned(
  852. duration: _successAnimationController.duration!,
  853. bottom: _bottomSlideAnimation.value,
  854. left: (device.screenSize.width - 200) / 2,
  855. child: child!,
  856. );
  857. },
  858. child: MyElevatedButton(
  859. width: 200,
  860. borderRadius: BorderRadius.circular(20),
  861. gradient: LinearGradient(colors: [SkinHelper.coreBgColor, SkinHelper.slotBorderColor]),
  862. onPressed: () async {
  863. if (_isExiting) return;
  864. _isExiting = true;
  865. audio.playSfx(SfxType.click);
  866. // 🔥 策略:在广告弹出前,先主动销毁最占资源的 Board 和 UI Image
  867. // 此时用户已经看到成功界面,底层画布即使变白也没关系(被动画层挡住了)
  868. // MemoryMonitor().manualCleanup(); // 广告前清理
  869. if (board != null) {
  870. _log.info('Pre-Ad Cleanup: Disposing board to free GPU memory');
  871. board!.dispose();
  872. board = null;
  873. }
  874. // 尝试直接pop up, 不等待返回结果,避免用户等待广告结束后才看到界面响应
  875. if (data.currentLevel % 25 != 0) {
  876. // 完成一个合集的最后一张图, 这个时候不展示插屏广告, 因为返回首页需要展示一系列的动画
  877. showInterstitialAd('level_done', widget.item.id, data.currentLevel - 1);
  878. }
  879. _safePop(result: true); // 返回true表示关卡完成
  880. },
  881. child: Text(AppLocalizations.of(context)!.next, style: TextStyle(color: Colors.white, fontSize: 20)),
  882. ),
  883. );
  884. }
  885. void _safePop({bool result = true}) {
  886. if (!mounted) return;
  887. final navigator = Navigator.of(context);
  888. if (navigator.canPop()) {
  889. navigator.pop(result);
  890. }
  891. }
  892. Widget get successBanner {
  893. Device device = context.read<Device>();
  894. final bannerWidth = device.screenSize.width - 40 * 2;
  895. final bannerHeight = 60.0;
  896. return AnimatedBuilder(
  897. animation: _bottomSlideAnimation,
  898. builder: (context, child) {
  899. return AnimatedPositioned(duration: _successAnimationController.duration!, top: _topSlideAnimation.value, left: 40, child: child!);
  900. },
  901. child: SizedBox(
  902. width: bannerWidth,
  903. height: bannerHeight,
  904. child: Stack(
  905. children: [
  906. Image.asset(
  907. 'assets/images/banner.png',
  908. width: double.infinity,
  909. height: double.infinity,
  910. fit: BoxFit.cover,
  911. cacheWidth: (context.watch<Device>().realPixelRatio * bannerWidth).toInt(),
  912. cacheHeight: (context.watch<Device>().realPixelRatio * bannerHeight).toInt(),
  913. ),
  914. Center(
  915. child: Padding(
  916. padding: EdgeInsets.only(top: 16.0),
  917. child: Text(
  918. AppLocalizations.of(context)!.levelPass,
  919. style: TextStyle(
  920. color: Colors.white,
  921. fontSize: 22,
  922. fontWeight: FontWeight.bold,
  923. shadows: [Shadow(color: Colors.black54, offset: Offset(1, 1), blurRadius: 2)],
  924. ),
  925. ),
  926. ),
  927. ),
  928. ],
  929. ),
  930. ),
  931. );
  932. }
  933. // 手势处理方法保持原有逻辑...
  934. Offset _globalToLocal(Offset globalPosition) {
  935. final RenderBox renderBox = boardKey.currentContext!.findRenderObject() as RenderBox;
  936. return renderBox.globalToLocal(globalPosition);
  937. }
  938. void _onPanStart(DragStartDetails details) {
  939. _log.info('_onPanStart');
  940. _overLayer?.stopHint();
  941. if (board!.status != BoardStatus.playing) {
  942. _log.info('不是playing状态,不响应onPanStart');
  943. return;
  944. }
  945. if (board!.checkWinCondition()) {
  946. _log.info('游戏已经完成,不再响应onPanStart');
  947. return;
  948. }
  949. // 动画中断逻辑
  950. if (_moveAnimationController.isAnimating && moveItems != null) {
  951. _log.info('移动动画中断,强制归位/交换');
  952. for (var item in moveItems!) {
  953. item.stop();
  954. }
  955. bool needRebuildGroup = moveItems!.any((item) => item.action == Action.swap);
  956. if (needRebuildGroup) {
  957. board!.backupAllGroups();
  958. board!.rebuildAllGroups();
  959. }
  960. moveItems = null;
  961. _moveAnimationController.stop();
  962. board!.invalidate();
  963. }
  964. if (_mergeAnimationController.isAnimating && _mergeGroups != null) {
  965. _log.info('合并动画中断,强制归位');
  966. for (var group in _mergeGroups!) {
  967. for (var piece in group.pieces) {
  968. piece.transform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  969. }
  970. }
  971. _mergeGroups = null;
  972. _mergeAnimationController.stop();
  973. board!.invalidate();
  974. }
  975. _moveAnimationController.stop();
  976. _mergeAnimationController.stop();
  977. moveItems = null;
  978. final localPosition = _globalToLocal(details.globalPosition);
  979. final touchedPiece = board?.findPieceAt(localPosition);
  980. if (touchedPiece != null) {
  981. audio.playSfx(SfxType.panstart);
  982. if (settings.vibrate.value) {
  983. if (Platform.isAndroid) {
  984. Vibration.vibrate(duration: 60, amplitude: 50);
  985. } else {
  986. HapticFeedback.mediumImpact();
  987. }
  988. }
  989. _draggingPiece = touchedPiece;
  990. final draggingGroup = _draggingPiece!.group;
  991. if (draggingGroup != null) {
  992. board!.pieces.removeWhere((p) => draggingGroup.contains(p));
  993. board!.pieces.addAll(draggingGroup.pieces);
  994. } else {
  995. board!.pieces.remove(_draggingPiece);
  996. board!.pieces.add(_draggingPiece!);
  997. }
  998. board!.invalidate();
  999. }
  1000. }
  1001. void _onPanUpdate(DragUpdateDetails details) {
  1002. _overLayer?.stopHint();
  1003. if (_draggingPiece == null) return;
  1004. final Offset delta = details.delta;
  1005. final draggingGroup = _draggingPiece!.group;
  1006. if (draggingGroup != null) {
  1007. for (var piece in draggingGroup.pieces) {
  1008. piece.applyDelta(delta);
  1009. }
  1010. } else {
  1011. _draggingPiece!.applyDelta(delta);
  1012. }
  1013. board!.invalidate();
  1014. }
  1015. void _onPanEnd(DragEndDetails details) {
  1016. _log.info('_onPanEnd');
  1017. _overLayer?.stopHint();
  1018. if (_draggingPiece == null) return;
  1019. audio.playSfx(SfxType.tap);
  1020. Piece leaderPiece = _draggingPiece!;
  1021. _draggingPiece = null;
  1022. board!.invalidate();
  1023. Piece? targetPiece = board!.findPieceAtExclude(leaderPiece.currentCenter, leaderPiece);
  1024. if (targetPiece == null && leaderPiece.group != null) {
  1025. for (var p in leaderPiece.group!.pieces) {
  1026. targetPiece = board!.findPieceAtExclude(p.currentCenter, p);
  1027. if (targetPiece != null) {
  1028. _log.info('推举 ${p.toString()} 为新leader');
  1029. leaderPiece = p;
  1030. break;
  1031. }
  1032. }
  1033. }
  1034. if (targetPiece != null && targetPiece != leaderPiece && leaderPiece.canPlaceTo(targetPiece)) {
  1035. _log.info("swap animation start");
  1036. _animateSwap(leaderPiece, targetPiece);
  1037. } else {
  1038. _log.info("revert animation start");
  1039. _animateRevert(leaderPiece);
  1040. }
  1041. }
  1042. void _animateSwap(Piece leaderPiece, Piece targetPiece) {
  1043. List<MoveItem> items = [];
  1044. final List<Piece> draggingPieces = leaderPiece.group != null ? leaderPiece.group!.pieces : [leaderPiece];
  1045. final int dr = targetPiece.curRow - leaderPiece.curRow;
  1046. final int dc = targetPiece.curCol - leaderPiece.curCol;
  1047. List<Piece> displacedPieces = [];
  1048. if (leaderPiece.group != null) {
  1049. for (var p in draggingPieces) {
  1050. final int targetRow = p.curRow + dr;
  1051. final int targetCol = p.curCol + dc;
  1052. final Piece? other = board!.getPieceByCoordinate(targetRow, targetCol);
  1053. if (other != null && !p.isSameGroup(other)) {
  1054. displacedPieces.add(other);
  1055. }
  1056. }
  1057. } else {
  1058. displacedPieces.add(targetPiece);
  1059. }
  1060. for (var p in draggingPieces) {
  1061. p.curRow += dr;
  1062. p.curCol += dc;
  1063. }
  1064. if (leaderPiece.group == null) {
  1065. targetPiece.curRow -= dr;
  1066. targetPiece.curCol -= dc;
  1067. } else {
  1068. for (var p in displacedPieces) {
  1069. int newRow = p.curRow - dr;
  1070. int newCol = p.curCol - dc;
  1071. do {
  1072. final Piece? pieceInSlot = board!.getPieceByCoordinate(newRow, newCol);
  1073. if (pieceInSlot == null) {
  1074. p.curRow = newRow;
  1075. p.curCol = newCol;
  1076. break;
  1077. } else {
  1078. newRow -= dr;
  1079. newCol -= dc;
  1080. }
  1081. } while (newRow >= 0 && newRow < p.rows && newCol >= 0 && newCol < p.cols);
  1082. }
  1083. }
  1084. for (var p in displacedPieces) {
  1085. final startTransform = p.transform;
  1086. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  1087. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  1088. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.swap));
  1089. board!.pieces.remove(p);
  1090. board!.pieces.add(p);
  1091. }
  1092. for (var p in draggingPieces) {
  1093. final startTransform = p.transform;
  1094. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  1095. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  1096. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.swap));
  1097. board!.pieces.remove(p);
  1098. board!.pieces.add(p);
  1099. }
  1100. moveItems = items;
  1101. _moveAnimationController.forward(from: 0.0);
  1102. }
  1103. void _animateRevert(Piece piece) {
  1104. List<MoveItem> items = [];
  1105. final List<Piece> groupPieces = piece.group != null ? piece.group!.pieces : [piece];
  1106. for (var p in groupPieces) {
  1107. final startTransform = p.transform;
  1108. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  1109. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  1110. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.revert));
  1111. }
  1112. moveItems = items;
  1113. _moveAnimationController.forward(from: 0.0);
  1114. }
  1115. }
  1116. class Matrix4Tween extends Tween<vmath.Matrix4> {
  1117. Matrix4Tween({required vmath.Matrix4 begin, required vmath.Matrix4 end}) : super(begin: begin, end: end);
  1118. @override
  1119. vmath.Matrix4 lerp(double t) {
  1120. if (begin == null || end == null) return begin ?? end ?? vmath.Matrix4.identity();
  1121. final List<double> lerpedStorage = List.generate(16, (i) {
  1122. return ui.lerpDouble(begin!.storage[i], end!.storage[i], t)!;
  1123. });
  1124. return vmath.Matrix4.fromList(lerpedStorage.cast<double>());
  1125. }
  1126. }
  1127. class MoveItem {
  1128. final Piece piece;
  1129. final Animation<vmath.Matrix4> animation;
  1130. final vmath.Matrix4 startTransform;
  1131. final vmath.Matrix4 endTransform;
  1132. final Action action;
  1133. MoveItem({required this.piece, required this.animation, required this.startTransform, required this.endTransform, required this.action});
  1134. void move() {
  1135. piece.transform = animation.value;
  1136. }
  1137. void stop() {
  1138. piece.transform = endTransform;
  1139. }
  1140. }