board_play.dart 60 KB

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