Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Flutter – A Simple Multi-Player Dice Game

  • Last Updated : 16 Aug, 2021

Here, we are going to create a dice game. As the name suggests there will be two dice and either player one or player two rolls the dice and according to the result the winner is decided.

What is Flutter?

Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, desktop, and embedded devices from a single codebase. Guide on installation of flutter can be found on their documentation.

Create a new Flutter project

When installing flutter you might have selected your preferred editor. Just go on the editor and create a new flutter project. If you wish to create the project via command line or if you are using VS Code enter the following command in terminal

$ flutter create dice

Approach to building the application

Before we start with flutter let’s first take a look at the approach to building our game. We’ll add 6 images of dice each having numbers (1-6). At first, both dice will show 1  and no result. When either player 1 or player 2 rolls the dice we’ll randomly select one of the 6 images we added and based on the outcome we’ll declare the result whether it is player 1 who won or player 2 or it is a draw. 



Add assets to the project

To add assets in the flutter project you can create a folder that contains all your assets at the root of the project. Now that we only have image assets we’ll create a folder called “images” and add the images to that folder. Typically you would create a folder called assets then inside it a folder called images this is due to the fact that many times apps have different assets such as audio, video, etc. You can find images with dice on the internet.

To let flutter know that we have added these images we’ll go to pubspec.yaml file and uncomment the assets line and added the image folder.

XML




name: dice
description: A new Flutter project.
  
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
  
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
version: 1.0.0+1
  
environment:
  sdk: ">=2.12.0 <3.0.0"
  
dependencies:
  flutter:
    sdk: flutter
  
  
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  
dev_dependencies:
  flutter_test:
    sdk: flutter
  
# For information on the generic Dart part of this file, see the
  
# The following section is specific to Flutter.
flutter:
  
  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true
  
  # To add assets to your application, add an assets section, like this:
  assets:
    - images/
  
  # An image asset can refer to one or more resolution-specific "variants", see
  
  # For details regarding adding assets from package dependencies, see
  
  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,

Code main.dart file

First, make sure that you delete all the code inside the main.dart file and delete the file inside the test folder.

Initialize Flutter app

Dart




import 'package:flutter/material.dart';
// The main function from where the execution starts //
void main() {
  // runApp function which starts the application //
  runApp(MaterialApp(
    // Disables debug tag which are in the flutter apps //
    debugShowCheckedModeBanner: false,
    // Scaffold is like canvas it is generally
    // in the root of screen widget //
    home: Scaffold(
      backgroundColor: Colors.green,
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: Text("GeeksForGeeks"),
        centerTitle: true,
      ),
      body: Container(),
    ),
  ));
}

After running the app you’ll see the app bar with a title on your screen.

Display the dice

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(MaterialApp(
    // Disables debug tag which are in the flutter apps //
    debugShowCheckedModeBanner: false,
    home: Scaffold(
     backgroundColor: Colors.green,
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: Text("GeeksForGeeks"),
        centerTitle: true,
      ),
      body: Dice(),
    ),
  ));
}
  
class Dice extends StatefulWidget {
  const Dice({Key? key}) : super(key: key);
  
  @override
  _DiceState createState() => _DiceState();
}
  
class _DiceState extends State<Dice> {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Column(
              children: [
                MaterialButton(
                  child:
                      Image.asset('images/dice1.png', height: 150, width: 150),
                  onPressed: () {},
                ),
                Text(
                  "Player 1",
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                    fontSize: 10,
                  ),
                ),
              ],
            ),
            Column(
              children: [
                MaterialButton(
                  child: Image.asset(
                    'images/dice1.png',
                    height: 150,
                    width: 150,
                  ),
                  onPressed: () {},
                ),
                Text(
                  "Player 2",
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                    fontSize: 10,
                  ),
                ),
              ],
            )
          ],
        ),
        // To create space between dice and result //
        SizedBox(
          height: 20,
        ),
        Text(
          "result",
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.white,
            fontSize: 20,
          ),
        ),
      ],
    );
  }
}

Add functionality of rolling the dice and announcing the winner

Dart




import 'dart:math';
import 'package:flutter/material.dart';
  
void main() {
  runApp(MaterialApp(
    // Disables debug tag which are in the flutter apps //
    debugShowCheckedModeBanner: false,
    home: Scaffold(
      backgroundColor: Colors.green,
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: Text("GeeksForGeeks"),
        centerTitle: true,
      ),
      body: Dice(),
    ),
  ));
}
  
class Dice extends StatefulWidget {
  const Dice({Key? key}) : super(key: key);
  
  @override
  _DiceState createState() => _DiceState();
}
  
class _DiceState extends State<Dice> {
  // Initialize the dice to 1 //
  int playerOne = 1;
  int playerTwo = 1;
  String result = "";
  // Function to roll the dice and decide the winner//
  void rollDice() {
    setState(() {
      // Randomise the dice //
      playerOne = Random().nextInt(6) + 1;
      playerTwo = Random().nextInt(6) + 1;
      // Check which player won //
      if (playerOne > playerTwo) {
        result = "Player 1 Wins";
      } else if (playerTwo > playerOne) {
        result = "Player 2 Wins";
      } else {
        result = "Draw";
      }
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Column(
              children: [
                MaterialButton(
                  child: Image.asset('images/dice$playerOne.png',
                      height: 150, width: 150),
                  onPressed: () {
                    rollDice();
                  },
                ),
                Text(
                  "Player 1",
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                    fontSize: 10,
                  ),
                ),
              ],
            ),
            Column(
              children: [
                MaterialButton(
                  child: Image.asset(
                    'images/dice$playerTwo.png',
                    height: 150,
                    width: 150,
                  ),
                  onPressed: () {
                    rollDice();
                  },
                ),
                Text(
                  "Player 2",
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                    fontSize: 10,
                  ),
                ),
              ],
            )
          ],
        ),
        // To create space between dice and result //
        SizedBox(
          height: 20,
        ),
        Text(
          result,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.white,
            fontSize: 20,
          ),
        ),
      ],
    );
  }
}

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :