### Method Documentation Example Source: https://github.com/flame-engine/flame/blob/main/doc/development/style_guide.md Document methods starting with a verb in the present simple tense. Include a paragraph break after the first sentence and mention pre- and post-conditions for clarity. ```dart /// Adds a new [child] into the container, and becomes the owner of that /// child. /// /// The child will be disposed of when this container is destroyed. /// It is an error to try to add a child that already belongs to another /// container. void addChild(T child) { ... } ``` -------------------------------- ### Install documentation requirements Source: https://github.com/flame-engine/flame/blob/main/doc/development/documentation.md Run this command to install the necessary dependencies for building the documentation. ```shell melos run doc-setup ``` -------------------------------- ### Verify Flutter Installation Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/bare_flame_game.md Use this command to check that the Flutter SDK is correctly installed and accessible. ```shell $ flutter doctor Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel stable, 3.13.7, on macOS 13.6 22G120 darwin-arm64, locale en) [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0) [✓] Xcode - develop for iOS and macOS (Xcode 15.0) [✓] Chrome - develop for the web [✓] Android Studio (version 2021.2) [✓] IntelliJ IDEA Community Edition (version 2022.2.2) [✓] VS Code (version 1.83.0) [✓] Connected device (2 available) [✓] Network resources • No issues found! ``` -------------------------------- ### Example `<>` Command Usage in Yarn Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/runtime/command_storage.md These examples show how the `<>` command can be used in Yarn scripts, illustrating how variables containing item names and quantities are expanded into arguments for the command. ```yarn <> ``` ```yarn <> ``` ```yarn <> ``` ```yarn <> ``` -------------------------------- ### Example: Setting a String Variable Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/commands/set.md This example demonstrates declaring a string variable and then setting its value based on user choices within a dialogue. ```yarn <> title: ColorQuiz --- What is your favorite color? -> White <> -> Red <> -> Yellow <> -> Blue Oh, Nice! Which shade of blue? -> Azure -> Cerulean -> Lapis Lazuli Umm, I don't know how to spell that. I'll just put you down as "blue". <> -> Black <> That's mine too! <> -> Prefer not to tell Aww... Maybe if I ask again really nicely? <> === ``` -------------------------------- ### Install flame_behavior_tree package Source: https://github.com/flame-engine/flame/blob/main/packages/flame_behavior_tree/README.md Add the dependency to your Flutter project using the command line. ```bash flutter pub add flame_behavior_tree ``` -------------------------------- ### Example: Guard Greeting Based on Reputation Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/commands/if.md This example demonstrates dynamic dialogue where a guard's greeting changes based on the player's reputation, including a case for immediate attack if reputation is critically low. ```yarn title: GuardGreeting --- <= 100>> Guard: Hail to the savior of the people! <= 30>> Guard: Nice to meet you, sir! <= 0>> Guard: Hello < -30>> Guard: I'm keeping an eye on you... < -100>> Guard: You filthy scum! <> Guard: You'll pay for your crimes! #auto <> <> === ``` -------------------------------- ### Install flame_steering_behaviors Source: https://github.com/flame-engine/flame/blob/main/packages/flame_steering_behaviors/README.md Add the package dependency to your Flutter project. ```sh flutter pub add flame_steering_behaviors ``` -------------------------------- ### Implement JoystickComponent in Flame Game Source: https://github.com/flame-engine/flame/blob/main/doc/flame/inputs/other_inputs.md This example demonstrates how to integrate a JoystickComponent into a FlameGame. It shows the setup of the joystick with custom sprites and its usage within a Player component to control movement and rotation. ```dart class MyGame extends FlameGame { @override Future onLoad() async { super.onLoad(); final image = await images.load('joystick.png'); final sheet = SpriteSheet.fromColumnsAndRows( image: image, columns: 6, rows: 1, ); final joystick = JoystickComponent( knob: SpriteComponent( sprite: sheet.getSpriteById(1), size: Vector2.all(100), ), background: SpriteComponent( sprite: sheet.getSpriteById(0), size: Vector2.all(150), ), margin: const EdgeInsets.only(left: 40, bottom: 40), ); final player = Player(joystick); add(player); add(joystick); } } class Player extends SpriteComponent with HasGameReference { Player(this.joystick) : super( anchor: Anchor.center, size: Vector2.all(100.0), ); /// Pixels/s double maxSpeed = 300.0; final JoystickComponent joystick; @override Future onLoad() async { sprite = await game.loadSprite('layers/player.png'); position = game.size / 2; } @override void update(double dt) { if (joystick.direction != JoystickDirection.idle) { position.add(joystick.relativeDelta * maxSpeed * dt); angle = joystick.delta.screenAngle(); } } } ``` -------------------------------- ### Initialize segment manager structure Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/platformer/step_3.md Initial setup for the Block class and the segments list. ```dart class Block { // gridPosition position is always segment based X,Y. // 0,0 is the bottom left corner. // 10,10 is the upper right corner. final Vector2 gridPosition; final Type blockType; Block(this.gridPosition, this.blockType); } final segments = [ segment0, ]; final segment0 = [ ]; ``` -------------------------------- ### Implementing SecondaryTapCallbacks Source: https://github.com/flame-engine/flame/blob/main/doc/flame/inputs/tap_events.md This example demonstrates how to use the SecondaryTapCallbacks mixin to handle secondary tap events, such as a right-click on a desktop. ```dart class MyComponent extends PositionComponent with SecondaryTapCallbacks { @override void onSecondaryTapUp(SecondaryTapUpEvent event) { /// Do something } @override void onSecondaryTapCancel(SecondaryTapCancelEvent event) { /// Do something } @override void onSecondaryTapDown(SecondaryTapDownEvent event) { /// Do something } } ``` -------------------------------- ### YarnSpinner File Structure Example Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/language.md Demonstrates the syntax for comments, file-level tags, variable declarations, and node definitions within a .yarn file. ```yarn // This is a comment // The line below, however, is a tag: # Chapter 1d <> <> // is this too much? title: Start --- // Node content === ``` -------------------------------- ### Custom Game World Setup Source: https://github.com/flame-engine/flame/blob/main/doc/README.md Extend `FlameGame` or `World` to create your game's structure. This example shows a custom `MyWorld` class that adds a `Player` component upon loading. ```dart import 'package:flame/game.dart'; import 'package:flame/components.dart'; import 'package:flutter/widgets.dart'; void main() { runApp( GameWidget( game: FlameGame(world: MyWorld()), ), ); } class MyWorld extends World { @override Future onLoad() async { add(Player(position: Vector2(0, 0))); } } ``` -------------------------------- ### Complete Flame Game Example with AudioPools Source: https://github.com/flame-engine/flame/blob/main/doc/bridge_packages/flame_audio/audio_pool.md Demonstrates loading and managing multiple AudioPools within a FlameGame. Includes loading sounds in onLoad and disposing them in onRemove. ```dart import 'package:flame/game.dart'; import 'package:flame_audio/flame_audio.dart'; class MyGame extends FlameGame { late AudioPool laserSound; late AudioPool explosionSound; @override Future onLoad() async { // Load sound effects into audio pools laserSound = await FlameAudio.createPool( 'laser.mp3', minPlayers: 3, maxPlayers: 6, ); explosionSound = await FlameAudio.createPool( 'explosion.mp3', minPlayers: 2, maxPlayers: 4, ); } void fireLaser() async { // Play the laser sound effect - can be called rapidly final stop = await laserSound.start(); // If you need to stop the sound early: // await stop(); } void enemyDestroyed() async { // Play explosion sound effect await explosionSound.start(volume: 0.7); } @override Future onRemove() async { await super.onRemove(); // Clean up resources when the game component is removed await laserSound.dispose(); await explosionSound.dispose(); } } ``` -------------------------------- ### Implementing DoubleTapCallbacks Source: https://github.com/flame-engine/flame/blob/main/doc/flame/inputs/tap_events.md This example demonstrates the use of the DoubleTapCallbacks mixin to detect and respond to double-tap gestures. ```dart class MyComponent extends PositionComponent with DoubleTapCallbacks { @override void onDoubleTapUp(DoubleTapEvent event) { /// Do something } @override void onDoubleTapCancel(DoubleTapCancelEvent event) { /// Do something } @override void onDoubleTapDown(DoubleTapDownEvent event) { /// Do something } } ``` -------------------------------- ### Initialize RouterComponent with Routes Source: https://github.com/flame-engine/flame/blob/main/doc/flame/router.md Set up the RouterComponent with a map of route names to Route objects. Use `initialRoute` to specify the starting screen. ```dart class MyGame extends FlameGame { late final RouterComponent router; @override void onLoad() { add( router = RouterComponent( routes: { 'home': Route(HomePage.new), 'level-selector': Route(LevelSelectorPage.new), 'settings': Route(SettingsPage.new, transparent: true), 'pause': PauseRoute(), 'confirm-dialog': OverlayRoute.existing(), }, initialRoute: 'home', ), ); } } class PauseRoute extends Route { ... } ``` -------------------------------- ### Start and Stop AudioPool Sounds Source: https://github.com/flame-engine/flame/blob/main/doc/bridge_packages/flame_audio/audio_pool.md Play a sound from the AudioPool using the start() method, which returns a StopFunction. Call the StopFunction to manually stop the sound before it finishes. ```dart // Play the sound with default volume (1.0) final stopFunction = await audioPool.start(); // Play the sound with custom volume final stopFunction = await audioPool.start(volume: 0.5); // Later, you can stop the sound if needed await stopFunction(); ``` -------------------------------- ### Handle Drag Start Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/klondike/step4.md Set the component priority to ensure it renders above others during a drag operation. ```dart @override void onDragStart(DragStartEvent event) { priority = 100; } ``` -------------------------------- ### Particle Composition Example Source: https://github.com/flame-engine/flame/blob/main/doc/flame/rendering/particles.md Illustrates particle effect composition using `Particle.generate` with `AcceleratedParticle` and `CircleParticle`. This approach defines behaviors from top to bottom. ```dart Random rnd = Random(); Vector2 randomVector2() => (Vector2.random(rnd) - Vector2.random(rnd)) * 200; // Composition. // // Defining a particle effect as a set of nested behaviors from top to bottom, // one within another: // // ParticleSystemComponent // > ComposedParticle // > AcceleratedParticle // > CircleParticle game.add( ParticleSystemComponent( particle: Particle.generate( count: 10, generator: (i) => AcceleratedParticle( acceleration: randomVector2(), child: CircleParticle( paint: Paint()..color = Colors.red, ), ), ), ), ); ``` -------------------------------- ### Using `<>` for Conditional Dialogue - Yarn Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/commands/visit.md Demonstrates conditional dialogue flow using the `<>` command. This example shows how to conditionally visit different nodes based on game state variables. ```yarn title: RoamingTrader1 --- <> Hello again, {$player}! <> <> <> -> What do you think about the Calamity? <> <> -> Have you seen a weird-looking girl running by? <> <> -> What do you have for trade? <> Pleasure doing business with you! #auto === ``` -------------------------------- ### Implementing TertiaryTapCallbacks Source: https://github.com/flame-engine/flame/blob/main/doc/flame/inputs/tap_events.md This example shows how to implement the TertiaryTapCallbacks mixin for handling tertiary tap events, like a middle-click on a desktop. ```dart class MyComponent extends PositionComponent with TertiaryTapCallbacks { @override void onTertiaryTapUp(TertiaryTapUpEvent event) { /// Do something } @override void onTertiaryTapCancel(TertiaryTapCancelEvent event) { /// Do something } @override void onTertiaryTapDown(TertiaryTapDownEvent event) { /// Do something } } ``` -------------------------------- ### Ceiling function examples Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/expressions/functions/numeric.md Use ceil(x) to round a number up to the nearest integer. ```yarn { ceil(0) } // 0 { ceil(0.3) } // 1 { ceil(5) } // 5 { ceil(5.001) } // 6 { ceil(5.999) } // 6 { ceil(-2.07) } // -2 ``` -------------------------------- ### Example Yarn Line with Markup Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/runtime/markup_attribute.md Demonstrates how to use markup tags like [b] and [link] to format text within a Yarn script. The [link] tag includes a URL parameter. ```yarn [b]Jenny[/b] is a library based on \ [link url="docs.yarnspinner.dev"]YarnSpinner[/link] for Unity. ``` -------------------------------- ### Common variable declaration patterns Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/commands/declare.md Various examples of declaring variables with different types and initial values. ```yarn <> <> <> <> <> <> <> ``` -------------------------------- ### Particle Chaining Example Source: https://github.com/flame-engine/flame/blob/main/doc/flame/rendering/particles.md Shows how to create particle effects using a fluent API with chaining. This method is suitable for `SingleChildParticle` mixins and defines behaviors from bottom to top. ```dart // Chaining. // // Expresses the same behavior as above, but with a more fluent API. // Only Particles with SingleChildParticle mixin can be used as chainable behaviors. game.add( ParticleSystemComponent( particle: Particle.generate( count: 10, generator: (i) => pt.CircleParticle(paint: Paint()..color = Colors.red) ) ) ); ``` -------------------------------- ### Computed Particle Example Source: https://github.com/flame-engine/flame/blob/main/doc/flame/rendering/particles.md Demonstrates creating custom particle behaviors using `ComputedParticle`. This offers maximum flexibility by allowing explicit definition of all behaviors, including rendering logic. ```dart // Computed Particle. // // All the behaviors are defined explicitly. Offers greater flexibility // compared to built-in behaviors. game.add( ParticleSystemComponent( particle: Particle.generate( count: 10, generator: (i) { Vector2 position = Vector2.zero(); Vector2 speed = Vector2.zero(); final acceleration = randomVector2(); final paint = Paint()..color = Colors.red; return ComputedParticle( renderer: (canvas, _) { speed += acceleration; position += speed; canvas.drawCircle(Offset(position.x, position.y), 1, paint); } ); } ) ) ); ``` -------------------------------- ### Set Initial Player Position Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/platformer/step_5.md In the `initializeGame` method, set the player's starting position to ensure they fall onto the ground when the game begins. ```dart _ember = EmberPlayer( position: Vector2(128, canvasSize.y - 128), ); ``` -------------------------------- ### Valid YarnSpinner Variable Names Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/expressions/variables.md Examples of syntactically correct variable names starting with a $ sign. ```text $i $WARNING $_secret_ $door10 $climbed_over_wall_and_avoided_all_guard_patrols $DoorPassword ``` -------------------------------- ### Custom Collision Behavior Implementation Source: https://github.com/flame-engine/flame/blob/main/doc/bridge_packages/flame_behaviors/collision-detection.md Define a custom collision behavior by extending `CollisionBehavior`. This example shows how to handle the start and end of collisions with a specific entity type (`MyCollidingEntity`). ```dart class MyEntityCollisionBehavior extends CollisionBehavior { @override void onCollisionStart( Set intersectionPoints, MyCollidingEntity other, ) { // We are starting colliding with MyCollidingEntity } @override void onCollisionEnd(MyCollidingEntity other) { // We stopped colliding with MyCollidingEntity } } ``` -------------------------------- ### Initialize a YarnProject Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/runtime/yarn_project.md Demonstrates the standard sequence for setting up a YarnProject, including linking custom functions and commands before parsing script files. ```dart final yarn = YarnProject() ..functions.addFunction0('money', player.getMoney) ..commands.addCommand1('achievement', player.earnAchievement) ..parse(readFile('project.yarn')) ..parse(readFile('chapter1.yarn')) ..parse(readFile('chapter2.yarn')); ``` -------------------------------- ### Class Documentation Convention Source: https://github.com/flame-engine/flame/blob/main/doc/development/style_guide.md Start class documentation with the class name itself, followed by a description of its purpose. This convention helps identify the documented class at the beginning of long doc comments. ```dart /// [MyClass] is ... /// [MyClass] serves as ... /// [MyClass] does the following ... ``` -------------------------------- ### Serve documentation locally Source: https://github.com/flame-engine/flame/blob/main/doc/development/documentation.md Automatically recompiles documentation on changes and hosts it at http://localhost:8000/. ```shell melos doc-serve ``` -------------------------------- ### YarnProject Initialization and Parsing Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/runtime/yarn_project.md Demonstrates the standard sequence for initializing a YarnProject, including linking functions and commands, setting locale, and parsing yarn scripts. ```APIDOC ## YarnProject Initialization and Parsing ### Description This snippet shows how to initialize a `YarnProject`, link custom functions and commands, set the locale, and parse multiple yarn script files. ### Method Dart (Example) ### Endpoint N/A (Class Method) ### Parameters N/A ### Request Example ```dart final yarn = YarnProject() ..functions.addFunction0('money', player.getMoney) ..commands.addCommand1('achievement', player.earnAchievement) ..parse(readFile('project.yarn')) ..parse(readFile('chapter1.yarn')) ..parse(readFile('chapter2.yarn')); ``` ### Response N/A (Initialization) ``` -------------------------------- ### Yarn Script Example Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/runtime/dialogue_runner.md This is a simple Yarn script demonstrating basic dialogue flow with choices and jumps. It defines two titles, 'main' and 'Away', to illustrate branching narratives. ```yarn title: main --- Hello -> Hi -> Go away <> === title: Away --- <> === ``` -------------------------------- ### Build documentation site Source: https://github.com/flame-engine/flame/blob/main/doc/development/documentation.md Generates the documentation site into HTML format. ```shell melos doc-build ``` -------------------------------- ### Handle Long Press Events with Visual Feedback Source: https://github.com/flame-engine/flame/blob/main/doc/flame/inputs/long_press_events.md This example demonstrates how to change a component's color on long press start and reset it on long press end. It also shows how to move the component with the pointer during a long press update. ```dart class LongPressSquare extends RectangleComponent with LongPressCallbacks { @override void onLongPressStart(LongPressStartEvent event) { super.onLongPressStart(event); paint.color = Colors.red; } @override void onLongPressMoveUpdate(LongPressMoveUpdateEvent event) { position += event.localDelta; } @override void onLongPressEnd(LongPressEndEvent event) { super.onLongPressEnd(event); paint.color = Colors.blue; } } ``` -------------------------------- ### Increment function examples Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/expressions/functions/numeric.md Use inc(x) to increase a number towards the next integer. If x is an integer, it returns x + 1; otherwise, it returns ceil(x). ```yarn { inc(0) } // 1 { inc(0.3) } // 1 { inc(5.0) } // 6 { inc(5.001) } // 6 { inc(5.999) } // 6 { inc(-2.07) } // -2 ``` -------------------------------- ### Initialize Git Repository and Push to GitHub Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/bare_flame_game.md Commands to initialize a local Git repository, stage all files, commit them, link to a remote GitHub repository, and push the main branch. Ensure the remote URL is replaced with your actual GitHub repository link. ```shell git init git add --all git commit -m 'Initial commit' git remote add origin https://github.com/your-github-username/syzygy.git git branch -M main git push -u origin main ``` -------------------------------- ### Initialize Flutter Project Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/bare_flame_game.md Initialize the current directory as a Flutter project and verify the generated file structure. ```shell flutter create . ``` ```shell $ ls README.md android/ lib/ pubspec.yaml test/ analysis_options.yaml ios/ pubspec.lock syzygy.iml web/ ``` -------------------------------- ### Install CSpell via npm Source: https://github.com/flame-engine/flame/blob/main/CONTRIBUTING.md Installs the CSpell spellchecker globally using npm, which is used for checking markdown files. ```bash npm install -g cspell ``` -------------------------------- ### Implement Simple Splash Screen Source: https://github.com/flame-engine/flame/blob/main/packages/flame_splash_screen/README.md Basic implementation requiring a theme and an onFinish callback. ```dart FlameSplashScreen( theme: FlameSplashTheme.dark, onFinish: (BuildContext context) => Navigator.pushNamed(context, '/your-game-initial-screen'), ) ``` -------------------------------- ### Example: Using Local Variable for Dice Roll in YarnSpinner Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/commands/local.md This example demonstrates declaring a local variable `$roll` for a dice roll within a single node. Local variables are suitable when a variable is only needed temporarily. ```yarn title: a_dice_roll --- <> <> You've rolled 1, rotten luck... <> You've rolled 2, which is still below the average. Try harder! <> You've rolled 3.14159265 (well, almost). <> Your roll is an unlucky number. Please roll again <> You've rolled 10 (when rounded to the nearest ten). Good job! <> === ``` -------------------------------- ### Create Project Directory Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/bare_flame_game.md Create a new directory for the project using standard shell commands. ```shell mkdir -p ~/projects/syzygy cd ~/projects/syzygy ``` -------------------------------- ### Record Starting Position During Drag Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/klondike/step5.md Captures the card's initial position before dragging begins. It's crucial to create a new `Vector2` object to avoid reference issues, ensuring `_whereCardStarted` holds the static starting coordinates. ```dart _isDragging = true; priority = 100; // Copy each co-ord, else _whereCardStarted changes as the position does. _whereCardStarted = Vector2(position.x, position.y); if (pile is TableauPile) { ``` -------------------------------- ### Define segment 0 Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/platformer/step_3.md Example of populating a segment with Block instances. ```dart final segment0 = [ Block(Vector2(0, 0), GroundBlock), Block(Vector2(1, 0), GroundBlock), Block(Vector2(2, 0), GroundBlock), Block(Vector2(3, 0), GroundBlock), Block(Vector2(4, 0), GroundBlock), Block(Vector2(5, 0), GroundBlock), Block(Vector2(5, 1), WaterEnemy), Block(Vector2(5, 3), PlatformBlock), Block(Vector2(6, 0), GroundBlock), Block(Vector2(6, 3), PlatformBlock), Block(Vector2(7, 0), GroundBlock), Block(Vector2(7, 3), PlatformBlock), Block(Vector2(8, 0), GroundBlock), Block(Vector2(8, 3), PlatformBlock), Block(Vector2(9, 0), GroundBlock), ]; ``` -------------------------------- ### Initialize EmberQuestGame Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/platformer/step_2.md Sets up the main game class, loads assets into the cache, and adds the EmberPlayer to the game world. ```dart import 'package:flame/game.dart'; import 'actors/ember.dart'; class EmberQuestGame extends FlameGame { late EmberPlayer _ember; @override Future onLoad() async { await images.loadAll([ 'block.png', 'ember.png', 'ground.png', 'heart_half.png', 'heart.png', 'star.png', 'water_enemy.png', ]); camera.viewfinder.anchor = Anchor.topLeft; _ember = EmberPlayer( position: Vector2(128, canvasSize.y - 70), ); world.add(_ember); } } ``` -------------------------------- ### Implement Bullet Group with Batching Source: https://github.com/flame-engine/flame/blob/main/doc/flame/rendering/images.md Example of using the mixin for a group of bullet components. ```dart class BulletGroup extends PositionComponent with HasAutoBatchedChildren { // Add SpriteComponent children representing bullets } // Add bullets to the group bulletGroup.add(BulletSpriteComponent(...)); ``` -------------------------------- ### Floor function examples Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/expressions/functions/numeric.md Use floor(x) to round a number down to the nearest integer. ```yarn { floor(0) } // 0 { floor(0.3) } // 0 { floor(5) } // 5 { floor(5.001) } // 5 { floor(5.999) } // 5 { floor(-2.07) } // -3 ``` -------------------------------- ### Register Overlays in Main Entry Point Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/platformer/step_7.md Configures the GameWidget to include the Main Menu and Game Over overlays. ```dart void main() { runApp( GameWidget.controlled( gameFactory: EmberQuestGame.new, overlayBuilderMap: { 'MainMenu': (_, game) => MainMenu(game: game), 'GameOver': (_, game) => GameOver(game: game), }, initialActiveOverlays: const ['MainMenu'], ), ); } ``` ```dart import 'overlays/game_over.dart'; import 'overlays/main_menu.dart'; ``` -------------------------------- ### Project Structure Overview Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/space_shooter/step_1.md Displays the recommended directory layout for a Flame project. ```text space_shooter/ ├─assets/ │ └─images/ ├─lib/ │ └─main.dart └─pubspec.yaml ``` -------------------------------- ### Configure assets in pubspec.yaml Source: https://github.com/flame-engine/flame/blob/main/packages/flame_audio/README.md Register the audio assets directory in your pubspec.yaml file. ```yaml assets: - assets/audio ``` -------------------------------- ### Checkout specific Flutter version Source: https://github.com/flame-engine/flame/blob/main/packages/flame_3d/CONTRIBUTING.md Updates the local Flutter installation to the specific commit required by the package. ```sh cd $(dirname $(which flutter)) \ && git fetch \ && git checkout bcdd1b2c481bca0647beff690238efaae68ca5ac -q \ && echo "Engine commit: $(cat internal/engine.version)" \ && cd - >/dev/null ``` -------------------------------- ### Embed Flutter Tutorial App Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/klondike/step5.md Directive to display the Klondike tutorial application source code. ```rst {flutter-app} :sources: ../tutorials/klondike/app :page: step5 :show: popup code ``` -------------------------------- ### Add flame_texturepacker to Flutter Project Source: https://github.com/flame-engine/flame/blob/main/doc/bridge_packages/flame_texturepacker/flame_texturepacker.md Install the flame_texturepacker package using Flutter's package manager. ```shell flutter pub add flame_texturepacker ``` -------------------------------- ### Invoke a custom Yarn command Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/runtime/command_storage.md Example of calling a registered command with string arguments in a Yarn script. ```yarn <> ``` -------------------------------- ### Create AudioPool Directly with Source Source: https://github.com/flame-engine/flame/blob/main/doc/bridge_packages/flame_audio/audio_pool.md Instantiate an AudioPool directly using a Source object, allowing for more control over the audio source. An optional AudioCache can be provided. ```dart import 'package:audioplayers/audioplayers.dart'; import 'package:flame_audio/flame_audio.dart'; Future loadSounds() async { // Create a pool with a specific Source AudioPool explosionSoundPool = await AudioPool.create( source: AssetSource('explosion.mp3'), minPlayers: 1, maxPlayers: 2, audioCache: FlameAudio.audioCache, // Optional ); } ``` -------------------------------- ### Restrict Drag Start Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/klondike/step4.md Check if a card is allowed to move based on its current pile before initiating the drag. ```dart void onDragStart(DragStartEvent event) { if (pile?.canMoveCard(this) ?? false) { super.onDragStart(event); priority = 100; } } ``` -------------------------------- ### Initialize FlameGame Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/klondike/step1.md Basic entry point for a Flame game application. ```dart import 'package:flame/game.dart'; import 'package:flutter/widgets.dart'; void main() { final game = FlameGame(); runApp(GameWidget(game: game)); } ``` -------------------------------- ### Get Random Segment Index Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/platformer/step_4.md Generates a random integer to select a segment. Ensure `segments.length` is accessible. ```dart Random().nextInt(segments.length), ``` -------------------------------- ### Find Sprite by Name and Index Source: https://github.com/flame-engine/flame/blob/main/doc/bridge_packages/flame_texturepacker/flame_texturepacker.md Get a sprite from the atlas by its name and a specific index, useful for sequences. ```dart final sprite = atlas.findSpriteByNameIndex('robot_walk', 0); ``` -------------------------------- ### Initialize and Implement SpineComponent in Flame Source: https://github.com/flame-engine/flame/blob/main/doc/bridge_packages/flame_spine/flame_spine.md Demonstrates initializing the Spine runtime and loading a Spine asset into a FlameGame using SpineComponent. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); await initSpineFlutter(); runApp(const GameWidget.controlled(gameFactory: SpineExample.new)); } class FlameSpineExample extends FlameGame { late final SpineComponent spineboy; @override Future onLoad() async { await initSpineFlutter(); // Load the Spineboy atlas and skeleton data from asset files // and create a SpineComponent from them, scaled down and // centered on the screen spineboy = await SpineComponent.fromAssets( atlasFile: 'assets/spine/spineboy.atlas', skeletonFile: 'assets/spine/spineboy-pro.skel', scale: Vector2(0.4, 0.4), anchor: Anchor.center, position: size / 2, ); // Set the "walk" animation on track 0 in looping mode spineboy.animationState.setAnimationByName(0, 'walk', true); await add(spineboy); } @override void onDetach() { // Dispose the native resources that have been loaded for spineboy. spineboy.dispose(); } } ``` -------------------------------- ### Invalid YarnSpinner Variable Names Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/expressions/variables.md Examples of syntactically incorrect variable names that do not follow the required naming conventions. ```text $2000_years $[main] @today victory ``` -------------------------------- ### Declare a variable in a Yarn script Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/commands/declare.md Example showing the declaration of a variable and its subsequent usage within a dialogue node. ```yarn <> --------------- title: Greeting --------------- Teacher: Welcome to the class, {$monicker}! === ``` -------------------------------- ### Implement a basic FlameGame Source: https://github.com/flame-engine/flame/blob/main/doc/flame/game.md Demonstrates creating a custom component and world, then initializing the game with GameWidget. ```dart import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flutter/widgets.dart'; /// A component that renders the crate sprite, with a 16 x 16 size. class MyCrate extends SpriteComponent { MyCrate() : super(size: Vector2.all(16)); @override Future onLoad() async { sprite = await Sprite.load('crate.png'); } } class MyWorld extends World { @override Future onLoad() async { await add(MyCrate()); } } void main() { final myGame = FlameGame(world: MyWorld()); runApp( GameWidget(game: myGame), ); } ``` -------------------------------- ### Load TextureAtlas with Automatic Package Detection Source: https://github.com/flame-engine/flame/blob/main/packages/flame_texturepacker/README.md The library automatically detects and handles package paths starting with 'packages/package_name/'. ```dart // Path: packages/my_assets_package/assets/images/heroes.atlas final atlas = await TexturePackerAtlas.load('packages/my_assets_package/assets/images/heroes.atlas'); ``` -------------------------------- ### Implement the deal() method Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/klondike/step5.md Handles card shuffling, movement animations, and stock pile initialization. Uses a callback mechanism to ensure all cards arrive before flipping the top cards. ```dart void deal() { assert(cards.length == 52, 'There are ${cards.length} cards: should be 52'); if (game.action != Action.sameDeal) { // New deal: change the Random Number Generator's seed. game.seed = Random().nextInt(KlondikeGame.maxInt); if (game.action == Action.changeDraw) { game.klondikeDraw = (game.klondikeDraw == 3) ? 1 : 3; } } // For the "Same deal" option, re-use the previous seed, else use a new one. cards.shuffle(Random(game.seed)); var cardToDeal = cards.length - 1; var nMovingCards = 0; for (var i = 0; i < 7; i++) { for (var j = i; j < 7; j++) { final card = cards[cardToDeal--]; card.doMove( tableauPiles[j].position, start: nMovingCards * 0.15, onComplete: () { tableauPiles[j].acquireCard(card); nMovingCards--; if (nMovingCards == 0) { var delayFactor = 0; for (final tableauPile in tableauPiles) { delayFactor++; tableauPile.flipTopCard(start: delayFactor * 0.15); } } }, ); nMovingCards++; } } for (var n = 0; n <= cardToDeal; n++) { stock.acquireCard(cards[n]); } } ``` -------------------------------- ### Use FlameSplashController for Customization Source: https://github.com/flame-engine/flame/blob/main/packages/flame_splash_screen/README.md Control animation durations and start behavior by managing a controller within a widget state. ```dart class SplashScreenGameState extends State { FlameSplashController controller; @override void initState() { super.initState(); controller = FlameSplashController( fadeInDuration: Duration(seconds: 1), fadeOutDuration: Duration(milliseconds: 250), waitDuration: Duration(seconds: 2), autoStart: false, ); } @override void dispose() { controller.dispose(); // dispose it when necessary super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: FlameSplashScreen( showBefore: (BuildContext context) { return Text("Before the logo"); }, showAfter: (BuildContext context) { return Text("After the logo"); }, theme: FlameSplashTheme.white, onFinish: (context) => Navigator.pushNamed(context, '/the-game-initial-screen'), controller: controller, ), ); } } ``` -------------------------------- ### Define Player Shooting Methods Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/space_shooter/step_4.md Placeholder methods for starting and stopping the shooting action within the Player class. ```dart class Player extends SpriteAnimationComponent with HasGameReference { // Rest of implementation omitted void startShooting() { // TODO } void stopShooting() { // TODO } } ``` -------------------------------- ### Initialize the game in main.dart Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/klondike/step2.md Entry point for the application that runs the KlondikeGame instance within a GameWidget. ```dart import 'package:flame/game.dart'; import 'package:flutter/widgets.dart'; import 'klondike_game.dart'; void main() { final game = KlondikeGame(); runApp(GameWidget(game: game)); } ``` -------------------------------- ### Build Custom Shaders with flame_3d Source: https://github.com/flame-engine/flame/blob/main/packages/flame_3d/README.md This command-line script helps bundle custom fragment and vertex shaders for use with flame_3d's custom materials. Ensure your shader files have matching names and are placed in a 'shaders' directory. ```bash dart pub run flame_3d:build_shaders ``` -------------------------------- ### Get Individual Sprite from SpriteSheet Source: https://github.com/flame-engine/flame/blob/main/doc/flame/rendering/images.md Retrieves a single Sprite from a SpriteSheet either by its unique ID or by its row and column. ```dart spriteSheet.getSpriteById(2); // by id ``` ```dart spriteSheet.getSprite(0, 0); // row, column ``` -------------------------------- ### Initialize Game Components Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/klondike/step2.md Instantiate game components like Stock, Waste, Foundation, and Pile with specific sizes and positions within the onLoad method. ```dart final stock = Stock() ..size = cardSize ..position = Vector2(cardGap, cardGap); final waste = Waste() ..size = cardSize ..position = Vector2(cardWidth + 2 * cardGap, cardGap); final foundations = List.generate( 4, (i) => Foundation() ..size = cardSize ..position = Vector2((i + 3) * (cardWidth + cardGap) + cardGap, cardGap), ); final piles = List.generate( 7, (i) => Pile() ..size = cardSize ..position = Vector2( cardGap + i * (cardWidth + cardGap), cardHeight + 2 * cardGap, ), ); ``` -------------------------------- ### Activate Melos Globally Source: https://github.com/flame-engine/flame/blob/main/CONTRIBUTING.md Installs the Melos tool globally, which is used for managing Flame project dependencies and running scripts. ```shell flutter pub global activate melos ``` -------------------------------- ### Build shaders Source: https://github.com/flame-engine/flame/blob/main/packages/flame_3d/CONTRIBUTING.md Executes the manual build script after modifying files in the shaders directory. ```sh dart bin/build_shaders.dart ``` -------------------------------- ### Integer part function examples Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/expressions/functions/numeric.md Use int(x) to truncate the fractional part of a number, rounding towards zero. ```yarn { int(0) } // 0 { int(0.3) } // 0 { int(5.0) } // 5 { int(5.001) } // 5 { int(5.999) } // 5 { int(-2.07) } // -2 ``` -------------------------------- ### Dialogue Example Using Declared Characters Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/commands/character.md A sample dialogue script demonstrating the usage of declared character aliases to represent speakers. ```yarn title: Alice_and_the_Cat --- Alice: But I don't want to go among mad people. Cat: Oh, you can't help that, we're all mad here. I'm mad. You're mad. Alice: How do you know I'm mad? Cat: You must be, or you wouldn't have come here. Alice: And how do you know that you're mad? Cat: To begin with, a dog's not mad. You grant that? Alice: I suppose so. Cat: Well then, you see a dog growls when it's angry, and wags its tail \ when it's pleased. Cat: Now, [i]I[/i] growl when I'm pleased, and wag my tail when I'm angry. \ Therefore, I'm mad. Alice: [i]I[/i] call it purring, not growling. Cat: Call it what you like. === ``` -------------------------------- ### Create Entity with Text using OxygenGame Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/oxygen/components.md Use this to create an entity with text using the OxygenGame helper. Requires TextInit with the desired string and optional TextPaintConfig. ```dart game.createEntity( position: // ... size: // ... )..add( TextInit( 'Your text', config: const TextPaintConfig(), ), ); ``` -------------------------------- ### Component Hot Reload Handling Source: https://github.com/flame-engine/flame/blob/main/doc/flame/components/components.md Example of overriding the onHotReload method to handle code changes during development. Ensure to call super.onHotReload(). ```dart class MyComponent extends Component { @override void onHotReload() { super.onHotReload(); // Re-read values that may have changed in source code. _cachedValue = _computeExpensiveValue(); } } ``` -------------------------------- ### Render a DocumentRoot with TextElementComponent Source: https://github.com/flame-engine/flame/blob/main/doc/flame/rendering/text_rendering.md Create a structured document with block elements and render it using a TextElementComponent. ```dart final document = DocumentRoot([ HeaderNode.simple('1984', level: 1), ParagraphNode.simple( 'Anything could be true. The so-called laws of nature were nonsense.', ), // ... ]); final element = TextElementComponent.fromDocument( document: document, position: Vector2(100, 50), size: Vector2(400, 200), ); ``` -------------------------------- ### Create a Weapon BodyComponent Source: https://github.com/flame-engine/flame/blob/main/doc/bridge_packages/flame_forge2d/forge2d.md Example of extending BodyComponent to create a custom physics body for a weapon. Override `onLoad` for initialization logic. ```dart class Weapon extends BodyComponent { @override void onLoad() { ... } } ``` -------------------------------- ### SvgComponent initialization Source: https://github.com/flame-engine/flame/blob/main/doc/flame/components/utility_components.md Loads and renders an SVG file using the flame_svg package. ```dart @override Future onLoad() async { final svg = await Svg.load('android.svg'); final android = SvgComponent.fromSvg( svg, position: Vector2.all(100), size: Vector2.all(100), ); } ``` -------------------------------- ### Marking Text with Cursed Style Source: https://github.com/flame-engine/flame/blob/main/doc/other_modules/jenny/language/markup.md Example of using markup tags to apply specific styles or meanings to words, like 'cursed' or 'emphasis'. ```yarn title: Scene117_Harry_MrMalfoy --- Harry: I'm not afraid of [cursed]Voldemort[/cursed]! MrMalfoy: You must be really brave... or really [i]stupid[/i]? === ``` -------------------------------- ### Initialize Deck and Stock Pile Source: https://github.com/flame-engine/flame/blob/main/doc/tutorials/klondike/step4.md Creates a full deck of 52 cards and adds them to the game world, then acquires each card into the stock pile. This is typically added at the end of the onLoad method. ```dart final cards = [ for (var rank = 1; rank <= 13; rank++) for (var suit = 0; suit < 4; suit++) Card(rank, suit) ]; world.addAll(cards); cards.forEach(stock.acquireCard); ``` -------------------------------- ### Bootstrap Project Dependencies with Melos Source: https://github.com/flame-engine/flame/blob/main/CONTRIBUTING.md Links local project dependencies using Melos. This command should be run once after cloning the repository and sets up the project for local development, eliminating the need for manual dependency overrides. ```shell melos bootstrap ```