Flutter 做一个类似超级玛丽 (想不起来名字 挺好玩反正)Flutter写个小游戏,欢迎一起撸代码 185行 代码逆天改命

Posted 安果移不动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter 做一个类似超级玛丽 (想不起来名字 挺好玩反正)Flutter写个小游戏,欢迎一起撸代码 185行 代码逆天改命相关的知识,希望对你有一定的参考价值。

 效果展示

 

 

代码数量截图

 

实际源码

import 'dart:async';

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

// 范围内大小
const double stageSize = 300;
// 超级玛丽 高度
const double size = 30;
// 墙的高度
const double wallHeight = 60;
enum Direction { Up, Down, None }

enum GameState { Runing, Dead }

class _MyHomePageState extends State<MyHomePage> {
  //玛丽的宽度
  double marioY = stageSize;

  // 墙的高度
  double wallX = stageSize;

  Direction direction = Direction.None;

  GameState gameState = GameState.Runing;

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: gameState == GameState.Runing ? buildGameRuning() : buildGameDead(),
// This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  GestureDetector buildGameRuning() {
    return GestureDetector(
      onTap: () {
        //点击后挑起
        setState(() {
          direction = Direction.Up;
        });
      },
      child: Container(
        width: stageSize,
        height: stageSize,
        decoration:
            BoxDecoration(border: Border.all(width: 1, color: Colors.black)),
        child: Stack(
          children: [
            //玛丽

            Positioned.fromRect(
                rect: Rect.fromCenter(
                    center: Offset(size / 2, marioY - size / 2),
                    width: size,
                    height: size),
                child: Container(
                  color: Colors.orange,
                )),
            //障碍物
            Positioned.fromRect(
                rect: Rect.fromCenter(
                    center:
                        Offset(wallX - size / 2, stageSize - wallHeight / 2),
                    width: size,
                    height: wallHeight),
                child: Container(
                  color: Colors.black,
                ))
          ],
        ),
      ),
    );
  }

  /**
   * 每次在build之前会被调用
   */
  @override
  void didChangeDependencies() {
    var duration = Duration(milliseconds: 5);
    Timer.periodic(duration, (timer) {
      double newMarioy = marioY;
      Direction newDirection = direction;
      //根据方向 先上去 再下来
      switch (direction) {
        case Direction.Up:
          newMarioy--;
          if (newMarioy < 100) {
            newDirection = Direction.Down;
          }
          break;
        case Direction.Down:
          newMarioy++;
          if (newMarioy > stageSize) {
            newDirection = Direction.None;
          }
          break;
      }
      // 判断碰撞
      if (wallX < size && marioY > stageSize - wallHeight) {
        setState(() {
          gameState = GameState.Dead;
        });
      }
      setState(() {
        marioY = newMarioy;
        direction = newDirection;
        //障碍物移动走后再回来
        wallX = (wallX -= 1 + stageSize) % stageSize;
      });
    });
    super.didChangeDependencies();
  }

  buildGameDead() {
    return GestureDetector(
      onTap: () {
        setState(() {
          gameState = GameState.Runing;
        });
      },
      child: Container(
        child: Center(
          child: Text("游戏结束,点击我重新开始"),
        ),
      ),
    );
  }
}

如果希望更加了解这些代码怎么写的 可以观看出处

https://www.bilibili.com/video/BV16f4y1G7bu

以上是关于Flutter 做一个类似超级玛丽 (想不起来名字 挺好玩反正)Flutter写个小游戏,欢迎一起撸代码 185行 代码逆天改命的主要内容,如果未能解决你的问题,请参考以下文章

《超级玛丽》1

P1000 超级玛丽游戏

1.1超级玛丽游戏

P1000 超级玛丽游戏

NOI-1.1-10-字符表示超级玛丽

P1000 超级玛丽游戏