📜  Flutter - 一个简单的多人骰子游戏

📅  最后修改于: 2022-05-13 01:55:07.489000             🧑  作者: Mango

Flutter - 一个简单的多人骰子游戏

在这里,我们将创建一个骰子游戏。顾名思义,将有两个骰子,玩家一或玩家二掷骰子,根据结果决定获胜者。

什么是Flutter?

Flutter是 Google 的 UI 工具包,用于从单个代码库为移动、Web、桌面和嵌入式设备构建漂亮的、本地编译的应用程序。在安装flutter的指南可以在他们的文档中找到。

创建一个新的Flutter项目

安装flutter,您可能选择了首选编辑器。只需在编辑器上创建一个新的flutter项目即可。如果您希望通过命令行创建项目或者如果您使用的是 VS Code,请在终端中输入以下命令

$ flutter创建骰子

构建应用程序的方法

在我们开始使用flutter之前,让我们先来看看构建我们的游戏的方法。我们将添加 6 个骰子图像,每个图像都有数字 (1-6)。一开始,两个骰子都会显示 1 并且没有结果。当玩家 1 或玩家 2 掷骰子时,我们将随机选择我们添加的 6 个图像中的一个,并根据结果宣布结果是玩家 1 获胜还是玩家 2 或平局。



将资产添加到项目

要在flutter项目中添加资产,您可以在项目的根目录下创建一个包含所有资产的文件夹。现在我们只有图像资产,我们将创建一个名为“images”的文件夹并将图像添加到该文件夹中。通常,您会创建一个名为 assets 的文件夹,然后在其中创建一个名为 images 的文件夹,这是因为很多时候应用程序具有不同的资产,例如音频、视频等。您可以在互联网上找到带有骰子的图像。

为了让flutter知道我们已经添加了这些图像,我们将转到pubspec.yaml文件并取消注释资产行并添加图像文件夹。

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
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
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
# following page: https://dart.dev/tools/pub/pubspec
  
# 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
  # https://flutter.dev/assets-and-images/#resolution-aware.
  
  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages
  
  # 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,
  # see https://flutter.dev/custom-fonts/#from-packages


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(),
    ),
  ));
}


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 {
  @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,
          ),
        ),
      ],
    );
  }
}


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 {
  // 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,
          ),
        ),
      ],
    );
  }
}


代码为主。dart文件

首先,确保您删除了 main.js 中的所有代码。 dart文件并删除 test 文件夹中的文件。

初始化Flutter应用

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(),
    ),
  ));
}

运行应用程序后,您将在屏幕上看到带有标题的应用程序栏。

显示骰子

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 {
  @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,
          ),
        ),
      ],
    );
  }
}

添加掷骰子和宣布获胜者的功能

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 {
  // 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,
          ),
        ),
      ],
    );
  }
}

输出: