board_play.dart 50 KB

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