ByteNoteByteNote

字节笔记本

2026年2月19日

flutter_dinosaur_run:Flutter 像素风恐龙跑酷游戏

本文介绍 flutter_dinosaur_run,一个使用 Flutter 实现的像素风恐龙跑酷小游戏,模仿 Chrome 浏览器离线页面游戏。

flutter_dinosaur_run 简介

flutter_dinosaur_run 是由 CCY0122 开发的开源项目,使用 Flutter 框架实现的像素风格恐龙跑酷小游戏。该游戏模仿了 Chrome 浏览器离线页面(chrome://dino)的经典恐龙游戏,在 GitHub 上拥有 19 stars 和 7 forks。

核心定位:Pixel style dinosaur-run small game。像素风恐龙快跑小游戏。

项目信息

核心实现

该项目展示了 Flutter 游戏开发的几个关键技术点:

1. CustomPainter 自定义绘制

使用 Flutter 的 CustomPainter 实现像素风格的图形绘制:

dart
class DinosaurPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.fill;

    // 绘制像素点
    for (int x = 0; x < pixelData.length; x++) {
      for (int y = 0; y < pixelData[x].length; y++) {
        if (pixelData[x][y] == 1) {
          canvas.drawRect(
            Rect.fromLTWH(
              x * pixelSize,
              y * pixelSize,
              pixelSize,
              pixelSize,
            ),
            paint,
          );
        }
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

2. 二维数组表示像素图像

使用二维数组定义像素图像数据:

dart
// 恐龙像素数据示例(简化)
final List<List<int>> dinosaurPixels = [
  [0, 0, 0, 1, 1, 1, 0, 0],
  [0, 0, 1, 1, 1, 1, 1, 0],
  [0, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 0, 0],
  [0, 1, 1, 1, 1, 0, 0, 0],
  [0, 1, 0, 0, 1, 0, 0, 0],
  [0, 1, 0, 0, 1, 0, 0, 0],
];

3. Animation + Timer 动画控制

使用 AnimationController 和 Timer 控制游戏动画:

dart
class GameController extends ChangeNotifier {
  late AnimationController _animationController;
  Timer? _gameTimer;

  double _dinosaurY = 0;
  double _speed = 5.0;
  bool _isJumping = false;

  void init(TickerProvider vsync) {
    _animationController = AnimationController(
      vsync: vsync,
      duration: Duration(milliseconds: 100),
    )..addListener(() {
      _updateGame();
      notifyListeners();
    });
  }

  void startGame() {
    _gameTimer = Timer.periodic(Duration(milliseconds: 16), (timer) {
      _animationController.forward(from: 0);
    });
  }

  void jump() {
    if (!_isJumping) {
      _isJumping = true;
      // 跳跃逻辑
    }
  }

  void _updateGame() {
    // 更新游戏状态
    // - 移动背景
    // - 生成障碍物
    // - 检测碰撞
    // - 更新分数
  }
}

游戏机制

基础玩法

  1. 自动奔跑:恐龙自动向前奔跑
  2. 跳跃躲避:点击屏幕或按空格键跳跃,躲避障碍物
  3. 分数累计:奔跑距离越远,分数越高
  4. 速度递增:随着游戏进行,速度逐渐加快

障碍物类型

  • 仙人掌:不同高度的仙人掌障碍物
  • 飞鸟:空中飞行的鸟类障碍物

游戏状态

  • 开始界面:等待玩家开始
  • 游戏中:正常运行
  • 游戏结束:碰撞障碍物后结束

项目结构

text
flutter_dinosaur_run/
├── lib/
│   ├── main.dart              # 应用入口
│   ├── game/
│   │   ├── dinosaur.dart      # 恐龙角色
│   │   ├── obstacle.dart      # 障碍物
│   │   ├── ground.dart        # 地面
│   │   └── cloud.dart         # 云朵背景
│   ├── painter/
│   │   └── pixel_painter.dart # 像素绘制
│   └── controller/
│       └── game_controller.dart # 游戏控制
├── assets/                    # 资源文件
├── pubspec.yaml
└── README.md

运行项目

1. 克隆仓库

bash
git clone https://github.com/CCY0122/flutter_dinosaur_run.git
cd flutter_dinosaur_run

2. 安装依赖

bash
flutter pub get

3. 运行应用

bash
flutter run

关键技术点

像素风格实现

dart
class PixelPainter extends CustomPainter {
  final List<List<int>> pixels;
  final double pixelSize;

  PixelPainter(this.pixels, {this.pixelSize = 4.0});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = Colors.black;

    for (int row = 0; row < pixels.length; row++) {
      for (int col = 0; col < pixels[row].length; col++) {
        if (pixels[row][col] == 1) {
          canvas.drawRect(
            Rect.fromLTWH(
              col * pixelSize,
              row * pixelSize,
              pixelSize,
              pixelSize,
            ),
            paint,
          );
        }
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

碰撞检测

dart
bool checkCollision(Dinosaur dinosaur, Obstacle obstacle) {
  final dinosaurRect = Rect.fromLTWH(
    dinosaur.x,
    dinosaur.y,
    dinosaur.width,
    dinosaur.height,
  );

  final obstacleRect = Rect.fromLTWH(
    obstacle.x,
    obstacle.y,
    obstacle.width,
    obstacle.height,
  );

  return dinosaurRect.overlaps(obstacleRect);
}

跳跃物理

dart
class JumpPhysics {
  double velocity = 0;
  double gravity = 0.6;
  double jumpForce = -12;

  void jump() {
    velocity = jumpForce;
  }

  void update() {
    velocity += gravity;
    position += velocity;

    // 地面检测
    if (position >= groundLevel) {
      position = groundLevel;
      velocity = 0;
      isJumping = false;
    }
  }
}

学习价值

Flutter 游戏开发入门

  • CustomPainter:学习自定义绘制
  • 动画控制:AnimationController 使用
  • 状态管理:游戏状态管理
  • 手势处理:点击/键盘事件处理

游戏开发基础

  • 游戏循环:update-render 循环
  • 碰撞检测:矩形碰撞检测
  • 物理模拟:简单的重力跳跃
  • 像素艺术:程序化像素绘制

扩展建议

添加音效

dart
import 'package:audioplayers/audioplayers.dart';

final player = AudioPlayer();

void playJumpSound() {
  player.play(AssetSource('jump.wav'));
}

添加难度等级

dart
void increaseDifficulty() {
  if (score > 100) speed = 6;
  if (score > 500) speed = 8;
  if (score > 1000) speed = 10;
}

本地存储最高分

dart
import 'package:shared_preferences/shared_preferences.dart';

Future<void> saveHighScore(int score) async {
  final prefs = await SharedPreferences.getInstance();
  final highScore = prefs.getInt('highScore') ?? 0;
  if (score > highScore) {
    await prefs.setInt('highScore', score);
  }
}

类似项目

  • Chrome Dino:原版 Chrome 离线游戏
  • Flutter 2048:数字益智游戏
  • Flappy Bird Clone:Flutter 实现的 Flappy Bird

总结

flutter_dinosaur_run 是一个简洁有趣的 Flutter 小游戏项目,展示了:

  • CustomPainter 绘制:像素风格图形渲染
  • 动画控制:流畅的游戏动画
  • 游戏逻辑:完整的跑酷游戏机制
  • 代码简洁:适合学习 Flutter 游戏开发

对于想学习 Flutter 游戏开发、CustomPainter 使用的开发者来说,这是一个很好的入门项目。

分享: