| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129 |
- import 'dart:async';
- import 'dart:io';
- import 'dart:math';
- import 'dart:typed_data';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
- import 'package:fluttertoast/fluttertoast.dart';
- import 'package:image_puzzle/audio/audio_controller.dart';
- import 'package:image_puzzle/config/device.dart';
- import 'package:image_puzzle/models/data.dart';
- import 'package:image_puzzle/models/download.dart';
- import 'package:image_puzzle/models/items.dart';
- import 'package:image_puzzle/play/board.dart';
- import 'package:image_puzzle/play/board_painter.dart';
- import 'package:image_puzzle/play/confetti_layer.dart';
- import 'package:image_puzzle/play/piece.dart';
- import 'package:image_puzzle/settings/settings_dialog.dart';
- import 'package:image_puzzle/skin/skin.dart';
- import 'package:image_puzzle/utils/mybutton.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;
- import 'package:vibration/vibration.dart';
- final Logger _log = Logger('board_play.dart');
- // 移动类型 (不再需要,但保留枚举以防止其他文件引用报错)
- enum MoveType {
- group, // 整个群组一起移动
- single, // 单个碎片移动
- }
- // 操作类型
- enum Action {
- revert, // 回归
- swap, // 交换
- }
- class BoardPlay extends StatefulWidget {
- final ListItem item;
- const BoardPlay({super.key, required this.item});
- @override
- State<StatefulWidget> createState() {
- return _BoardPlayState();
- }
- static PageRouteBuilder buildRoute(ListItem item, {difficult = 1, count = 6}) {
- return PageRouteBuilder(
- pageBuilder: (context, animation, secondaryAnimation) {
- return BoardPlay(item: item);
- },
- transitionsBuilder: (context, animation, secondaryAnimation, child) {
- return FadeTransition(opacity: animation, child: child);
- // return SlideTransition(
- // position: Tween(begin: const Offset(1, 0), end: Offset.zero).animate(animation),
- // child: child,
- // );
- },
- );
- }
- }
- class _BoardPlayState extends State<BoardPlay> with TickerProviderStateMixin {
- final GlobalKey boardKey = GlobalKey();
- Board? board;
- bool _isLoading = true;
- int progress = 0;
- bool isDownloadSlow = false;
- late Timer timer;
- late ItemLoader itemLoader;
- late AudioController audio;
- late Data data;
- late ConfettiLayer confettiLayer;
- Piece? _draggingPiece;
- // 记录所有动画中的移动项 (位移/交换/归位)
- List<MoveItem>? moveItems;
- // 动画控制器
- late AnimationController _moveAnimationController; // 移动动画(位移)
- late AnimationController _mergeAnimationController; // merge动画(scale)
- // merge 动画的缩放值
- late Animation<double> _mergeScaleAnimation;
- List<PieceGroup>? _mergeGroups; // 记录当前merge的group
- late AnimationController _prepareAnimationController; // 预备动画, Opacity透明动画展示核心绘制区
- late AnimationController dealingAnimationController; // 发牌动画
- late AnimationController flipAnimationController; // 翻牌动画
- // 发牌动画相关
- late Animation<double> _dealingAnimation;
- // 发牌动画参数
- // 发牌间隔(ms)
- int get _dealingPieceInterval {
- if (board!.rows <= 3) return 120;
- if (board!.rows == 4) return 100;
- if (board!.rows == 5) return 80;
- if (board!.rows == 6) return 60;
- return 50;
- }
- // 每个卡片移动时间(ms)
- int get _dealingPieceDuration {
- if (board!.rows <= 3) return 500;
- if (board!.rows == 4) return 400;
- if (board!.rows == 5) return 300;
- if (board!.rows == 6) return 200;
- return 100;
- }
- // 发牌动画总时长
- int get _totalDealingDuration => (board!.pieces.length - 1) * _dealingPieceInterval + _dealingPieceDuration; // 发牌动画总时长(ms)
- Timer? _dealingPeriodicTimer;
- int _dealingCount = 0; // 计数:记录执行次数
- // 成功动画控制器
- late AnimationController _successAnimationController;
- late Animation<double> _offsetAnimation; // 用于控制核心绘制区上移
- late Animation<double> _bottomSlideAnimation; // 用于控制next按钮从屏幕下方移动上来
- late Animation<double> _topSlideAnimation; // 用于控制通关banner从屏幕上方移动上来
- // Hard Mode Banner 动画控制器
- late AnimationController _hardModeBannerController;
- // 缩放动画
- late Animation<double> _bannerScaleAnimation;
- // 透明度动画
- late Animation<double> _bannerFadeAnimation;
- // 是否显示 Hard Mode Banner 的标志
- bool _showHardModeBanner = false;
- @override
- initState() {
- super.initState();
- itemLoader = ItemLoader.load(widget.item);
- _onProgressUpdate();
- itemLoader.progress.addListener(_onProgressUpdate);
- timer = Timer(const Duration(seconds: 5), () {
- if (mounted && progress < 50) {
- if (progress <= 1) {
- //啥都没下载到, 直接弹toast然后退出
- Fluttertoast.showToast(
- msg: "网络状况不佳",
- toastLength: Toast.LENGTH_SHORT,
- gravity: ToastGravity.CENTER,
- timeInSecForIosWeb: 1,
- backgroundColor: SkinHelper.slotBorderColor,
- textColor: Colors.white,
- fontSize: 16.0,
- );
- Navigator.pop(context);
- } else {
- // 有下载只是慢
- setState(() {
- isDownloadSlow = true;
- });
- }
- }
- });
- Device device = context.read<Device>();
- audio = context.read<AudioController>();
- data = context.read<Data>();
- confettiLayer = ConfettiLayer(this);
- Future.delayed(Duration.zero, () {
- if (mounted) {
- confettiLayer.setup(context);
- }
- });
- // 初始化移动动画,在dragging结束松手后的swap或evert操作都需要用到移动
- _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, // 曲线类型(先加速后减速)
- ),
- );
- _prepareAnimationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 800));
- _prepareAnimationController.addListener(_prepareAnimationListener);
- _prepareAnimationController.addStatusListener(_prepareAnimationStatusListener);
- // 初始化发牌动画
- dealingAnimationController = AnimationController(vsync: this);
- _dealingAnimation = CurvedAnimation(parent: dealingAnimationController, curve: Curves.linear);
- dealingAnimationController.addListener(_dealingAnimationListener);
- dealingAnimationController.addStatusListener(_dealingAnimationStatusListener);
- // 初始化翻转动画
- flipAnimationController = AnimationController(vsync: this, duration: Duration(milliseconds: 500));
- flipAnimationController.addListener(_flipAnimationListener);
- flipAnimationController.addStatusListener(_flipAnimationStatusListener);
- // 初始化成功动画
- _successAnimationController = AnimationController(vsync: this, duration: Duration(milliseconds: 500));
- final deltaY = (device.targetRect.top - device.appBarHeight) / 2;
- _offsetAnimation = Tween<double>(begin: 0.0, end: -deltaY).animate(_successAnimationController);
- _bottomSlideAnimation =
- Tween<double>(
- begin: -500, // 初始在屏幕外
- end: device.screenSize.height - device.targetRect.bottom + deltaY - 60,
- ).animate(
- CurvedAnimation(
- parent: _successAnimationController,
- curve: Curves.easeOut, // 缓出曲线,滑入更自然
- ),
- );
- _topSlideAnimation =
- Tween<double>(
- begin: -200, // 初始在屏幕外
- end: device.targetRect.top - deltaY - 70,
- ).animate(
- CurvedAnimation(
- parent: _successAnimationController,
- curve: Curves.easeOut, // 缓出曲线,滑入更自然
- ),
- );
- _successAnimationController.addListener(_successAnimationListener);
- _successAnimationController.addStatusListener(_successAnimationStatusListener);
- // 初始化 Hard Mode Banner 动画
- _hardModeBannerController = AnimationController(vsync: this, duration: const Duration(milliseconds: 1500));
- // 缩放:0.0 -> 1.0 (前 40% 时间快速放大)
- _bannerScaleAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
- CurvedAnimation(
- parent: _hardModeBannerController,
- curve: const Interval(0.0, 0.4, curve: Curves.easeOut),
- ),
- );
- // 透明度:1.0 -> 0.0 (后 70% 时间逐渐淡出)
- _bannerFadeAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(
- CurvedAnimation(
- parent: _hardModeBannerController,
- curve: const Interval(0.3, 1.0, curve: Curves.easeIn),
- ),
- );
- // 监听器用于触发重绘
- _hardModeBannerController.addListener(() {
- // if (mounted) setState(() {}); // 效率较低,改用AnimatedBuilder来实现局部重绘
- });
- // 动画完成时,设置标志为 false,完全隐藏
- _hardModeBannerController.addStatusListener((status) {
- if (status == AnimationStatus.completed) {
- if (mounted) setState(() => _showHardModeBanner = false);
- }
- });
- _init();
- }
- _onProgressUpdate() {
- // progress = (downloadItem.progress.value * 100).ceil();
- progress = (itemLoader.progress.value * 100).ceil();
- _log.info('onProgressUpdate: progress=$progress');
- setState(() {});
- }
- void _successAnimationListener() {
- final delta = _offsetAnimation.value;
- board!.finalRect = board!.targetRect.translate(0, delta);
- board!.invalidate();
- }
- void _successAnimationStatusListener(AnimationStatus status) {
- if (status == AnimationStatus.completed) {}
- }
- void _dealingAnimationListener() {
- if (board == null) return;
- // 当前动画已运行的时间(ms)
- final currentTime = _dealingAnimation.value * _totalDealingDuration;
- // 逐个更新卡片位置(最后一张不需要动)
- for (int i = 0; i < board!.pieces.length - 1; i++) {
- final piece = board!.pieces[i];
- final startTime = i * _dealingPieceInterval;
- final duration = _dealingPieceDuration;
- // 尚未到启动时间:保持在起点
- if (currentTime < startTime) {
- continue;
- }
- // 计算移动进度(0~1):已移动时间 / 总持续时间
- double progress = (currentTime - startTime) / duration;
- progress = progress.clamp(0.0, 1.0); // 限制进度不超过1(防止超调)
- // 计算当前位置(起点到终点的插值)
- final startTransform = board!.getBottomRightTransform();
- final endTransform = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
- final tween = Matrix4Tween(begin: startTransform, end: endTransform);
- piece.transform = tween.lerp(progress);
- }
- board!.invalidate();
- }
- // 发牌动画状态监听器
- void _dealingAnimationStatusListener(AnimationStatus status) {
- if (status == AnimationStatus.completed) {
- board!.resetAllPieces();
- board!.shuffle(ShuffleStep.flipping);
- flipAnimationController.forward(from: 0.0);
- audio.playSfx(SfxType.flip);
- }
- }
- // 翻转动画监听器
- void _flipAnimationListener() {
- if (board == null) return;
- final flipValue = flipAnimationController.value;
- for (final piece in board!.pieces) {
- // 1. 计算翻转角度(0→π,180度翻转)
- final angle = flipValue * pi;
- // 2. 获取卡片的固定目标位置(基于curRow/curCol,不依赖动态transform)
- final targetTranslate = board!.getTransformByCoordinate(piece.curRow, piece.curCol);
- // 3. 执行翻转动画(传入固定目标位置)
- piece.updateFlipTransform(angle, targetTranslate);
- }
- board!.invalidate();
- }
- // 翻转动画状态监听器
- void _flipAnimationStatusListener(AnimationStatus status) {
- if (status == AnimationStatus.completed) {
- // 翻转完成,开始游戏
- board!.resetAllPieces();
- board!.rebuildAllGroups();
- // 检查是否初始化就已经merge的group
- 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);
- audio.playSfx(SfxType.pop);
- }
- board!.start();
- }
- }
- // 关键修正:动画监听器,只注册一次
- 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);
- audio.playSfx(SfxType.pop);
- // 如果执行了 merge 动画,将胜利条件检查推迟到 merge 动画完成时
- moveItems = null;
- return;
- }
- }
- 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;
- // 检查胜利条件
- if (board!.checkWinCondition()) {
- _onSuccess();
- }
- board!.invalidate();
- }
- }
- void _prepareAnimationListener() {
- board!.invalidate();
- }
- // prepare动画结束,进入洗牌动画
- void _prepareAnimationStatusListener(AnimationStatus status) {
- if (status == AnimationStatus.completed) {
- if (board != null && board!.hard == true) {
- setState(() => _showHardModeBanner = true);
- _hardModeBannerController.forward(from: 0.0);
- }
- board!.setAllPieceToBottomRight();
- board!.shuffle(ShuffleStep.dealing);
- dealingAnimationController.duration = Duration(milliseconds: _totalDealingDuration);
- dealingAnimationController.forward(from: 0.0);
- audio.playSfx(SfxType.card);
- _dealingPeriodicTimer = Timer.periodic(Duration(milliseconds: 120), (timer) {
- if (mounted) {
- _dealingCount++;
- if (_dealingCount >= (_totalDealingDuration / 120) - 2) {
- timer.cancel();
- } else {
- audio.playSfx(SfxType.card);
- }
- }
- });
- }
- }
- _onSuccess() {
- _log.info('success! 游戏完成!');
- data.workDone(widget.item);
- board!.success();
- audio.playSfx(SfxType.success);
- confettiLayer.play();
- _successAnimationController.forward(from: 0.0);
- setState(() {});
- }
- _init() async {
- Device device = context.read<Device>();
- setState(() {
- _isLoading = true;
- });
- final dpr = device.devicePixelRatio;
- final targetRect = device.targetRect;
- final bestImageSize = device.bestImageSize;
- final image = await itemLoader.getImageBySize(bestImageSize.width.round(), bestImageSize.height.round());
- _log.info('imageSize: (${image.width},${image.height}), bestImageSize: ($bestImageSize)');
- // 加载图片,后续改为从远程服务器加载, 目前demo从本地assets读取
- // final ByteData data = await rootBundle.load('assets/images/test.jpeg');
- // final ByteData data = await rootBundle.load(widget.item.image);
- // 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;
- // 加载扑克背面图片,用于制作发牌动画
- final Size bestCardImageSize = Size(targetRect.width * dpr / widget.item.rows, targetRect.height * dpr / widget.item.cols);
- final ByteData cardData = await rootBundle.load(widget.item.hard ? 'assets/images/backcard_red.png' : 'assets/images/backcard_blue.png');
- final ui.Codec cardCodec = await ui.instantiateImageCodec(
- cardData.buffer.asUint8List(),
- targetWidth: bestCardImageSize.width.round(),
- targetHeight: bestCardImageSize.height.round(),
- );
- final ui.FrameInfo cardFrameInfo = await cardCodec.getNextFrame();
- final cardImage = cardFrameInfo.image;
- board = Board(this, image, cardImage, widget.item.rows, widget.item.cols, widget.item.hard, targetRect, device);
- board!.prepare();
- // **修正:在调用 AnimationController 之前检查 `mounted` 状态**
- if (!mounted) return;
- _prepareAnimationController.forward(from: 0.0);
- setState(() {
- _isLoading = false;
- });
- }
- @override
- void didChangeDependencies() async {
- super.didChangeDependencies();
- _log.info("didChangeDependencies");
- }
- @override
- dispose() {
- timer.cancel();
- itemLoader.progress.removeListener(_onProgressUpdate);
- _moveAnimationController.removeListener(_moveAnimationListener);
- _moveAnimationController.removeStatusListener(_moveAnimationStatusListener);
- _moveAnimationController.dispose();
- _mergeAnimationController.removeListener(_mergeAnimationListener);
- _mergeAnimationController.removeStatusListener(_mergeAnimationStatusListener);
- _mergeAnimationController.dispose();
- _prepareAnimationController.removeListener(_prepareAnimationListener);
- _prepareAnimationController.removeStatusListener(_prepareAnimationStatusListener);
- _prepareAnimationController.dispose();
- dealingAnimationController.removeListener(_dealingAnimationListener);
- dealingAnimationController.removeStatusListener(_dealingAnimationStatusListener);
- dealingAnimationController.dispose();
- flipAnimationController.removeListener(_flipAnimationListener);
- flipAnimationController.removeStatusListener(_flipAnimationStatusListener);
- flipAnimationController.dispose();
- _successAnimationController.removeListener(_successAnimationListener);
- _successAnimationController.removeStatusListener(_successAnimationStatusListener);
- _hardModeBannerController.dispose();
- _dealingPeriodicTimer?.cancel();
- confettiLayer.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)),
- if (board == null || board!.status != BoardStatus.success) Positioned(top: 0, left: 0, right: 0, child: appBar),
- // 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)),
- ),
- ),
- successBanner,
- nextButton,
- if (_isLoading)
- Positioned.fill(
- child: Container(
- color: SkinHelper.wholeBgColor,
- child: const Center(child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(Colors.white))),
- ),
- ),
- ],
- ),
- );
- }
- Widget get appBar => SafeArea(
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 30.0, vertical: 10.0),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- // 左侧占位(保持标题居中)
- const SizedBox(width: 30),
- // 中间标题
- Text(
- board != null && board!.status == BoardStatus.success ? '关卡通过!' : '关卡${data.currentLevel}',
- style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w600),
- ),
- // 右侧设置按钮(30x30 圆形、深绿色背景、白色图标)
- SizedBox(
- width: 30,
- height: 30,
- child: IconButton(
- icon: const Icon(Icons.settings, color: Colors.white, size: 22),
- iconSize: 22,
- padding: EdgeInsets.zero, // 清除默认内边距,确保按钮尺寸准确
- onPressed: () {
- Navigator.push(context, SettingsDialog.buildRoute(showReturn: true, showRestart: true, item: widget.item));
- },
- style: ButtonStyle(
- // 深绿色背景(与你之前的按钮风格一致,使用 Color(0xff26600c) 深绿色)
- backgroundColor: WidgetStateProperty.all(SkinHelper.slotBorderColor),
- // 圆形形状
- shape: WidgetStateProperty.all(
- RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(15), // 30x30 按钮对应 15 圆角
- ),
- ),
- // 固定按钮尺寸(30x30)
- minimumSize: WidgetStateProperty.all(const Size(30, 30)),
- maximumSize: WidgetStateProperty.all(const Size(30, 30)),
- ),
- ),
- ),
- ],
- ),
- ),
- );
- Widget _buildPuzzleCanvas(double width, double height) {
- return RepaintBoundary(
- child: CustomPaint(
- painter: BoardPainter(board: board!, prepareAnimation: _prepareAnimationController),
- size: Size(width, height),
- child: GestureDetector(
- key: boardKey,
- onPanStart: _onPanStart,
- onPanUpdate: _onPanUpdate,
- onPanEnd: _onPanEnd,
- child: // 根据游戏状态动态显示提示动画或透明容器
- board != null && board!.hard && _showHardModeBanner
- ? _hardModeBanner
- : Container(color: Colors.transparent), // 非显示条件时,使用透明容器
- ),
- ),
- );
- }
- // 困难模式提示动画组件
- Widget get _hardModeBanner => Center(
- // 使用 AnimatedBuilder 包裹需要动画的组件
- child: AnimatedBuilder(
- animation: _hardModeBannerController, // 监听控制器
- builder: (context, child) {
- return FadeTransition(
- opacity: _bannerFadeAnimation, // 使用控制器驱动的动画值
- child: ScaleTransition(
- scale: _bannerScaleAnimation, // 使用控制器驱动的动画值
- child: child, // 不随动画重建的子组件
- ),
- );
- },
- // child 是不依赖动画状态变化的组件,只会构建一次
- child: Container(
- width: double.infinity,
- height: 60,
- margin: const EdgeInsets.symmetric(horizontal: 10),
- decoration: BoxDecoration(
- color: Colors.red,
- borderRadius: BorderRadius.circular(10),
- border: Border.all(color: const Color.fromARGB(255, 247, 143, 135), width: 2),
- boxShadow: [BoxShadow(color: Color.fromRGBO(0, 0, 0, 0.3), blurRadius: 5, offset: const Offset(0, 3))],
- ),
- child: const Center(
- child: Text(
- '困难模式',
- style: TextStyle(color: Colors.white, fontSize: 30, fontWeight: FontWeight.bold),
- ),
- ),
- ),
- ),
- );
- Widget get nextButton {
- Device device = context.read<Device>();
- return AnimatedBuilder(
- // 监听显式动画 _bottomSlideAnimation
- animation: _bottomSlideAnimation,
- builder: (context, child) {
- return AnimatedPositioned(
- duration: _successAnimationController.duration!,
- // 从动画中获取实时 value,赋值给 bottom
- bottom: _bottomSlideAnimation.value,
- left: (device.screenSize.width - 200) / 2,
- child: child!, // 固定子组件,优化性能
- );
- },
- // 固定的按钮组件(仅构建一次,优化性能)
- child: MyElevatedButton(
- width: 200,
- borderRadius: BorderRadius.circular(20),
- gradient: LinearGradient(colors: [SkinHelper.coreBgColor, SkinHelper.slotBorderColor]),
- onPressed: () {
- audio.playSfx(SfxType.tap);
- Navigator.pop(context, true);
- },
- child: const Text('Next', style: TextStyle(color: Colors.white, fontSize: 20)),
- ),
- );
- }
- Widget get successBanner {
- Device device = context.read<Device>();
- // 计算banner宽高
- final bannerWidth = device.screenSize.width - 60; // 左右各30间距
- final bannerHeight = 60.0;
- return AnimatedBuilder(
- animation: _bottomSlideAnimation,
- builder: (context, child) {
- return AnimatedPositioned(
- duration: _successAnimationController.duration!,
- top: _topSlideAnimation.value, // 固定底部位置
- left: 30, // 左间距30,与bannerWidth配合实现水平居中
- child: child!,
- );
- },
- // 核心:用Container固定尺寸,Stack填充Container,确保图片和文字尺寸对齐
- child: SizedBox(
- width: bannerWidth, // 容器宽=图片宽
- height: bannerHeight, // 容器高=图片高
- child: Stack(
- children: [
- // 1. 图片充满容器(与容器尺寸一致)
- Image.asset(
- 'assets/images/banner3.png',
- width: double.infinity, // 图片宽=容器宽
- height: double.infinity, // 图片高=容器高
- fit: BoxFit.cover, // 图片填充容器(不拉伸,超出部分裁剪)
- cacheWidth: (context.watch<Device>().devicePixelRatio * bannerWidth).toInt(),
- cacheHeight: (context.watch<Device>().devicePixelRatio * bannerHeight).toInt(),
- ),
- const Center(
- child: Padding(
- padding: EdgeInsets.only(top: 16.0),
- child: Text(
- '关卡通过!',
- style: TextStyle(
- color: Colors.white,
- fontSize: 22,
- fontWeight: FontWeight.bold,
- shadows: [Shadow(color: Colors.black54, offset: Offset(1, 1), blurRadius: 2)],
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- );
- }
- Offset _globalToLocal(Offset globalPosition) {
- final RenderBox renderBox = boardKey.currentContext!.findRenderObject() as RenderBox;
- return renderBox.globalToLocal(globalPosition);
- }
- void _onPanStart(DragStartDetails details) {
- _log.info('_onPanStart');
- if (board!.status != BoardStatus.playing) {
- _log.info('不是playing状态,不响应onPanStart');
- return;
- }
- // 动画中断逻辑:如果动画正在进行,立即停止并强制所有 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();
- }
- // audio.playSfx(SfxType.tap);
- // 停止所有正在运行的动画(如果尚未停止)
- _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();
- }
- if (Platform.isAndroid) {
- Vibration.vibrate(duration: 60, amplitude: 50);
- } else {
- HapticFeedback.mediumImpact();
- }
- }
- void _onPanUpdate(DragUpdateDetails details) {
- 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 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));
- board!.pieces.remove(p);
- board!.pieces.add(p);
- }
- // b. 拖拽群组/碎片
- 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));
- board!.pieces.remove(p);
- board!.pieces.add(p);
- }
- // 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;
- }
- }
|