跳到主内容

使用 Firestore 添加多人游戏支持

如何使用 Firebase Cloud Firestore 在游戏中实现多人游戏。

多人游戏需要一种在玩家之间同步游戏状态的方式。广义上讲,存在两种类型的多人游戏

  1. 高滴答率。这些游戏需要在每秒多次同步游戏状态,且延迟较低。这些包括动作游戏、体育游戏、格斗游戏。

  2. 低滴答率。这些游戏只需要偶尔同步游戏状态,且延迟影响较小。这些包括纸牌游戏、策略游戏、益智游戏。

这类似于实时游戏与回合制游戏之间的区别,但这种类比并不完全准确。例如,实时策略游戏——顾名思义——是实时运行的,但这与高滴答率并不相关。这些游戏可以在玩家交互之间在本地机器上模拟很多内容。因此,它们不需要那么频繁地同步游戏状态。

An illustration of two mobile phones and a two-way arrow between them

如果您可以作为开发者选择低滴答率,您应该这样做。低滴答率降低了延迟要求和服务器成本。对于需要高滴答率同步的情况,Firestore 不适合。选择专用的多人游戏服务器解决方案,例如 Nakama。Nakama 有一个 Dart 包

如果您预计您的游戏需要低滴答率的同步,请继续阅读。

本教程演示了如何使用 cloud_firestore 在游戏中实现多人游戏功能。本教程不需要服务器。它使用两个或多个客户端使用 Cloud Firestore 共享游戏状态。

1. 准备游戏以支持多人游戏

#

编写游戏代码,以响应本地事件和远程事件来更改游戏状态。本地事件可以是玩家操作或某些游戏逻辑。远程事件可以是来自服务器的世界更新。

Screenshot of the card game

为了简化本教程,请从 card 模板开始,该模板位于 flutter/games 仓库 中。运行以下命令来克隆该仓库

git clone https://github.com/flutter/games.git

templates/card 中打开项目。

2. 安装 Firestore

#

Cloud Firestore 是云中的水平扩展的 NoSQL 文档数据库。它包括内置的实时同步。这非常适合我们的需求。它使游戏状态在云数据库中保持更新,因此每个玩家都看到相同状态。

如果您想快速了解 Cloud Firestore,请观看以下视频

在新的标签页上在 YouTube 上观看:“什么是 NoSQL 数据库?了解 Cloud Firestore”

要将 Firestore 添加到您的 Flutter 项目,请遵循 开始使用 Cloud Firestore 指南的前两个步骤

期望的结果包括

  • 在云中准备好的 Firestore 数据库,处于 测试模式
  • 生成的 firebase_options.dart 文件
  • 将适当的插件添加到您的 pubspec.yaml

不需要在此步骤中编写任何 Dart 代码。一旦您理解了该指南中编写 Dart 代码的步骤,请返回本教程。

3. 初始化 Firestore

#
  1. 打开 lib/main.dart 并导入插件以及在上一步中由 flutterfire configure 生成的 firebase_options.dart 文件。

    dart
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:firebase_core/firebase_core.dart';
    
    import 'firebase_options.dart';
    
  2. lib/main.dart 中,在 runApp() 调用之上添加以下代码

    dart
    WidgetsFlutterBinding.ensureInitialized();
    
    await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
    

    这确保了在游戏启动时初始化 Firebase。

  3. 将 Firestore 实例添加到应用程序。这样,任何小部件都可以访问此实例。小部件还可以对实例缺失做出反应(如果需要)。

    要使用 card 模板执行此操作,可以使用 provider 包(已安装为依赖项)。

    将占位符 runApp(MyApp()) 替换为以下内容

    dart
    runApp(Provider.value(value: FirebaseFirestore.instance, child: MyApp()));
    

    将 provider 放在 MyApp 之上,而不是在其内部。这使您可以在没有 Firebase 的情况下测试应用程序。

    :::note 如果您使用 card 模板,则必须 安装 provider 或使用您自己的方法从代码库的不同部分访问 FirebaseFirestore 实例。 ::

4. 创建 Firestore 控制器类

#

虽然可以直接与 Firestore 通信,但您应该编写一个专门的控制器类,以使代码更具可读性和可维护性。

如何实现控制器取决于您的游戏以及多人游戏体验的确切设计。对于 card 模板,您可以同步两个圆形游戏区域的内容。这不足以提供完整的多人游戏体验,但这是一个好的开始。

Screenshot of the card game, with arrows pointing to playing areas

要创建控制器,请复制,然后将以下代码粘贴到名为 lib/multiplayer/firestore_controller.dart 的新文件中。

