Creating a Casual Game Leaderboard in Flutter

Flutter 3 has introduced several exciting features, including support for creating casual games with the Casual Games Toolkit and template. This template provides built-in functionalities such as sounds, advertisements, play service linking, and more. In this article, we will explore how to build a Flutter gaming leaderboard using Firebase Realtime Database.

Building a Casual Asteroid Game in Flutter

Before diving into building a leaderboard, let’s create a simple asteroid game. The game concept is straightforward: the player must prevent a moving asteroid from colliding with a spaceship using a mouse or trackpad.

Creating the Spaceship

To build our Flutter game, we’ll start by creating a spaceship that follows the mouse and trackpad using the MouseRegion widget.

dart
MouseRegion(
onHover: (event) {
setState(() {
_spaceshipPosition = event.position;
});
},
child: Container(
width: 50,
height: 50,
color: Colors.blue,
),
)

Building the Obstacles

Next, we’ll add randomly moving obstacles (asteroids) to the game.

“`dart
class Asteroid extends StatefulWidget {
@override
_AsteroidState createState() => _AsteroidState();
}

class _AsteroidState extends State with SingleTickerProviderStateMixin {
AnimationController _animationController;

@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
)..repeat();
}

@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _animationController,
builder: (context, child) {
return Transform.translate(
offset: Offset(
_animationController.value * 100,
_animationController.value * 100,
),
child: Container(
width: 50,
height: 50,
color: Colors.red,
),
);
},
);
}
}
“`

Adding the Spaceship and Obstacles to a Stack Widget

Now, we can add the spaceship and multiple asteroids to a stack widget.

dart
Stack(
children: [
Spaceship(),
Asteroid(),
Asteroid(),
],
)

Building the Flutter Gaming Leaderboard

A leaderboard shows a user’s score compared to all other online players. To create a leaderboard, we need to set a metric that shows the user’s performance in the game. In this case, we’ll use the game duration.

Tracking the Game Duration

To track the game duration, we can subtract the saved game start time from the time the game ends.

dart
int _gameDuration = DateTime.now().millisecondsSinceEpoch - _gameStartTime;

Setting up Firebase

To create a leaderboard, we need to set up Firebase Realtime Database. First, create a Firebase account and navigate to the Firebase console. Then, select “Create a new project” and follow the setup process.

Authenticating and Logging in the User

To save and retrieve user scores, we need to authenticate the user. We can use the email and password method provided by Firebase.

dart
FirebaseAuth.instance.signInWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);

Tracking High Scores with Firebase Database

To track high scores, we need to structure our data in a way that allows us to easily save, retrieve, and sort according to ranks. We can use the Firebase database to achieve this.

dart
FirebaseDatabase.instance.reference().child('leaderboard').push().set({
'score': _gameDuration,
'name': _usernameController.text,
});

Displaying All Leaderboard High Scores with a Data Table

To display all leaderboard high scores, we can use a data table.

dart
DataTable(
columns: [
DataColumn(label: Text('Rank')),
DataColumn(label: Text('Name')),
DataColumn(label: Text('Score')),
],
rows: _leaderboardScores.map((score) {
return DataRow(
cells: [
DataCell(Text(score['rank'].toString())),
DataCell(Text(score['name'])),
DataCell(Text(score['score'].toString())),
],
);
}).toList(),
)

By following these steps, we can create a casual game leaderboard in Flutter using Firebase Realtime Database.

Leave a Reply

Your email address will not be published. Required fields are marked *