| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575 |
- import 'dart:typed_data';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
- import 'package:image_puzzle/config/device.dart';
- import 'package:image_puzzle/play/board.dart';
- import 'package:image_puzzle/play/board_painter.dart';
- import 'package:image_puzzle/play/piece.dart';
- import 'package:logging/logging.dart';
- import 'package:provider/provider.dart';
- import 'dart:ui' as ui;
- import 'package:vector_math/vector_math.dart' as vmath;
- final Logger _log = Logger('board_play.dart');
- // 移动类型 (不再需要,但保留枚举以防止其他文件引用报错)
- enum MoveType {
- group, // 整个群组一起移动
- single, // 单个碎片移动
- }
- // 操作类型
- enum Action {
- revert, // 回归
- swap, // 交换
- }
- class BoardPlay extends StatefulWidget {
- final int cols;
- final int rows;
- const BoardPlay({super.key, required this.cols, required this.rows});
- @override
- State<StatefulWidget> createState() {
- return _BoardPlayState();
- }
- }
- class _BoardPlayState extends State<BoardPlay> with TickerProviderStateMixin {
- final GlobalKey boardKey = GlobalKey();
- Board? board;
- bool _isLoading = true;
- Piece? _draggingPiece;
- // 记录所有动画中的移动项 (位移/交换/归位)
- List<MoveItem>? moveItems;
- // 动画控制器
- late AnimationController _moveAnimationController; // 移动动画(位移)
- late AnimationController _mergeAnimationController; // merge动画(scale)
- // merge 动画的缩放值
- late Animation<double> _mergeScaleAnimation;
- List<PieceGroup>? _mergeGroups;
- @override
- initState() {
- super.initState();
- _moveAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
- _moveAnimationController.addListener(_moveAnimationListener);
- _moveAnimationController.addStatusListener(_moveAnimationStatusListener);
- // 初始化 Merge 动画
- _mergeAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300)); // 0.4s for scale up/down
- _mergeAnimationController.addListener(_mergeAnimationListener);
- _mergeAnimationController.addStatusListener(_mergeAnimationStatusListener);
- // 缩放值从 1.0 -> 1.1 -> 1.0 (使用 TweenSequence 实现放大再缩小)
- _mergeScaleAnimation =
- TweenSequence<double>([
- TweenSequenceItem(tween: Tween<double>(begin: 1.0, end: 1.06), weight: 50),
- TweenSequenceItem(tween: Tween<double>(begin: 1.06, end: 1.0), weight: 50),
- ]).animate(
- // 应用曲线:用 CurvedAnimation 包装控制器
- CurvedAnimation(
- parent: _mergeAnimationController, // 动画控制器
- curve: Curves.easeInOut, // 曲线类型(先加速后减速)
- ),
- );
- init();
- }
- // 关键修正:动画监听器,只注册一次
- void _moveAnimationListener() {
- if (moveItems == null || moveItems!.isEmpty) {
- return;
- }
- for (var item in moveItems!) {
- item.move();
- }
- board!.invalidate();
- }
- void _moveAnimationStatusListener(AnimationStatus status) {
- if (status == AnimationStatus.completed) {
- // 动画完成,确保所有 piece 都在它们的最终位置(endTransform)
- if (moveItems != null) {
- bool needRebuildGroup = moveItems!.any((item) => item.action == Action.swap);
- // 确保所有 piece 的 transform 最终停留在 endTransform
- for (var item in moveItems!) {
- item.stop();
- }
- if (needRebuildGroup) {
- board!.backupAllGroups();
- board!.rebuildAllGroups();
- final mergeGroups = board!.compareAllGroups();
- // 有新的区块合成,执行 merge 动画,稍稍放大然后再复原
- if (mergeGroups.isNotEmpty) {
- _log.info('Merge animation start for ${mergeGroups.length} groups.');
- // 启动 Merge 动画
- _mergeGroups = mergeGroups;
- _mergeAnimationController.forward(from: 0.0);
- // 如果执行了 merge 动画,将胜利条件检查推迟到 merge 动画完成时
- moveItems = null;
- return;
- }
- }
- // 如果没有 merge 发生,或者 move action 是 revert,检查胜利条件
- if (board!.checkWinCondition()) {
- board!.success();
- }
- moveItems = null;
- }
- }
- }
- // 新增:Merge 动画监听器
- void _mergeAnimationListener() {
- if (_mergeGroups == null || _mergeGroups!.isEmpty || board == null) {
- return;
- }
- // 当前缩放值 (从 1.0 -> 1.1 -> 1.0)
- final double scale = _mergeScaleAnimation.value;
- for (var group in _mergeGroups!) {
- final groupCenter = group.center;
- for (var piece in group.pieces) {
- // 1. 获取碎片归位后的基础位置(纯平移)
- final baseTransform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
- // 2. 计算碎片左上角到群组中心的偏移量
- final pieceTopLeft = Offset(baseTransform.storage[12], baseTransform.storage[13]);
- final offsetToCenter = groupCenter - pieceTopLeft;
- // 3. 创建围绕群组中心的缩放矩阵
- final scaleMatrix = vmath.Matrix4.identity()
- ..translate(offsetToCenter.dx, offsetToCenter.dy) // 移到群组中心
- ..scale(scale, scale, 1.0) // 缩放
- ..translate(-offsetToCenter.dx, -offsetToCenter.dy); // 移回原位
- // 4. 应用最终变换
- piece.transform = baseTransform * scaleMatrix;
- }
- }
- board!.invalidate();
- }
- // 新增:Merge 动画状态监听器
- void _mergeAnimationStatusListener(AnimationStatus status) {
- if (status == AnimationStatus.completed) {
- if (_mergeGroups != null && _mergeGroups!.isNotEmpty) {
- for (var group in _mergeGroups!) {
- for (var piece in group.pieces) {
- piece.transform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
- }
- }
- }
- _mergeGroups = null;
- // 检查胜利条件 (现在所有 pieces 都在正确位置且 scale=1.0)
- if (board!.checkWinCondition()) {
- board!.success();
- }
- board!.invalidate();
- }
- }
- init() async {
- Device device = context.read<Device>();
- setState(() {
- _isLoading = true;
- });
- final targetRect = device.targetRect;
- final bestImageSize = device.bestImageSize;
- // TODO: 替换为实际的图片加载逻辑
- final ByteData data = await rootBundle.load('assets/images/test.jpeg');
- final ui.Codec codec = await ui.instantiateImageCodec(
- data.buffer.asUint8List(),
- targetWidth: bestImageSize.width.round(),
- targetHeight: bestImageSize.height.round(),
- );
- final ui.FrameInfo frameInfo = await codec.getNextFrame();
- final image = frameInfo.image;
- board = Board(this, image, widget.cols, widget.rows, targetRect, device);
- board!.start(); // 游戏开始
- setState(() {
- _isLoading = false;
- });
- }
- @override
- void didChangeDependencies() async {
- super.didChangeDependencies();
- _log.info("didChangeDependencies");
- }
- @override
- dispose() {
- _moveAnimationController.removeListener(_moveAnimationListener);
- _moveAnimationController.removeStatusListener(_moveAnimationStatusListener);
- _moveAnimationController.dispose();
- _mergeAnimationController.removeListener(_mergeAnimationListener);
- _mergeAnimationController.removeStatusListener(_mergeAnimationStatusListener);
- _mergeAnimationController.dispose();
- board?.dispose();
- super.dispose();
- }
- @override
- Widget build(BuildContext context) {
- Device device = context.read<Device>();
- return Scaffold(
- body: Stack(
- children: <Widget>[
- if (!_isLoading) Positioned.fill(child: _buildPuzzleCanvas(device.screenSize.width, device.screenSize.height)),
- Positioned(top: 0, left: 0, right: 0, child: appBar),
- Positioned(
- bottom: 0,
- left: 0,
- right: 0,
- child: Container(
- height: device.bannerHeight,
- color: Colors.green.shade100,
- alignment: Alignment.center,
- child: const Text('Banner 广告区域', style: TextStyle(fontSize: 12)),
- ),
- ),
- if (_isLoading) const Positioned.fill(child: Center(child: CircularProgressIndicator())),
- ],
- ),
- );
- }
- final appBar = SafeArea(
- child: Center(
- child: Padding(
- padding: const EdgeInsets.all(10.0),
- child: Text(
- '关卡1',
- style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w600),
- ),
- ),
- ),
- );
- Widget _buildPuzzleCanvas(double width, double height) {
- return CustomPaint(
- painter: BoardPainter(board: board!),
- size: Size(width, height),
- child: GestureDetector(
- key: boardKey,
- onPanStart: _onPanStart,
- onPanUpdate: _onPanUpdate,
- onPanEnd: _onPanEnd,
- child: Container(color: Colors.transparent),
- ),
- );
- }
- Offset _globalToLocal(Offset globalPosition) {
- final RenderBox renderBox = boardKey.currentContext!.findRenderObject() as RenderBox;
- return renderBox.globalToLocal(globalPosition);
- }
- void _onPanStart(DragStartDetails details) {
- _log.info('_onPanStart');
- // 动画中断逻辑:如果动画正在进行,立即停止并强制所有 pieces 归位到最终位置
- if (_moveAnimationController.isAnimating && moveItems != null) {
- _log.info('移动动画中断,强制归位/交换');
- for (var item in moveItems!) {
- item.stop();
- }
- bool needRebuildGroup = moveItems!.any((item) => item.action == Action.swap);
- if (needRebuildGroup) {
- board!.backupAllGroups();
- board!.rebuildAllGroups();
- final mergeGroups = board!.compareAllGroups();
- if (mergeGroups.isNotEmpty) {
- // 此时不需要触发 merge 动画,只需确保数据结构正确
- }
- }
- moveItems = null; // 清空动画列表
- _moveAnimationController.stop();
- board!.invalidate(); // 触发一次重绘来显示最终位置
- }
- // 如果 merge 动画正在进行,也应该中断并立即归位
- if (_mergeAnimationController.isAnimating && _mergeGroups != null) {
- _log.info('合并动画中断,强制归位');
- for (var group in _mergeGroups!) {
- for (var piece in group.pieces) {
- piece.transform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
- }
- }
- _mergeGroups = null;
- _mergeAnimationController.stop();
- board!.invalidate();
- }
- // 停止所有正在运行的动画(如果尚未停止)
- _moveAnimationController.stop();
- _mergeAnimationController.stop();
- moveItems = null;
- final localPosition = _globalToLocal(details.globalPosition);
- final touchedPiece = board?.findPieceAt(localPosition);
- if (touchedPiece != null) {
- _draggingPiece = touchedPiece;
- final draggingGroup = _draggingPiece!.group;
- if (draggingGroup != null) {
- // 将拖拽群组置于 pieces 列表末尾,确保它在 CustomPainter 中被最后绘制(在最上层)
- board!.pieces.removeWhere((p) => draggingGroup.contains(p));
- board!.pieces.addAll(draggingGroup.pieces);
- } else {
- board!.pieces.remove(_draggingPiece);
- board!.pieces.add(_draggingPiece!);
- }
- board!.invalidate();
- }
- }
- void _onPanUpdate(DragUpdateDetails details) {
- _log.info('_onPanUpdate');
- if (_draggingPiece == null) return;
- final Offset delta = details.delta;
- final draggingGroup = _draggingPiece!.group;
- if (draggingGroup != null) {
- // 拖拽过程中,所有群组成员共享相同的位移
- for (var piece in draggingGroup.pieces) {
- piece.applyDelta(delta);
- }
- } else {
- _draggingPiece!.applyDelta(delta);
- }
- board!.invalidate();
- }
- void _onPanEnd(DragEndDetails details) {
- _log.info('_onPanEnd');
- if (_draggingPiece == null) {
- return;
- }
- // 保存当前拖拽结束的碎片,以备动画使用
- Piece leaderPiece = _draggingPiece!;
- _draggingPiece = null; // 结束拖拽
- board!.invalidate();
- /// 交换或归位
- // 获取碎片的中心点,判断中心点是否落到某个piece上
- Piece? targetPiece = board!.findPieceAtExclude(leaderPiece.currentCenter, leaderPiece);
- // 群组特殊处理:如果 leaderPiece 没有落在其他碎片上,检查群组其他成员
- if (targetPiece == null && leaderPiece.group != null) {
- for (var p in leaderPiece.group!.pieces) {
- targetPiece = board!.findPieceAtExclude(p.currentCenter, p);
- if (targetPiece != null) {
- _log.info('推举 ${p.toString()} 为新leader');
- leaderPiece = p; // p 落在有效的其他piece上,推举为leaderPiece
- break;
- }
- }
- }
- // 判断是否可以交换
- if (targetPiece != null && targetPiece != leaderPiece && leaderPiece.canPlaceTo(targetPiece)) {
- _log.info("swap animation start");
- _animateSwap(leaderPiece, targetPiece);
- } else {
- _log.info("revert animation start");
- _animateRevert(leaderPiece);
- }
- }
- // 关键重构:为所有涉及移动的 piece 创建独立的 MoveItem
- void _animateSwap(Piece leaderPiece, Piece targetPiece) {
- List<MoveItem> items = [];
- // 1. 确定涉及移动的所有碎片
- final List<Piece> draggingPieces = leaderPiece.group != null ? leaderPiece.group!.pieces : [leaderPiece];
- final int dr = targetPiece.curRow - leaderPiece.curRow; // 目标位置的行位移
- final int dc = targetPiece.curCol - leaderPiece.curCol; // 目标位置的列位移
- // 2. 识别被替换/推开的碎片
- List<Piece> displacedPieces = [];
- if (leaderPiece.group != null) {
- // 群组交换:找到群组新目标位置上的所有非自身群组的碎片
- for (var p in draggingPieces) {
- final int targetRow = p.curRow + dr;
- final int targetCol = p.curCol + dc;
- final Piece? other = board!.getPieceByCoordinate(targetRow, targetCol);
- if (other != null && !p.isSameGroup(other)) {
- displacedPieces.add(other);
- }
- }
- } else {
- // 单碎片交换:被替换的碎片就是 targetPiece
- displacedPieces.add(targetPiece);
- }
- // 3. 更新逻辑坐标 (curRow, curCol) - 必须在创建动画前完成
- // a. 更新拖拽群组/碎片的位置
- for (var p in draggingPieces) {
- p.curRow += dr;
- p.curCol += dc;
- }
- // b. 更新被推开的碎片的位置 (移入拖拽群组腾出的槽位)
- if (leaderPiece.group == null) {
- // 单碎片交换:targetPiece 移入 leaderPiece 的旧槽位
- targetPiece.curRow -= dr;
- targetPiece.curCol -= dc;
- } else {
- // 群组交换:被推开的碎片向后退 dr/dc 距离,找到空槽位
- for (var p in displacedPieces) {
- int newRow = p.curRow - dr;
- int newCol = p.curCol - dc;
- do {
- final Piece? pieceInSlot = board!.getPieceByCoordinate(newRow, newCol);
- if (pieceInSlot == null) {
- p.curRow = newRow;
- p.curCol = newCol;
- break;
- } else {
- newRow -= dr;
- newCol -= dc;
- }
- } while (newRow >= 0 && newRow < p.rows && newCol >= 0 && newCol < p.cols);
- }
- }
- // 4. 为所有涉及移动的碎片创建 MoveItem
- // a. 拖拽群组/碎片
- for (var p in draggingPieces) {
- // 动画起点:拖拽结束时的实际 Canvas 坐标 (p.transform)
- final startTransform = p.transform;
- // 动画终点:新的逻辑网格坐标
- final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
- final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
- items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.swap));
- }
- // b. 被推开的碎片
- for (var p in displacedPieces) {
- // 动画起点:旧的逻辑网格坐标 (p.transform)
- final startTransform = p.transform;
- // 动画终点:新的逻辑网格坐标
- final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
- final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
- items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.swap));
- }
- // 5. 启动动画
- moveItems = items;
- _moveAnimationController.forward(from: 0.0);
- }
- // 关键重构:为所有涉及归位的 piece 创建独立的 MoveItem
- void _animateRevert(Piece piece) {
- List<MoveItem> items = [];
- final List<Piece> groupPieces = piece.group != null ? piece.group!.pieces : [piece];
- for (var p in groupPieces) {
- // 动画起点:拖拽结束时的实际 Canvas 坐标 (p.transform)
- final startTransform = p.transform;
- // 动画终点:归位位置(即拖拽前所在的逻辑网格坐标)
- final endTransform = board!.getTransformByCoordinate(p.curRow, p.curCol);
- final animation = Matrix4Tween(begin: startTransform, end: endTransform).animate(_moveAnimationController);
- items.add(MoveItem(piece: p, animation: animation, startTransform: startTransform, endTransform: endTransform, action: Action.revert));
- }
- moveItems = items;
- _moveAnimationController.forward(from: 0.0);
- }
- }
- // 辅助类:用于对 vmath.Matrix4 进行线性插值 (lerp),实现平滑动画
- class Matrix4Tween extends Tween<vmath.Matrix4> {
- Matrix4Tween({required vmath.Matrix4 begin, required vmath.Matrix4 end}) : super(begin: begin, end: end);
- @override
- vmath.Matrix4 lerp(double t) {
- if (begin == null || end == null) return begin ?? end ?? vmath.Matrix4.identity();
- final List<double> lerpedStorage = List.generate(16, (i) {
- // 确保使用 ui.lerpDouble 进行插值
- return ui.lerpDouble(begin!.storage[i], end!.storage[i], t)!;
- });
- return vmath.Matrix4.fromList(lerpedStorage.cast<double>());
- }
- }
- // 动画辅助类,记录移动信息
- class MoveItem {
- // 要移动的piece
- final Piece piece;
- // 动画animation
- final Animation<vmath.Matrix4> animation;
- // 起始位置(拖拽结束时的实际 Canvas 坐标)
- final vmath.Matrix4 startTransform;
- // 结束位置(目标网格槽位的 Canvas 坐标)
- final vmath.Matrix4 endTransform;
- // 移除了 MoveType,因为现在每个 piece 都有自己的 MoveItem
- // final MoveType moveType;
- final Action action;
- MoveItem({required this.piece, required this.animation, required this.startTransform, required this.endTransform, required this.action});
- // 关键修正:直接设置 piece 的 transform 为动画插值
- void move() {
- // 关键修正:直接设置piece的transform为动画插值,而不是累加delta
- piece.transform = animation.value;
- }
- void stop() {
- // 关键修正:动画中断时,直接设置到最终目标位置 (endTransform)
- // 此时 piece 的 curRow/curCol 已经是目标网格坐标
- piece.transform = endTransform;
- }
- }
|