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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值