board_play.dart 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. import 'dart:math';
  2. import 'dart:typed_data';
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter/services.dart';
  5. import 'package:image_puzzle/config/device.dart';
  6. import 'package:image_puzzle/play/board.dart';
  7. import 'package:image_puzzle/play/board_painter.dart';
  8. import 'package:image_puzzle/play/piece.dart';
  9. import 'package:logging/logging.dart';
  10. import 'package:provider/provider.dart';
  11. import 'dart:ui' as ui;
  12. import 'package:vector_math/vector_math.dart' as vmath;
  13. final Logger _log = Logger('board_play.dart');
  14. // 移动类型 (不再需要,但保留枚举以防止其他文件引用报错)
  15. enum MoveType {
  16. group, // 整个群组一起移动
  17. single, // 单个碎片移动
  18. }
  19. // 操作类型
  20. enum Action {
  21. revert, // 回归
  22. swap, // 交换
  23. }
  24. class BoardPlay extends StatefulWidget {
  25. final int cols;
  26. final int rows;
  27. const BoardPlay({super.key, required this.cols, required this.rows});
  28. @override
  29. State<StatefulWidget> createState() {
  30. return _BoardPlayState();
  31. }
  32. }
  33. class _BoardPlayState extends State<BoardPlay> with TickerProviderStateMixin {
  34. final GlobalKey boardKey = GlobalKey();
  35. Board? board;
  36. bool _isLoading = true;
  37. Piece? _draggingPiece;
  38. // 记录所有动画中的移动项 (位移/交换/归位)
  39. List<MoveItem>? moveItems;
  40. // 动画控制器
  41. late AnimationController _moveAnimationController; // 移动动画(位移)
  42. late AnimationController _mergeAnimationController; // merge动画(scale)
  43. // merge 动画的缩放值
  44. late Animation<double> _mergeScaleAnimation;
  45. List<PieceGroup>? _mergeGroups; // 记录当前merge的group
  46. late AnimationController _prepareAnimationController; // 预备动画, Opacity透明动画展示核心绘制区
  47. late AnimationController dealingAnimationController; // 发牌动画
  48. late AnimationController flipAnimationController; // 翻牌动画
  49. // 发牌动画相关
  50. late Animation<double> _dealingAnimation;
  51. // 发牌动画参数
  52. List<double> _pieceStartTimes = []; // 每个卡片的启动时间(单位:ms)
  53. List<double> _pieceDurations = []; // 每个卡片的移动持续时间(单位:ms)
  54. double _totalDealingDuration = 0; // 发牌动画总时长(ms)
  55. @override
  56. initState() {
  57. super.initState();
  58. // 初始化移动动画,在dragging结束松手后的swap或evert操作都需要用到移动
  59. _moveAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
  60. _moveAnimationController.addListener(_moveAnimationListener);
  61. _moveAnimationController.addStatusListener(_moveAnimationStatusListener);
  62. // 初始化 Merge 动画
  63. _mergeAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300)); // 0.4s for scale up/down
  64. _mergeAnimationController.addListener(_mergeAnimationListener);
  65. _mergeAnimationController.addStatusListener(_mergeAnimationStatusListener);
  66. // 缩放值从 1.0 -> 1.1 -> 1.0 (使用 TweenSequence 实现放大再缩小)
  67. _mergeScaleAnimation =
  68. TweenSequence<double>([
  69. TweenSequenceItem(tween: Tween<double>(begin: 1.0, end: 1.06), weight: 50),
  70. TweenSequenceItem(tween: Tween<double>(begin: 1.06, end: 1.0), weight: 50),
  71. ]).animate(
  72. // 应用曲线:用 CurvedAnimation 包装控制器
  73. CurvedAnimation(
  74. parent: _mergeAnimationController, // 动画控制器
  75. curve: Curves.easeInOut, // 曲线类型(先加速后减速)
  76. ),
  77. );
  78. _prepareAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 800));
  79. _prepareAnimationController.addListener(_prepareAnimationListener);
  80. _prepareAnimationController.addStatusListener(_prepareAnimationStatusListener);
  81. // 初始化发牌动画
  82. dealingAnimationController = AnimationController(vsync: this);
  83. _dealingAnimation = CurvedAnimation(parent: dealingAnimationController, curve: Curves.linear);
  84. dealingAnimationController.addListener(_dealingAnimationListener);
  85. dealingAnimationController.addStatusListener(_dealingAnimationStatusListener);
  86. // 初始化翻转动画
  87. flipAnimationController = AnimationController(vsync: this, duration: Duration(milliseconds: 1000));
  88. flipAnimationController.addListener(_flipAnimationListener);
  89. flipAnimationController.addStatusListener(_flipAnimationStatusListener);
  90. _init();
  91. }
  92. // 初始化发牌时间点
  93. void _initDealTimes() {
  94. _pieceStartTimes.clear();
  95. _pieceDurations.clear();
  96. // 3. 计算动画参数(速度恒定)
  97. const double interval = 120; // 发牌间隔(ms):每张牌间隔50ms发出
  98. const double maxDuration = 500; // 最长移动时间(ms):距离最远的卡片用1000ms
  99. // 为每个卡片计算启动时间和持续时间
  100. for (int i = 0; i < board!.pieces.length; i++) {
  101. // final duration = maxDuration - i * interval;
  102. // 启动时间:第1张0ms,第2张50ms,第3张100ms...)
  103. final startTime = i * interval;
  104. _pieceStartTimes.add(startTime);
  105. _pieceDurations.add(maxDuration);
  106. }
  107. // 总动画时长 = 最后一张卡片的启动时间 + 其持续时间
  108. _totalDealingDuration = _pieceStartTimes.last + _pieceDurations.last;
  109. // 更新动画控制器时长
  110. dealingAnimationController.duration = Duration(milliseconds: _totalDealingDuration.round());
  111. }
  112. void _dealingAnimationListener() {
  113. if (board == null) return;
  114. // 当前动画已运行的时间(ms)
  115. final currentTime = _dealingAnimation.value * _totalDealingDuration;
  116. // 逐个更新卡片位置(最后一张不需要动)
  117. for (int i = 0; i < board!.pieces.length - 1; i++) {
  118. final piece = board!.pieces[i];
  119. final startTime = _pieceStartTimes[i];
  120. final duration = _pieceDurations[i];
  121. // 尚未到启动时间:保持在起点
  122. if (currentTime < startTime) {
  123. continue;
  124. }
  125. // 计算移动进度(0~1):已移动时间 / 总持续时间
  126. double progress = (currentTime - startTime) / duration;
  127. progress = progress.clamp(0.0, 1.0); // 限制进度不超过1(防止超调)
  128. // 计算当前位置(起点到终点的插值)
  129. final startTransform = board!.getBottomRightTransform();
  130. final endTransform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  131. final tween = Matrix4Tween(begin: startTransform, end: endTransform);
  132. piece.transform = tween.lerp(progress);
  133. }
  134. board!.invalidate();
  135. }
  136. // 发牌动画状态监听器
  137. void _dealingAnimationStatusListener(AnimationStatus status) {
  138. if (status == AnimationStatus.completed) {
  139. board!.resetAllPieces();
  140. board!.shuffle(ShuffleStep.flipping);
  141. flipAnimationController.forward(from: 0.0);
  142. }
  143. }
  144. // 翻转动画监听器
  145. void _flipAnimationListener() {
  146. if (board == null) return;
  147. final flipValue = flipAnimationController.value;
  148. for (final piece in board!.pieces) {
  149. // 1. 计算翻转角度(0→π,180度翻转)
  150. final angle = flipValue * pi;
  151. // 2. 获取卡片的固定目标位置(基于curRow/curCol,不依赖动态transform)
  152. final targetTranslate = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  153. // 3. 执行翻转动画(传入固定目标位置)
  154. piece.updateFlipTransform(angle, targetTranslate);
  155. }
  156. board!.invalidate();
  157. }
  158. // 翻转动画状态监听器
  159. void _flipAnimationStatusListener(AnimationStatus status) {
  160. if (status == AnimationStatus.completed) {
  161. // 翻转完成,开始游戏
  162. board!.resetAllPieces();
  163. board!.rebuildAllGroups();
  164. // 检查是否初始化就已经merge的group
  165. final mergeGroups = board!.compareAllGroups();
  166. // 有新的区块合成,执行 merge 动画,稍稍放大然后再复原
  167. if (mergeGroups.isNotEmpty) {
  168. _log.info('Merge animation start for ${mergeGroups.length} groups.');
  169. // 启动 Merge 动画
  170. _mergeGroups = mergeGroups;
  171. _mergeAnimationController.forward(from: 0.0);
  172. }
  173. board!.start();
  174. }
  175. }
  176. // 关键修正:动画监听器,只注册一次
  177. void _moveAnimationListener() {
  178. if (moveItems == null || moveItems!.isEmpty) {
  179. return;
  180. }
  181. for (var item in moveItems!) {
  182. item.move();
  183. }
  184. board!.invalidate();
  185. }
  186. void _moveAnimationStatusListener(AnimationStatus status) {
  187. if (status == AnimationStatus.completed) {
  188. // 动画完成,确保所有 piece 都在它们的最终位置(endTransform)
  189. if (moveItems != null) {
  190. bool needRebuildGroup = moveItems!.any((item) => item.action == Action.swap);
  191. // 确保所有 piece 的 transform 最终停留在 endTransform
  192. for (var item in moveItems!) {
  193. item.stop();
  194. }
  195. if (needRebuildGroup) {
  196. board!.backupAllGroups();
  197. board!.rebuildAllGroups();
  198. final mergeGroups = board!.compareAllGroups();
  199. // 有新的区块合成,执行 merge 动画,稍稍放大然后再复原
  200. if (mergeGroups.isNotEmpty) {
  201. _log.info('Merge animation start for ${mergeGroups.length} groups.');
  202. // 启动 Merge 动画
  203. _mergeGroups = mergeGroups;
  204. _mergeAnimationController.forward(from: 0.0);
  205. // 如果执行了 merge 动画,将胜利条件检查推迟到 merge 动画完成时
  206. moveItems = null;
  207. return;
  208. }
  209. }
  210. // 如果没有 merge 发生,或者 move action 是 revert,检查胜利条件
  211. if (board!.checkWinCondition()) {
  212. board!.success();
  213. }
  214. moveItems = null;
  215. }
  216. }
  217. }
  218. // 新增:Merge 动画监听器
  219. void _mergeAnimationListener() {
  220. if (_mergeGroups == null || _mergeGroups!.isEmpty || board == null) {
  221. return;
  222. }
  223. // 当前缩放值 (从 1.0 -> 1.1 -> 1.0)
  224. final double scale = _mergeScaleAnimation.value;
  225. for (var group in _mergeGroups!) {
  226. final groupCenter = group.center;
  227. for (var piece in group.pieces) {
  228. // 1. 获取碎片归位后的基础位置(纯平移)
  229. final baseTransform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  230. // 2. 计算碎片左上角到群组中心的偏移量
  231. final pieceTopLeft = Offset(baseTransform.storage[12], baseTransform.storage[13]);
  232. final offsetToCenter = groupCenter - pieceTopLeft;
  233. // 3. 创建围绕群组中心的缩放矩阵
  234. final scaleMatrix = vmath.Matrix4.identity()
  235. ..translate(offsetToCenter.dx, offsetToCenter.dy) // 移到群组中心
  236. ..scale(scale, scale, 1.0) // 缩放
  237. ..translate(-offsetToCenter.dx, -offsetToCenter.dy); // 移回原位
  238. // 4. 应用最终变换
  239. piece.transform = baseTransform * scaleMatrix;
  240. }
  241. }
  242. board!.invalidate();
  243. }
  244. // 新增:Merge 动画状态监听器
  245. void _mergeAnimationStatusListener(AnimationStatus status) {
  246. if (status == AnimationStatus.completed) {
  247. if (_mergeGroups != null && _mergeGroups!.isNotEmpty) {
  248. for (var group in _mergeGroups!) {
  249. for (var piece in group.pieces) {
  250. piece.transform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  251. }
  252. }
  253. }
  254. _mergeGroups = null;
  255. // 检查胜利条件 (现在所有 pieces 都在正确位置且 scale=1.0)
  256. if (board!.checkWinCondition()) {
  257. board!.success();
  258. }
  259. board!.invalidate();
  260. }
  261. }
  262. void _prepareAnimationListener() {
  263. board!.invalidate();
  264. }
  265. // prepare动画结束,进入洗牌动画
  266. void _prepareAnimationStatusListener(AnimationStatus status) {
  267. if (status == AnimationStatus.completed) {
  268. _initDealTimes();
  269. board!.setAllPieceToBottomRight();
  270. board!.shuffle(ShuffleStep.dealing);
  271. dealingAnimationController.forward(from: 0.0);
  272. }
  273. }
  274. _init() async {
  275. Device device = context.read<Device>();
  276. setState(() {
  277. _isLoading = true;
  278. });
  279. final dpr = device.devicePixelRatio;
  280. final targetRect = device.targetRect;
  281. final bestImageSize = device.bestImageSize;
  282. // 加载图片,后续改为从远程服务器加载, 目前demo从本地assets读取
  283. final ByteData data = await rootBundle.load('assets/images/test.jpeg');
  284. final ui.Codec codec = await ui.instantiateImageCodec(
  285. data.buffer.asUint8List(),
  286. targetWidth: bestImageSize.width.round(),
  287. targetHeight: bestImageSize.height.round(),
  288. );
  289. final ui.FrameInfo frameInfo = await codec.getNextFrame();
  290. final image = frameInfo.image;
  291. // 加载扑克背面图片,用于制作发牌动画
  292. final Size bestCardImageSize = Size(targetRect.width * dpr / widget.rows, targetRect.height * dpr / widget.cols);
  293. final ByteData cardData = await rootBundle.load('assets/images/backcard.png');
  294. final ui.Codec cardCodec = await ui.instantiateImageCodec(
  295. cardData.buffer.asUint8List(),
  296. targetWidth: bestCardImageSize.width.round(),
  297. targetHeight: bestCardImageSize.height.round(),
  298. );
  299. final ui.FrameInfo cardFrameInfo = await cardCodec.getNextFrame();
  300. final cardImage = cardFrameInfo.image;
  301. board = Board(this, image, cardImage, widget.rows, widget.cols, targetRect, device);
  302. board!.prepare();
  303. _prepareAnimationController.forward(from: 0.0);
  304. if (!mounted) return;
  305. setState(() {
  306. _isLoading = false;
  307. });
  308. }
  309. @override
  310. void didChangeDependencies() async {
  311. super.didChangeDependencies();
  312. _log.info("didChangeDependencies");
  313. }
  314. @override
  315. dispose() {
  316. _moveAnimationController.removeListener(_moveAnimationListener);
  317. _moveAnimationController.removeStatusListener(_moveAnimationStatusListener);
  318. _moveAnimationController.dispose();
  319. _mergeAnimationController.removeListener(_mergeAnimationListener);
  320. _mergeAnimationController.removeStatusListener(_mergeAnimationStatusListener);
  321. _mergeAnimationController.dispose();
  322. _prepareAnimationController.removeListener(_prepareAnimationListener);
  323. _prepareAnimationController.removeStatusListener(_prepareAnimationStatusListener);
  324. _prepareAnimationController.dispose();
  325. dealingAnimationController.removeListener(_dealingAnimationListener);
  326. dealingAnimationController.removeStatusListener(_dealingAnimationStatusListener);
  327. dealingAnimationController.dispose();
  328. flipAnimationController.removeListener(_flipAnimationListener);
  329. flipAnimationController.removeStatusListener(_flipAnimationStatusListener);
  330. flipAnimationController.dispose();
  331. board?.dispose();
  332. super.dispose();
  333. }
  334. @override
  335. Widget build(BuildContext context) {
  336. Device device = context.read<Device>();
  337. return Scaffold(
  338. body: Stack(
  339. children: <Widget>[
  340. if (!_isLoading) Positioned.fill(child: _buildPuzzleCanvas(device.screenSize.width, device.screenSize.height)),
  341. Positioned(top: 0, left: 0, right: 0, child: appBar),
  342. Positioned(
  343. bottom: 0,
  344. left: 0,
  345. right: 0,
  346. child: Container(
  347. height: device.bannerHeight,
  348. color: Colors.green.shade100,
  349. alignment: Alignment.center,
  350. child: const Text('Banner 广告区域', style: TextStyle(fontSize: 12)),
  351. ),
  352. ),
  353. if (_isLoading)
  354. Positioned.fill(
  355. child: Container(
  356. color: Colors.lightGreen, // 填充绿色背景(可根据需要调整色值,如 Colors.green.shade100 浅绿)
  357. child: const Center(
  358. child: CircularProgressIndicator(
  359. // 可选:调整进度条颜色,与绿色背景对比更明显
  360. valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
  361. ),
  362. ),
  363. ),
  364. ),
  365. ],
  366. ),
  367. );
  368. }
  369. final appBar = SafeArea(
  370. child: Center(
  371. child: Padding(
  372. padding: const EdgeInsets.all(10.0),
  373. child: Text(
  374. '关卡1',
  375. style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w600),
  376. ),
  377. ),
  378. ),
  379. );
  380. Widget _buildPuzzleCanvas(double width, double height) {
  381. return CustomPaint(
  382. painter: BoardPainter(board: board!, prepareAnimation: _prepareAnimationController),
  383. size: Size(width, height),
  384. child: GestureDetector(
  385. key: boardKey,
  386. onPanStart: _onPanStart,
  387. onPanUpdate: _onPanUpdate,
  388. onPanEnd: _onPanEnd,
  389. child: Container(color: Colors.transparent),
  390. ),
  391. );
  392. }
  393. Offset _globalToLocal(Offset globalPosition) {
  394. final RenderBox renderBox = boardKey.currentContext!.findRenderObject() as RenderBox;
  395. return renderBox.globalToLocal(globalPosition);
  396. }
  397. void _onPanStart(DragStartDetails details) {
  398. _log.info('_onPanStart');
  399. // 动画中断逻辑:如果动画正在进行,立即停止并强制所有 pieces 归位到最终位置
  400. if (_moveAnimationController.isAnimating && moveItems != null) {
  401. _log.info('移动动画中断,强制归位/交换');
  402. for (var item in moveItems!) {
  403. item.stop();
  404. }
  405. bool needRebuildGroup = moveItems!.any((item) => item.action == Action.swap);
  406. if (needRebuildGroup) {
  407. board!.backupAllGroups();
  408. board!.rebuildAllGroups();
  409. final mergeGroups = board!.compareAllGroups();
  410. if (mergeGroups.isNotEmpty) {
  411. // 此时不需要触发 merge 动画,只需确保数据结构正确
  412. }
  413. }
  414. moveItems = null; // 清空动画列表
  415. _moveAnimationController.stop();
  416. board!.invalidate(); // 触发一次重绘来显示最终位置
  417. }
  418. // 如果 merge 动画正在进行,也应该中断并立即归位
  419. if (_mergeAnimationController.isAnimating && _mergeGroups != null) {
  420. _log.info('合并动画中断,强制归位');
  421. for (var group in _mergeGroups!) {
  422. for (var piece in group.pieces) {
  423. piece.transform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  424. }
  425. }
  426. _mergeGroups = null;
  427. _mergeAnimationController.stop();
  428. board!.invalidate();
  429. }
  430. // 停止所有正在运行的动画(如果尚未停止)
  431. _moveAnimationController.stop();
  432. _mergeAnimationController.stop();
  433. moveItems = null;
  434. final localPosition = _globalToLocal(details.globalPosition);
  435. final touchedPiece = board?.findPieceAt(localPosition);
  436. if (touchedPiece != null) {
  437. _draggingPiece = touchedPiece;
  438. final draggingGroup = _draggingPiece!.group;
  439. if (draggingGroup != null) {
  440. // 将拖拽群组置于 pieces 列表末尾,确保它在 CustomPainter 中被最后绘制(在最上层)
  441. board!.pieces.removeWhere((p) => draggingGroup.contains(p));
  442. board!.pieces.addAll(draggingGroup.pieces);
  443. } else {
  444. board!.pieces.remove(_draggingPiece);
  445. board!.pieces.add(_draggingPiece!);
  446. }
  447. board!.invalidate();
  448. }
  449. }
  450. void _onPanUpdate(DragUpdateDetails details) {
  451. _log.info('_onPanUpdate');
  452. if (_draggingPiece == null) return;
  453. final Offset delta = details.delta;
  454. final draggingGroup = _draggingPiece!.group;
  455. if (draggingGroup != null) {
  456. // 拖拽过程中,所有群组成员共享相同的位移
  457. for (var piece in draggingGroup.pieces) {
  458. piece.applyDelta(delta);
  459. }
  460. } else {
  461. _draggingPiece!.applyDelta(delta);
  462. }
  463. board!.invalidate();
  464. }
  465. void _onPanEnd(DragEndDetails details) {
  466. _log.info('_onPanEnd');
  467. if (_draggingPiece == null) {
  468. return;
  469. }
  470. // 保存当前拖拽结束的碎片,以备动画使用
  471. Piece leaderPiece = _draggingPiece!;
  472. _draggingPiece = null; // 结束拖拽
  473. board!.invalidate();
  474. /// 交换或归位
  475. // 获取碎片的中心点,判断中心点是否落到某个piece上
  476. Piece? targetPiece = board!.findPieceAtExclude(leaderPiece.currentCenter, leaderPiece);
  477. // 群组特殊处理:如果 leaderPiece 没有落在其他碎片上,检查群组其他成员
  478. if (targetPiece == null && leaderPiece.group != null) {
  479. for (var p in leaderPiece.group!.pieces) {
  480. targetPiece = board!.findPieceAtExclude(p.currentCenter, p);
  481. if (targetPiece != null) {
  482. _log.info('推举 ${p.toString()} 为新leader');
  483. leaderPiece = p; // p 落在有效的其他piece上,推举为leaderPiece
  484. break;
  485. }
  486. }
  487. }
  488. // 判断是否可以交换
  489. if (targetPiece != null && targetPiece != leaderPiece && leaderPiece.canPlaceTo(targetPiece)) {
  490. _log.info("swap animation start");
  491. _animateSwap(leaderPiece, targetPiece);
  492. } else {
  493. _log.info("revert animation start");
  494. _animateRevert(leaderPiece);
  495. }
  496. }
  497. // 为所有涉及移动的 piece 创建独立的 MoveItem
  498. void _animateSwap(Piece leaderPiece, Piece targetPiece) {
  499. List<MoveItem> items = [];
  500. // 1. 确定涉及移动的所有碎片
  501. final List<Piece> draggingPieces = leaderPiece.group != null ? leaderPiece.group!.pieces : [leaderPiece];
  502. final int dr = targetPiece.curRow - leaderPiece.curRow; // 目标位置的行位移
  503. final int dc = targetPiece.curCol - leaderPiece.curCol; // 目标位置的列位移
  504. // 2. 识别被替换/推开的碎片
  505. List<Piece> displacedPieces = [];
  506. if (leaderPiece.group != null) {
  507. // 群组交换:找到群组新目标位置上的所有非自身群组的碎片
  508. for (var p in draggingPieces) {
  509. final int targetRow = p.curRow + dr;
  510. final int targetCol = p.curCol + dc;
  511. final Piece? other = board!.getPieceByCoordinate(targetRow, targetCol);
  512. if (other != null && !p.isSameGroup(other)) {
  513. displacedPieces.add(other);
  514. }
  515. }
  516. } else {
  517. // 单碎片交换:被替换的碎片就是 targetPiece
  518. displacedPieces.add(targetPiece);
  519. }
  520. // 3. 更新逻辑坐标 (curRow, curCol) - 必须在创建动画前完成
  521. // a. 更新拖拽群组/碎片的位置
  522. for (var p in draggingPieces) {
  523. p.curRow += dr;
  524. p.curCol += dc;
  525. }
  526. // b. 更新被推开的碎片的位置 (移入拖拽群组腾出的槽位)
  527. if (leaderPiece.group == null) {
  528. // 单碎片交换:targetPiece 移入 leaderPiece 的旧槽位
  529. targetPiece.curRow -= dr;
  530. targetPiece.curCol -= dc;
  531. } else {
  532. // 群组交换:被推开的碎片向后退 dr/dc 距离,找到空槽位
  533. for (var p in displacedPieces) {
  534. int newRow = p.curRow - dr;
  535. int newCol = p.curCol - dc;
  536. do {
  537. final Piece? pieceInSlot = board!.getPieceByCoordinate(newRow, newCol);
  538. if (pieceInSlot == null) {
  539. p.curRow = newRow;
  540. p.curCol = newCol;
  541. break;
  542. } else {
  543. newRow -= dr;
  544. newCol -= dc;
  545. }
  546. } while (newRow >= 0 && newRow < p.rows && newCol >= 0 && newCol < p.cols);
  547. }
  548. }
  549. // 4. 为所有涉及移动的碎片创建 MoveItem
  550. // a. 拖拽群组/碎片
  551. for (var p in draggingPieces) {
  552. // 动画起点:拖拽结束时的实际 Canvas 坐标 (p.transform)
  553. final startTransform = p.transform;
  554. // 动画终点:新的逻辑网格坐标
  555. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  556. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  557. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.swap));
  558. }
  559. // b. 被推开的碎片
  560. for (var p in displacedPieces) {
  561. // 动画起点:旧的逻辑网格坐标 (p.transform)
  562. final startTransform = p.transform;
  563. // 动画终点:新的逻辑网格坐标
  564. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  565. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  566. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.swap));
  567. }
  568. // 5. 启动动画
  569. moveItems = items;
  570. _moveAnimationController.forward(from: 0.0);
  571. }
  572. // 关键重构:为所有涉及归位的 piece 创建独立的 MoveItem
  573. void _animateRevert(Piece piece) {
  574. List<MoveItem> items = [];
  575. final List<Piece> groupPieces = piece.group != null ? piece.group!.pieces : [piece];
  576. for (var p in groupPieces) {
  577. // 动画起点:拖拽结束时的实际 Canvas 坐标 (p.transform)
  578. final startTransform = p.transform;
  579. // 动画终点:归位位置(即拖拽前所在的逻辑网格坐标)
  580. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  581. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  582. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.revert));
  583. }
  584. moveItems = items;
  585. _moveAnimationController.forward(from: 0.0);
  586. }
  587. }
  588. // 辅助类:用于对 vmath.Matrix4 进行线性插值 (lerp),实现平滑动画
  589. class Matrix4Tween extends Tween<vmath.Matrix4> {
  590. Matrix4Tween({required vmath.Matrix4 begin, required vmath.Matrix4 end}) : super(begin: begin, end: end);
  591. @override
  592. vmath.Matrix4 lerp(double t) {
  593. if (begin == null || end == null) return begin ?? end ?? vmath.Matrix4.identity();
  594. final List<double> lerpedStorage = List.generate(16, (i) {
  595. // 确保使用 ui.lerpDouble 进行插值
  596. return ui.lerpDouble(begin!.storage[i], end!.storage[i], t)!;
  597. });
  598. return vmath.Matrix4.fromList(lerpedStorage.cast<double>());
  599. }
  600. }
  601. // 动画辅助类,记录移动信息
  602. class MoveItem {
  603. // 要移动的piece
  604. final Piece piece;
  605. // 动画animation
  606. final Animation<vmath.Matrix4> animation;
  607. // 起始位置(拖拽结束时的实际 Canvas 坐标)
  608. final vmath.Matrix4 startTransform;
  609. // 结束位置(目标网格槽位的 Canvas 坐标)
  610. final vmath.Matrix4 endTransform;
  611. // 移除了 MoveType,因为现在每个 piece 都有自己的 MoveItem
  612. // final MoveType moveType;
  613. final Action action;
  614. MoveItem({required this.piece, required this.animation, required this.startTransform, required this.endTransform, required this.action});
  615. // 关键修正:直接设置 piece 的 transform 为动画插值
  616. void move() {
  617. // 关键修正:直接设置piece的transform为动画插值,而不是累加delta
  618. piece.transform = animation.value;
  619. }
  620. void stop() {
  621. // 关键修正:动画中断时,直接设置到最终目标位置 (endTransform)
  622. // 此时 piece 的 curRow/curCol 已经是目标网格坐标
  623. piece.transform = endTransform;
  624. }
  625. }