dart
import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';

import '../game_internals/board_state.dart';
import '../game_internals/playing_area.dart';
import '../game_internals/playing_card.dart';

class FirestoreController {
  static final _log = Logger('FirestoreController');

  final FirebaseFirestore instance;

  final BoardState boardState;

  /// For now, there is only one match. But in order to be ready
  /// for match-making, put it in a Firestore collection called matches.
  late final _matchRef = instance.collection('matches').doc('match_1');

  late final _areaOneRef = _matchRef
      .collection('areas')
      .doc('area_one')
      .withConverter<List<PlayingCard>>(
        fromFirestore: _cardsFromFirestore,
        toFirestore: _cardsToFirestore,
      );

  late final _areaTwoRef = _matchRef
      .collection('areas')
      .doc('area_two')
      .withConverter<List<PlayingCard>>(
        fromFirestore: _cardsFromFirestore,
        toFirestore: _cardsToFirestore,
      );

  late final StreamSubscription<void> _areaOneFirestoreSubscription;
  late final StreamSubscription<void> _areaTwoFirestoreSubscription;

  late final StreamSubscription<void> _areaOneLocalSubscription;
  late final StreamSubscription<void> _areaTwoLocalSubscription;

  FirestoreController({required this.instance, required this.boardState}) {
    // Subscribe to the remote changes (from Firestore).
    _areaOneFirestoreSubscription = _areaOneRef.snapshots().listen((snapshot) {
      _updateLocalFromFirestore(boardState.areaOne, snapshot);
    });
    _areaTwoFirestoreSubscription = _areaTwoRef.snapshots().listen((snapshot) {
      _updateLocalFromFirestore(boardState.areaTwo, snapshot);
    });

    // Subscribe to the local changes in game state.
    _areaOneLocalSubscription = boardState.areaOne.playerChanges.listen((_) {
      _updateFirestoreFromLocalAreaOne();
    });
    _areaTwoLocalSubscription = boardState.areaTwo.playerChanges.listen((_) {
      _updateFirestoreFromLocalAreaTwo();
    });

    _log.fine('Initialized');
  }

  void dispose() {
    _areaOneFirestoreSubscription.cancel();
    _areaTwoFirestoreSubscription.cancel();
    _areaOneLocalSubscription.cancel();
    _areaTwoLocalSubscription.cancel();

    _log.fine('Disposed');
  }

  /// Takes the raw JSON snapshot coming from Firestore and attempts to
  /// convert it into a list of [PlayingCard]s.
  List<PlayingCard> _cardsFromFirestore(
    DocumentSnapshot<Map<String, Object?>> snapshot,
    SnapshotOptions? options,
  ) {
    final data = snapshot.data()?['cards'] as List<Object?>?;

    if (data == null) {
      _log.info('No data found on Firestore, returning empty list');
      return [];
    }

    try {
      return data
          .cast<Map<String, Object?>>()
          .map(PlayingCard.fromJson)
          .toList();
    } catch (e) {
      throw FirebaseControllerException(
        'Failed to parse data from Firestore: $e',
      );
    }
  }

  /// Takes a list of [PlayingCard]s and converts it into a JSON object
  /// that can be saved into Firestore.
  Map<String, Object?> _cardsToFirestore(
    List<PlayingCard> cards,
    SetOptions? options,
  ) {
    return {'cards': cards.map((c) => c.toJson()).toList()};
  }

  /// Updates Firestore with the local state of [area].
  Future<void> _updateFirestoreFromLocal(
    PlayingArea area,
    DocumentReference<List<PlayingCard>> ref,
  ) async {
    try {
      _log.fine('Updating Firestore with local data (${area.cards}) ...');
      await ref.set(area.cards);
      _log.fine('... done updating.');
    } catch (e) {
      throw FirebaseControllerException(
        'Failed to update Firestore with local data (${area.cards}): $e',
      );
    }
  }

  /// Sends the local state of `boardState.areaOne` to Firestore.
  void _updateFirestoreFromLocalAreaOne() {
    _updateFirestoreFromLocal(boardState.areaOne, _areaOneRef);
  }

  /// Sends the local state of `boardState.areaTwo` to Firestore.
  void _updateFirestoreFromLocalAreaTwo() {
    _updateFirestoreFromLocal(boardState.areaTwo, _areaTwoRef);
  }

