board_play.dart 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. import 'dart:typed_data';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:image_puzzle/config/device.dart';
  5. import 'package:image_puzzle/play/board.dart';
  6. import 'package:image_puzzle/play/board_painter.dart';
  7. import 'package:image_puzzle/play/piece.dart';
  8. import 'package:logging/logging.dart';
  9. import 'package:provider/provider.dart';
  10. import 'dart:ui' as ui;
  11. import 'package:vector_math/vector_math.dart' as vmath;
  12. final Logger _log = Logger('board_play.dart');
  13. // 移动类型 (不再需要,但保留枚举以防止其他文件引用报错)
  14. enum MoveType {
  15. group, // 整个群组一起移动
  16. single, // 单个碎片移动
  17. }
  18. // 操作类型
  19. enum Action {
  20. revert, // 回归
  21. swap, // 交换
  22. }
  23. class BoardPlay extends StatefulWidget {
  24. final int cols;
  25. final int rows;
  26. const BoardPlay({super.key, required this.cols, required this.rows});
  27. @override
  28. State<StatefulWidget> createState() {
  29. return _BoardPlayState();
  30. }
  31. }
  32. class _BoardPlayState extends State<BoardPlay> with TickerProviderStateMixin {
  33. final GlobalKey boardKey = GlobalKey();
  34. Board? board;
  35. bool _isLoading = true;
  36. Piece? _draggingPiece;
  37. // 记录所有动画中的移动项 (位移/交换/归位)
  38. List<MoveItem>? moveItems;
  39. // 动画控制器
  40. late AnimationController _moveAnimationController; // 移动动画(位移)
  41. late AnimationController _mergeAnimationController; // merge动画(scale)
  42. // merge 动画的缩放值
  43. late Animation<double> _mergeScaleAnimation;
  44. List<PieceGroup>? _mergeGroups;
  45. @override
  46. initState() {
  47. super.initState();
  48. _moveAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
  49. _moveAnimationController.addListener(_moveAnimationListener);
  50. _moveAnimationController.addStatusListener(_moveAnimationStatusListener);
  51. // 初始化 Merge 动画
  52. _mergeAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300)); // 0.4s for scale up/down
  53. _mergeAnimationController.addListener(_mergeAnimationListener);
  54. _mergeAnimationController.addStatusListener(_mergeAnimationStatusListener);
  55. // 缩放值从 1.0 -> 1.1 -> 1.0 (使用 TweenSequence 实现放大再缩小)
  56. _mergeScaleAnimation =
  57. TweenSequence<double>([
  58. TweenSequenceItem(tween: Tween<double>(begin: 1.0, end: 1.06), weight: 50),
  59. TweenSequenceItem(tween: Tween<double>(begin: 1.06, end: 1.0), weight: 50),
  60. ]).animate(
  61. // 应用曲线:用 CurvedAnimation 包装控制器
  62. CurvedAnimation(
  63. parent: _mergeAnimationController, // 动画控制器
  64. curve: Curves.easeInOut, // 曲线类型(先加速后减速)
  65. ),
  66. );
  67. init();
  68. }
  69. // 关键修正:动画监听器,只注册一次
  70. void _moveAnimationListener() {
  71. if (moveItems == null || moveItems!.isEmpty) {
  72. return;
  73. }
  74. for (var item in moveItems!) {
  75. item.move();
  76. }
  77. board!.invalidate();
  78. }
  79. void _moveAnimationStatusListener(AnimationStatus status) {
  80. if (status == AnimationStatus.completed) {
  81. // 动画完成,确保所有 piece 都在它们的最终位置(endTransform)
  82. if (moveItems != null) {
  83. bool needRebuildGroup = moveItems!.any((item) => item.action == Action.swap);
  84. // 确保所有 piece 的 transform 最终停留在 endTransform
  85. for (var item in moveItems!) {
  86. item.stop();
  87. }
  88. if (needRebuildGroup) {
  89. board!.backupAllGroups();
  90. board!.rebuildAllGroups();
  91. final mergeGroups = board!.compareAllGroups();
  92. // 有新的区块合成,执行 merge 动画,稍稍放大然后再复原
  93. if (mergeGroups.isNotEmpty) {
  94. _log.info('Merge animation start for ${mergeGroups.length} groups.');
  95. // 启动 Merge 动画
  96. _mergeGroups = mergeGroups;
  97. _mergeAnimationController.forward(from: 0.0);
  98. // 如果执行了 merge 动画,将胜利条件检查推迟到 merge 动画完成时
  99. moveItems = null;
  100. return;
  101. }
  102. }
  103. // 如果没有 merge 发生,或者 move action 是 revert,检查胜利条件
  104. if (board!.checkWinCondition()) {
  105. board!.success();
  106. }
  107. moveItems = null;
  108. }
  109. }
  110. }
  111. // 新增:Merge 动画监听器
  112. void _mergeAnimationListener() {
  113. if (_mergeGroups == null || _mergeGroups!.isEmpty || board == null) {
  114. return;
  115. }
  116. // 当前缩放值 (从 1.0 -> 1.1 -> 1.0)
  117. final double scale = _mergeScaleAnimation.value;
  118. for (var group in _mergeGroups!) {
  119. final groupCenter = group.center;
  120. for (var piece in group.pieces) {
  121. // 1. 获取碎片归位后的基础位置(纯平移)
  122. final baseTransform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  123. // 2. 计算碎片左上角到群组中心的偏移量
  124. final pieceTopLeft = Offset(baseTransform.storage[12], baseTransform.storage[13]);
  125. final offsetToCenter = groupCenter - pieceTopLeft;
  126. // 3. 创建围绕群组中心的缩放矩阵
  127. final scaleMatrix = vmath.Matrix4.identity()
  128. ..translate(offsetToCenter.dx, offsetToCenter.dy) // 移到群组中心
  129. ..scale(scale, scale, 1.0) // 缩放
  130. ..translate(-offsetToCenter.dx, -offsetToCenter.dy); // 移回原位
  131. // 4. 应用最终变换
  132. piece.transform = baseTransform * scaleMatrix;
  133. }
  134. }
  135. board!.invalidate();
  136. }
  137. // 新增:Merge 动画状态监听器
  138. void _mergeAnimationStatusListener(AnimationStatus status) {
  139. if (status == AnimationStatus.completed) {
  140. if (_mergeGroups != null && _mergeGroups!.isNotEmpty) {
  141. for (var group in _mergeGroups!) {
  142. for (var piece in group.pieces) {
  143. piece.transform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  144. }
  145. }
  146. }
  147. _mergeGroups = null;
  148. // 检查胜利条件 (现在所有 pieces 都在正确位置且 scale=1.0)
  149. if (board!.checkWinCondition()) {
  150. board!.success();
  151. }
  152. board!.invalidate();
  153. }
  154. }
  155. init() async {
  156. Device device = context.read<Device>();
  157. setState(() {
  158. _isLoading = true;
  159. });
  160. final targetRect = device.targetRect;
  161. final bestImageSize = device.bestImageSize;
  162. // TODO: 替换为实际的图片加载逻辑
  163. final ByteData data = await rootBundle.load('assets/images/test.jpeg');
  164. final ui.Codec codec = await ui.instantiateImageCodec(
  165. data.buffer.asUint8List(),
  166. targetWidth: bestImageSize.width.round(),
  167. targetHeight: bestImageSize.height.round(),
  168. );
  169. final ui.FrameInfo frameInfo = await codec.getNextFrame();
  170. final image = frameInfo.image;
  171. board = Board(this, image, widget.cols, widget.rows, targetRect, device);
  172. board!.start(); // 游戏开始
  173. setState(() {
  174. _isLoading = false;
  175. });
  176. }
  177. @override
  178. void didChangeDependencies() async {
  179. super.didChangeDependencies();
  180. _log.info("didChangeDependencies");
  181. }
  182. @override
  183. dispose() {
  184. _moveAnimationController.removeListener(_moveAnimationListener);
  185. _moveAnimationController.removeStatusListener(_moveAnimationStatusListener);
  186. _moveAnimationController.dispose();
  187. _mergeAnimationController.removeListener(_mergeAnimationListener);
  188. _mergeAnimationController.removeStatusListener(_mergeAnimationStatusListener);
  189. _mergeAnimationController.dispose();
  190. board?.dispose();
  191. super.dispose();
  192. }
  193. @override
  194. Widget build(BuildContext context) {
  195. Device device = context.read<Device>();
  196. return Scaffold(
  197. body: Stack(
  198. children: <Widget>[
  199. if (!_isLoading) Positioned.fill(child: _buildPuzzleCanvas(device.screenSize.width, device.screenSize.height)),
  200. Positioned(top: 0, left: 0, right: 0, child: appBar),
  201. Positioned(
  202. bottom: 0,
  203. left: 0,
  204. right: 0,
  205. child: Container(
  206. height: device.bannerHeight,
  207. color: Colors.green.shade100,
  208. alignment: Alignment.center,
  209. child: const Text('Banner 广告区域', style: TextStyle(fontSize: 12)),
  210. ),
  211. ),
  212. if (_isLoading) const Positioned.fill(child: Center(child: CircularProgressIndicator())),
  213. ],
  214. ),
  215. );
  216. }
  217. final appBar = SafeArea(
  218. child: Center(
  219. child: Padding(
  220. padding: const EdgeInsets.all(10.0),
  221. child: Text(
  222. '关卡1',
  223. style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w600),
  224. ),
  225. ),
  226. ),
  227. );
  228. Widget _buildPuzzleCanvas(double width, double height) {
  229. return CustomPaint(
  230. painter: BoardPainter(board: board!),
  231. size: Size(width, height),
  232. child: GestureDetector(
  233. key: boardKey,
  234. onPanStart: _onPanStart,
  235. onPanUpdate: _onPanUpdate,
  236. onPanEnd: _onPanEnd,
  237. child: Container(color: Colors.transparent),
  238. ),
  239. );
  240. }
  241. Offset _globalToLocal(Offset globalPosition) {
  242. final RenderBox renderBox = boardKey.currentContext!.findRenderObject() as RenderBox;
  243. return renderBox.globalToLocal(globalPosition);
  244. }
  245. void _onPanStart(DragStartDetails details) {
  246. _log.info('_onPanStart');
  247. // 动画中断逻辑:如果动画正在进行,立即停止并强制所有 pieces 归位到最终位置
  248. if (_moveAnimationController.isAnimating && moveItems != null) {
  249. _log.info('移动动画中断,强制归位/交换');
  250. for (var item in moveItems!) {
  251. item.stop();
  252. }
  253. bool needRebuildGroup = moveItems!.any((item) => item.action == Action.swap);
  254. if (needRebuildGroup) {
  255. board!.backupAllGroups();
  256. board!.rebuildAllGroups();
  257. final mergeGroups = board!.compareAllGroups();
  258. if (mergeGroups.isNotEmpty) {
  259. // 此时不需要触发 merge 动画,只需确保数据结构正确
  260. }
  261. }
  262. moveItems = null; // 清空动画列表
  263. _moveAnimationController.stop();
  264. board!.invalidate(); // 触发一次重绘来显示最终位置
  265. }
  266. // 如果 merge 动画正在进行,也应该中断并立即归位
  267. if (_mergeAnimationController.isAnimating && _mergeGroups != null) {
  268. _log.info('合并动画中断,强制归位');
  269. for (var group in _mergeGroups!) {
  270. for (var piece in group.pieces) {
  271. piece.transform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
  272. }
  273. }
  274. _mergeGroups = null;
  275. _mergeAnimationController.stop();
  276. board!.invalidate();
  277. }
  278. // 停止所有正在运行的动画(如果尚未停止)
  279. _moveAnimationController.stop();
  280. _mergeAnimationController.stop();
  281. moveItems = null;
  282. final localPosition = _globalToLocal(details.globalPosition);
  283. final touchedPiece = board?.findPieceAt(localPosition);
  284. if (touchedPiece != null) {
  285. _draggingPiece = touchedPiece;
  286. final draggingGroup = _draggingPiece!.group;
  287. if (draggingGroup != null) {
  288. // 将拖拽群组置于 pieces 列表末尾,确保它在 CustomPainter 中被最后绘制(在最上层)
  289. board!.pieces.removeWhere((p) => draggingGroup.contains(p));
  290. board!.pieces.addAll(draggingGroup.pieces);
  291. } else {
  292. board!.pieces.remove(_draggingPiece);
  293. board!.pieces.add(_draggingPiece!);
  294. }
  295. board!.invalidate();
  296. }
  297. }
  298. void _onPanUpdate(DragUpdateDetails details) {
  299. _log.info('_onPanUpdate');
  300. if (_draggingPiece == null) return;
  301. final Offset delta = details.delta;
  302. final draggingGroup = _draggingPiece!.group;
  303. if (draggingGroup != null) {
  304. // 拖拽过程中,所有群组成员共享相同的位移
  305. for (var piece in draggingGroup.pieces) {
  306. piece.applyDelta(delta);
  307. }
  308. } else {
  309. _draggingPiece!.applyDelta(delta);
  310. }
  311. board!.invalidate();
  312. }
  313. void _onPanEnd(DragEndDetails details) {
  314. _log.info('_onPanEnd');
  315. if (_draggingPiece == null) {
  316. return;
  317. }
  318. // 保存当前拖拽结束的碎片,以备动画使用
  319. Piece leaderPiece = _draggingPiece!;
  320. _draggingPiece = null; // 结束拖拽
  321. board!.invalidate();
  322. /// 交换或归位
  323. // 获取碎片的中心点,判断中心点是否落到某个piece上
  324. Piece? targetPiece = board!.findPieceAtExclude(leaderPiece.currentCenter, leaderPiece);
  325. // 群组特殊处理:如果 leaderPiece 没有落在其他碎片上,检查群组其他成员
  326. if (targetPiece == null && leaderPiece.group != null) {
  327. for (var p in leaderPiece.group!.pieces) {
  328. targetPiece = board!.findPieceAtExclude(p.currentCenter, p);
  329. if (targetPiece != null) {
  330. _log.info('推举 ${p.toString()} 为新leader');
  331. leaderPiece = p; // p 落在有效的其他piece上,推举为leaderPiece
  332. break;
  333. }
  334. }
  335. }
  336. // 判断是否可以交换
  337. if (targetPiece != null && targetPiece != leaderPiece && leaderPiece.canPlaceTo(targetPiece)) {
  338. _log.info("swap animation start");
  339. _animateSwap(leaderPiece, targetPiece);
  340. } else {
  341. _log.info("revert animation start");
  342. _animateRevert(leaderPiece);
  343. }
  344. }
  345. // 关键重构:为所有涉及移动的 piece 创建独立的 MoveItem
  346. void _animateSwap(Piece leaderPiece, Piece targetPiece) {
  347. List<MoveItem> items = [];
  348. // 1. 确定涉及移动的所有碎片
  349. final List<Piece> draggingPieces = leaderPiece.group != null ? leaderPiece.group!.pieces : [leaderPiece];
  350. final int dr = targetPiece.curRow - leaderPiece.curRow; // 目标位置的行位移
  351. final int dc = targetPiece.curCol - leaderPiece.curCol; // 目标位置的列位移
  352. // 2. 识别被替换/推开的碎片
  353. List<Piece> displacedPieces = [];
  354. if (leaderPiece.group != null) {
  355. // 群组交换:找到群组新目标位置上的所有非自身群组的碎片
  356. for (var p in draggingPieces) {
  357. final int targetRow = p.curRow + dr;
  358. final int targetCol = p.curCol + dc;
  359. final Piece? other = board!.getPieceByCoordinate(targetRow, targetCol);
  360. if (other != null && !p.isSameGroup(other)) {
  361. displacedPieces.add(other);
  362. }
  363. }
  364. } else {
  365. // 单碎片交换:被替换的碎片就是 targetPiece
  366. displacedPieces.add(targetPiece);
  367. }
  368. // 3. 更新逻辑坐标 (curRow, curCol) - 必须在创建动画前完成
  369. // a. 更新拖拽群组/碎片的位置
  370. for (var p in draggingPieces) {
  371. p.curRow += dr;
  372. p.curCol += dc;
  373. }
  374. // b. 更新被推开的碎片的位置 (移入拖拽群组腾出的槽位)
  375. if (leaderPiece.group == null) {
  376. // 单碎片交换:targetPiece 移入 leaderPiece 的旧槽位
  377. targetPiece.curRow -= dr;
  378. targetPiece.curCol -= dc;
  379. } else {
  380. // 群组交换:被推开的碎片向后退 dr/dc 距离,找到空槽位
  381. for (var p in displacedPieces) {
  382. int newRow = p.curRow - dr;
  383. int newCol = p.curCol - dc;
  384. do {
  385. final Piece? pieceInSlot = board!.getPieceByCoordinate(newRow, newCol);
  386. if (pieceInSlot == null) {
  387. p.curRow = newRow;
  388. p.curCol = newCol;
  389. break;
  390. } else {
  391. newRow -= dr;
  392. newCol -= dc;
  393. }
  394. } while (newRow >= 0 && newRow < p.rows && newCol >= 0 && newCol < p.cols);
  395. }
  396. }
  397. // 4. 为所有涉及移动的碎片创建 MoveItem
  398. // a. 拖拽群组/碎片
  399. for (var p in draggingPieces) {
  400. // 动画起点:拖拽结束时的实际 Canvas 坐标 (p.transform)
  401. final startTransform = p.transform;
  402. // 动画终点:新的逻辑网格坐标
  403. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  404. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  405. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.swap));
  406. }
  407. // b. 被推开的碎片
  408. for (var p in displacedPieces) {
  409. // 动画起点:旧的逻辑网格坐标 (p.transform)
  410. final startTransform = p.transform;
  411. // 动画终点:新的逻辑网格坐标
  412. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  413. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  414. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.swap));
  415. }
  416. // 5. 启动动画
  417. moveItems = items;
  418. _moveAnimationController.forward(from: 0.0);
  419. }
  420. // 关键重构:为所有涉及归位的 piece 创建独立的 MoveItem
  421. void _animateRevert(Piece piece) {
  422. List<MoveItem> items = [];
  423. final List<Piece> groupPieces = piece.group != null ? piece.group!.pieces : [piece];
  424. for (var p in groupPieces) {
  425. // 动画起点:拖拽结束时的实际 Canvas 坐标 (p.transform)
  426. final startTransform = p.transform;
  427. // 动画终点:归位位置(即拖拽前所在的逻辑网格坐标)
  428. final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
  429. final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
  430. items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.revert));
  431. }
  432. moveItems = items;
  433. _moveAnimationController.forward(from: 0.0);
  434. }
  435. }
  436. // 辅助类:用于对 vmath.Matrix4 进行线性插值 (lerp),实现平滑动画
  437. class Matrix4Tween extends Tween<vmath.Matrix4> {
  438. Matrix4Tween({required vmath.Matrix4 begin, required vmath.Matrix4 end}) : super(begin: begin, end: end);
  439. @override
  440. vmath.Matrix4 lerp(double t) {
  441. if (begin == null || end == null) return begin ?? end ?? vmath.Matrix4.identity();
  442. final List<double> lerpedStorage = List.generate(16, (i) {
  443. // 确保使用 ui.lerpDouble 进行插值
  444. return ui.lerpDouble(begin!.storage[i], end!.storage[i], t)!;
  445. });
  446. return vmath.Matrix4.fromList(lerpedStorage.cast<double>());
  447. }
  448. }
  449. // 动画辅助类,记录移动信息
  450. class MoveItem {
  451. // 要移动的piece
  452. final Piece piece;
  453. // 动画animation
  454. final Animation<vmath.Matrix4> animation;
  455. // 起始位置(拖拽结束时的实际 Canvas 坐标)
  456. final vmath.Matrix4 startTransform;
  457. // 结束位置(目标网格槽位的 Canvas 坐标)
  458. final vmath.Matrix4 endTransform;
  459. // 移除了 MoveType,因为现在每个 piece 都有自己的 MoveItem
  460. // final MoveType moveType;
  461. final Action action;
  462. MoveItem({required this.piece, required this.animation, required this.startTransform, required this.endTransform, required this.action});
  463. // 关键修正:直接设置 piece 的 transform 为动画插值
  464. void move() {
  465. // 关键修正:直接设置piece的transform为动画插值,而不是累加delta
  466. piece.transform = animation.value;
  467. }
  468. void stop() {
  469. // 关键修正:动画中断时,直接设置到最终目标位置 (endTransform)
  470. // 此时 piece 的 curRow/curCol 已经是目标网格坐标
  471. piece.transform = endTransform;
  472. }
  473. }