Setting Up a Widget-Tree Based Game with Flame and Flutter

in #originalworks6 years ago

One of the advantages of being a developer making your own games is that you have full control over the outcome. You control how a certain element functions or how an enemy character behaves. You can even control the (in-game) world and play around with the physical rules like gravity.

<p dir="auto"><img src="https://images.hive.blog/768x0/https://jap.alekhin.io/wp-content/uploads/2019/05/setup-widget-tree-flame-flutter-game.jpg" srcset="https://images.hive.blog/768x0/https://jap.alekhin.io/wp-content/uploads/2019/05/setup-widget-tree-flame-flutter-game.jpg 1x, https://images.hive.blog/1536x0/https://jap.alekhin.io/wp-content/uploads/2019/05/setup-widget-tree-flame-flutter-game.jpg 2x" /> <p dir="auto">With this kind of freedom though, most beginner developers find it hard to establish a structure when developing games along with the UI that goes with it. <h2>Standard structure <p dir="auto">It seems that <strong>there’s no standard structure when it comes to game development with <a href="https://flame-engine.org/" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Flame and <a href="https://flutter.dev/" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Flutter. <p dir="auto">The closest thing to it is simply feeding the main game class’ <code>.widgetproperty directly into <code>runApp. This setup is perfect for simple “tap-tap” games and the hyper-casual games like <a href="https://github.com/japalekhin/langaw" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Langaw. <p dir="auto"><img src="https://images.hive.blog/768x0/https://jap.alekhin.io/wp-content/uploads/2019/05/langaw.jpg" srcset="https://images.hive.blog/768x0/https://jap.alekhin.io/wp-content/uploads/2019/05/langaw.jpg 1x, https://images.hive.blog/1536x0/https://jap.alekhin.io/wp-content/uploads/2019/05/langaw.jpg 2x" /> <p dir="auto">Here’s an example <code>./lib/main.js from <strong>Shadow Training. <pre><code>import 'package:flame/flame.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:shadow_training/shadow-training.dart'; void main() async { await Flame.util.fullScreen(); await Flame.util.setOrientation(DeviceOrientation.portraitUp); await Flame.images.loadAll([ 'background.png', 'boxer/dizzy.png', 'boxer/idle.png', 'boxer/punch-left.png', 'boxer/punch-right.png', 'boxer/punch-up.png', ]); ShadowTraining game = ShadowTraining(); runApp(game.widget); TapGestureRecognizer tapper = TapGestureRecognizer(); tapper.onTapDown = game.onTapDown; Flame.util.addGestureRecognizer(tapper); } <p dir="auto">If a game has been released for a while, chances are, there are going to be updates. These updates most probably present more features. <p dir="auto">As the number of features grows, the game will be needing <strong>UI (user-interface) elements. <p dir="auto">UI elements help the players connect, understand, and interact with the game. Examples of UI elements include the score display, health bar, settings dialog box, exit button, play button. <p dir="auto">In fact, even the simplest game (except maybe the <a href="https://github.com/japalekhin/boxgame" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Box Game) needs to have at least a play button or a score display. <p dir="auto">This presents a problem with the “standard structure” as this would mean building the UI manually. <strong>The developer has to write everything. Rendering managing states and screens, <strong>and animation. <p dir="auto">Again, as long the game is simple, this can be bearable to manually write. <p dir="auto">The moment your game gets more complex than a game that can be described as dead simple, this becomes an easy source of a headache (<em>based on personal experience). <h2>Taking advantage of the widget-tree <p dir="auto">Let me introduce Flutter, no wait, we’re already developing in Flutter. When developing games using Flame, it’s easy to forget that we’re still developing apps using Flutter. <p dir="auto">Flutter is actually a framework designed for business mobile app development. The type of apps that aren’t really that graphical, just some nice looking buttons, lists, labels, checkboxes, input controls. Maybe some basic animation and transition effects. <p dir="auto">One of the things that are very easy to do in Flutter is UI. Exactly those elements we need for our game but too troublesome to write on our own. <p dir="auto"><strong>Let’s take advantage of this <p dir="auto">A Flame game is still rendered inside a widget (<code>Game‘s <code>.widgetproperty). If we put this game widget in a <code>Stack, we can easily build UI elements on top of it. <p dir="auto"><img src="https://images.hive.blog/768x0/https://jap.alekhin.io/wp-content/uploads/2019/05/shadow-training-dialog.jpg" srcset="https://images.hive.blog/768x0/https://jap.alekhin.io/wp-content/uploads/2019/05/shadow-training-dialog.jpg 1x, https://images.hive.blog/1536x0/https://jap.alekhin.io/wp-content/uploads/2019/05/shadow-training-dialog.jpg 2x" /> <p dir="auto">Here’s the same code from <strong>Shadow Training‘s <code>./lib/main.dart; but this time the game widget is enclosed in a <code>MaterialApp widget (for possible navigation or routing between screens in the future). <pre><code>import 'package:flame/flame.dart'; import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:shadow_training/shadow-training-ui.dart'; import 'package:shadow_training/shadow-training.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() async { await Flame.util.fullScreen(); await Flame.util.setOrientation(DeviceOrientation.portraitUp); await Flame.images.loadAll([ 'background.png', 'boxer/dizzy.png', 'boxer/idle.png', 'boxer/punch-left.png', 'boxer/punch-right.png', 'boxer/punch-up.png', 'markers.png', 'perfect-time.png', ]); SharedPreferences storage = await SharedPreferences.getInstance(); ShadowTrainingUI gameUI = ShadowTrainingUI(); ShadowTraining game = ShadowTraining(gameUI.state); gameUI.state.storage = storage; gameUI.state.game = game; runApp( MaterialApp( title: 'Shadow Training', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( body: Stack( fit: StackFit.expand, children: [ Positioned.fill( child: GestureDetector( behavior: HitTestBehavior.opaque, onTapDown: game.onTapDown, child: game.widget, ), ), Positioned.fill( child: gameUI, ), ], ), ), debugShowCheckedModeBanner: false, ), ); } <p dir="auto">The main difference here is instead of passing <code>game.widget directly to <code>runApp, we pass a <code>MaterialApp first. This <code>MaterialApp has a <code>Scaffold as its <code>home property (which is basically the child widget that will be shown when starting the app). <p dir="auto">The <code>Scaffold in turn, has a <code>Stack as its body. <p dir="auto">This <code>Stack has two <code>Positioned.fill widgets as its children. This is just to make sure that whatever gets assigned as their children will take up the entire screen. One has the <code>game.widget, the other has <code>gameUI which is a <code>ShadowTrainingUI. It’s a class that extends a <code>StatefulWidget. <h2>Performance and drawbacks <p dir="auto">As I was developing and testing the game, I checked and kept an eye on the performance every step of the way. <p dir="auto">There’s actually a commented out code that prints out the real-time FPS of the game and this is what I’ve been monitoring. The whole time I was close to 60 FPS. <p dir="auto">
<p dir="auto">That being said, there were no noticeable performance issues seen during these tests. So having the widget inside a <code>MaterialApp in the widget tree while running the game is fine within a Flame game. <p dir="auto">Of course, this can’t all be good. There are some drawbacks like the need to expose the state in the widget so you can pass it on the to the game class. This is important in order to update the state of the UI from the game class. <p dir="auto">A two-way communication system between the game and the UI class is important as you will probably need to write code on each side that changes things on the other side. <p dir="auto">This can be a tricky situation but can be solved by writing the classes so they have instance variables that hold the reference to the other. Another way is to have a globally accessible singleton class that has references to both the main game class and the UI class. <h2>Conclusion <p dir="auto">Based on my experience developing games using Flame and Flutter, I have found out that having a regular widget tree in a game is generally good practice. <p dir="auto">Buttons, text, dialog boxes, text input, and other UI elements become significantly easier to create. <p dir="auto">There’s no set-back on performance and the only thing tricky to set up is the communication between the game and the UI class. <p dir="auto">If you have any questions, please leave a comment below or ask me by joining <a href="https://discord.gg/SNvNfas" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">my Discord server. Shadow Training is an open-source game that can be found <a href="https://github.com/japalekhin/shadow-training" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">on GitHub.
Sort:  

Some cool activity you have there. I am always wondering if I would have not pursued my profession, will I do the same? Having a passion for computers and the like and maybe has some background on programming, it would have been fun and exciting. Especially if your concept will become a trend, no one really knows.

Anyway, good luck with your endeavor and I hope that many will follow you and your games. Just don't stop and I am sure that you can formulate something unique that will attract many players. Cheers.

Hey, thanks for visiting and the encouragement.

It's not too late! You can do programming as a non-serious hobby. :D

Thank you japalekhin! You've just received an upvote of 43% by artturtle!


Learn how I will upvote each and every one of your posts



Please come visit me to see my daily report detailing my current upvote power and how much I'm currently upvoting.

Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.Congratulations! This post has been upvoted from the communal account, @minnowsupport, by JapAlekhin from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.

Hi japalekhin,

This post has been upvoted by the Curie community curation project and associated vote trail as exceptional content (human curated and reviewed). Have a great day :)

Visit curiesteem.com or join the Curie Discord community to learn more.