  /// Updates the local state of [area] with the data from Firestore.
  void _updateLocalFromFirestore(
    PlayingArea area,
    DocumentSnapshot<List<PlayingCard>> snapshot,
  ) {
    _log.fine('Received new data from Firestore (${snapshot.data()})');

    final cards = snapshot.data() ?? [];

    if (listEquals(cards, area.cards)) {
      _log.fine('No change');
    } else {
      _log.fine('Updating local data with Firestore data ($cards)');
      area.replaceWith(cards);
    }
  }
}

class FirebaseControllerException implements Exception {
  final String message;

  FirebaseControllerException(this.message);

  @override
  String toString() => 'FirebaseControllerException: $message';
}

请注意此代码的以下特性

  • 控制器的构造函数接受一个 BoardState。这使控制器能够操作游戏本地状态。

  • 控制器订阅本地更改以更新 Firestore,并订阅远程更改以更新本地状态和 UI。

  • 字段 _areaOneRef_areaTwoRef 是 Firebase 文档引用。它们描述了每个区域的数据驻留位置,以及如何在本地 Dart 对象(List<PlayingCard>)和远程 JSON 对象(Map<String, dynamic>)之间进行转换。Firestore API 允许我们使用 .snapshots() 订阅这些引用,并使用 .set() 写入它们。

5. 使用 Firestore 控制器

#
  1. 打开负责启动游戏会话的文件:对于 card 模板,在 lib/play_session/play_session_screen.dart 中。您将从该文件实例化 Firestore 控制器。

  2. 导入 Firebase 和控制器

    dart
    import 'package:cloud_firestore/cloud_firestore.dart';
    import '../multiplayer/firestore_controller.dart';
    
  3. 将一个可为空的字段添加到 _PlaySessionScreenState 类,以包含控制器实例

    dart
    FirestoreController? _firestoreController;
    
  4. 在同一类的 initState() 方法中,添加代码以尝试读取 FirebaseFirestore 实例,如果成功,则构造控制器。您已在 初始化 Firestore 步骤中将 FirebaseFirestore 实例添加到 main.dart

    dart
    final firestore = context.read<FirebaseFirestore?>();
    if (firestore == null) {
      _log.warning(
        "Firestore instance wasn't provided. "
        'Running without _firestoreController.',
      );
    } else {
      _firestoreController = FirestoreController(
        instance: firestore,
        boardState: _boardState,
      );
    }
    
  5. 使用同一类的 dispose() 方法销毁控制器。

    dart
    _firestoreController?.dispose();
    

6. 测试游戏

#
  1. 在两台单独的设备上或在同一设备上的 2 个不同的窗口中运行游戏。

  2. 观察在一个设备上添加卡片到区域,它如何在另一个设备上出现。

  3. 打开 Firebase Web 控制台 并导航到您的项目 Firestore 数据库。

  4. 观察它如何实时更新数据。您甚至可以在控制台中编辑数据,并查看所有正在运行的客户端更新。

    Screenshot of the Firebase Firestore data view

故障排除

#

测试 Firebase 集成时,您可能会遇到以下常见问题

  • 游戏在尝试访问 Firebase 时崩溃。

    • Firebase 集成未正确设置。重新访问 步骤 2 并确保将 flutterfire configure 作为该步骤的一部分运行。
  • 游戏在 macOS 上无法与 Firebase 通信。

    • 默认情况下,macOS 应用程序没有互联网访问权限。首先启用 互联网授权

7. 后续步骤

#

此时,游戏具有近乎即时且可靠的跨客户端状态同步。它缺少实际的游戏规则:何时可以玩哪些卡牌以及结果如何。这取决于游戏本身,由您来尝试。

An illustration of two mobile phones and a two-way arrow between them

此时,比赛的共享状态仅包括两个游戏区域和其中的卡牌。您还可以将其他数据保存到 _matchRef 中,例如玩家是谁以及轮到谁了。如果您不确定从哪里开始,请遵循 Firestore 代码实验室 以熟悉 API。

起初,与同事和朋友测试您的多人游戏时,单个比赛就足够了。在接近发布日期时,请考虑身份验证和匹配。幸运的是,Firebase 提供了 内置方式来验证用户,Firestore 数据库结构可以处理多个比赛。您可以将比赛集合填充为需要的记录数,而不是单个 match_1

Screenshot of the Firebase Firestore data view with additional matches

在线比赛可以从“等待”状态开始,只有第一名玩家存在。其他玩家可以在某种大厅中看到“等待”比赛。一旦有足够多的玩家加入比赛,它将变为“活动”。再次,确切的实现取决于您想要什么样的在线体验。基本原理仍然相同:一个大型文档集合,每个文档代表一个活动或潜在的比赛。