board_play.dart 47 KB

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