Open In App

Flutter – A Simple Multi-Player Dice Game

Last Updated : 11 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Full Dart Code Explanation:

  1. The code starts by importing the necessary libraries.
  2. The first library is dart:math which is used to calculate various mathematical operations.
  3. Next, the Material design library is imported.
  4. This library provides a set of widgets that can be used to create user interfaces in Flutter.
  5. The main() function starts by running the app.
  6. The runApp() function takes two arguments: the first argument is an instance of MaterialApp and the second argument is a list of widget instances.
  7. In this example, there are three widget instances: Dice(), Scaffold(), and AppBar().
  8. The Dice class extends StatefulWidget .
  9. A StatefulWidget is a type of widget that maintains a history of its current state and can be restored to its previous state if it gets destroyed and recreated.
  10. In other words, when you create a StatefulWidget , it remembers what its current state was when it was last closed (or destroyed).
  11. This allows you to easily restore a widget’s previous appearance after making changes to it.
  12. The Dice class has one property named analyze .
  13. When this property gets initialized, it sets up some basic analysis parameters for the dice game that will be played later on in the code.
  14. These parameters include how many sides each die has (
  15. The code will create a new MaterialApp and configure it to disable the debug tag.
  16. This is so that we can see the output of our code in a more readable fashion.
  17. Next, we create a new Scaffold object and set its background color to green.
  18. We also set the appBar to have a green background color and title to Text(“GeeksForGeeks”).
  19. Finally, we set centerTitle to be true so that the title is centered within the appBar.
  20. Next, we create a new Dice object and configure it as follows: The first property is called _size which specifies how many sides the dice will have.
  21. The second property is called _face which specifies what face (1-6) will be
  22. The code starts by declaring two variables: playerOne and playerTwo.
  23. These will store the number 1 or 2, respectively, at any given time during the game.
  24. Next, the code sets up a function to roll the dice.
  25. This function randomly assigns one of the two numbers (playerOne or playerTwo) to be 1 and the other to be 2.
  26. It then checks which number is greater (playerOne or playerTwo).
  27. If it’s playerOne that’s greater, then the code sets result to “Player 1 Wins.”
  28. Otherwise if it’s playerTwo that’s greater, then result is set to “Player 2 Wins.”
  29. Finally, if there was a draw, result is set to “Draw.”
  30. The next part of the code deals with displaying buttons for each player.
  31. The first button displays an image of a die with number one on it.
  32. The second button displays an image of a die with number two on it.
  33. When either button is pressed, the rollDice() function will be called.
  34. rollDice() simply calls setState(), which updates all of the dice variables based on what was rolled in randomizer().
  35. Then play proceeds as normal until someone wins!
  36. The code creates a Dice class with two properties – playerOne and playerTwo.
  37. It also creates a function called rollDice which will be used to randomly select the dice values and then determine the winner of the game.
  38. The build() method is responsible for creating the UI elements needed for the game.
  39. The first element created is a Column which will have playerOne and playerTwo as its children.
  40. The second element is a Row which will contain two MaterialButton elements – one for playerOne and one for playerTwo.
  41. When either button is pressed, rollDice() will be called.
  42. There’s not much else to say about this code, so we’ll move on to the next section!


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads