board_play.dart 60 KB

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