### Create Basic Game with BonfireWidget in Dart Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Initializes and displays a Bonfire game, including map loading from Tiled, player configuration, joystick controls, and camera setup. This example demonstrates the core structure for a Bonfire game. ```dart import 'package:bonfire/bonfire.dart'; import 'package:flutter/material.dart'; class MyGame extends StatelessWidget { @override Widget build(BuildContext context) { const tileSize = 16.0; return BonfireWidget( // Load map from Tiled JSON file map: WorldMapByTiled( WorldMapReader.fromAsset('tiled/map.tmj'), objectsBuilder: { 'enemy': (properties) => SimpleEnemy( position: properties.position, size: Vector2.all(32), speed: 50, ), 'chest': (properties) => GameDecoration.withSprite( sprite: Sprite.load('chest.png'), position: properties.position, size: Vector2.all(32), ), }, ), // Configure player player: SimplePlayer( position: Vector2(tileSize * 5, tileSize * 5), size: Vector2.all(32), animation: SimpleDirectionAnimation( idleRight: SpriteAnimation.load('player_idle_right.png', SpriteAnimationData.sequenced(amount: 4, stepTime: 0.1, textureSize: Vector2(32, 32))), runRight: SpriteAnimation.load('player_run_right.png', SpriteAnimationData.sequenced(amount: 8, stepTime: 0.1, textureSize: Vector2(32, 32))), ), life: 100, speed: 100, ), // Add joystick controls playerControllers: [ Joystick( directional: JoystickDirectional( color: Colors.blueGrey, size: 100, ), actions: [ JoystickAction( actionId: 'attack', color: Colors.red, size: 60, margin: EdgeInsets.only(bottom: 50, right: 50), ), ], ), ], // Camera configuration cameraConfig: CameraConfig( zoom: getZoomFromMaxVisibleTile(context, tileSize, 20), speed: 5, startFollowPlayer: true, ), // Background color backgroundColor: Color(0xff20a0b4), // Debug options debugMode: false, showCollisionArea: false, // Game ready callback onReady: (game) { print('Game loaded successfully'); }, ); } } ``` -------------------------------- ### Bonfire Dart: Create and Use Custom AI Behaviors Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Demonstrates how to create a custom AI behavior by extending the `Behavior` class. The `CustomBehavior` class allows defining a custom action and an optional condition to control its execution. This is shown in the `SmartEnemy` example, where the enemy retreats when low on health. ```dart import 'package:bonfire/bonfire.dart'; // Example 4: Custom behavior class CustomBehavior extends Behavior { final Function(GameComponent) action; final bool Function(GameComponent)? condition; CustomBehavior({ required this.action, this.condition, dynamic id, }) : super(id: id); @override bool runAction(double dt, GameComponent comp, BonfireGameInterface game) { if (condition != null && !condition!(comp)) { return false; // Stop behavior } action(comp); return true; // Continue behavior } } // Usage of custom behavior class SmartEnemy extends SimpleEnemy with UseBehavior { SmartEnemy({required Vector2 position}) : super(position: position, size: Vector2.all(32), speed: 50); @override Future onLoad() { addBehavior( CustomBehavior( action: (comp) { final player = gameRef.player; if (player != null && life < maxLife * 0.3) { // Retreat when low health final escapeDirection = (position - player.position).normalized(); moveFromDirection(escapeDirection); } }, condition: (comp) => !isDead, ), ); return super.onLoad(); } } ``` -------------------------------- ### Create Custom Player with Animations and Collision (Dart) Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Defines a 'HumanPlayer' class extending 'SimplePlayer' with directional animations and block movement collision. It includes setup for idle, run, and attack animations, joystick input handling for attacks, and collision hitbox definition. The player also has a health system and a death callback. ```dart import 'package:bonfire/bonfire.dart'; class HumanPlayer extends SimplePlayer with BlockMovementCollision { HumanPlayer({required Vector2 position}) : super( position: position, size: Vector2.all(32), life: 100, speed: 80, initDirection: Direction.down, animation: SimpleDirectionAnimation( idleRight: SpriteAnimation.load( 'player/idle_right.png', SpriteAnimationData.sequenced( amount: 4, stepTime: 0.15, textureSize: Vector2.all(32), ), ), runRight: SpriteAnimation.load( 'player/run_right.png', SpriteAnimationData.sequenced( amount: 8, stepTime: 0.1, textureSize: Vector2.all(32), ), ), idleDown: SpriteAnimation.load( 'player/idle_down.png', SpriteAnimationData.sequenced( amount: 4, stepTime: 0.15, textureSize: Vector2.all(32), ), ), runDown: SpriteAnimation.load( 'player/run_down.png', SpriteAnimationData.sequenced( amount: 8, stepTime: 0.1, textureSize: Vector2.all(32), ), ), others: { 'attack_right': SpriteAnimation.load( 'player/attack_right.png', SpriteAnimationData.sequenced( amount: 6, stepTime: 0.08, textureSize: Vector2.all(32), ), ), }, ), ); @override void onJoystickAction(JoystickActionEvent event) { if (event.id == 'attack' && event.event == ActionEvent.DOWN) { _executeAttack(); } super.onJoystickAction(event); } void _executeAttack() { // Play attack animation animation?.playOnceOther('attack_right', onFinish: () { print('Attack animation finished'); }); // Create attack hitbox add( DamageHitbox( damage: 20, direction: lastDirection, size: Vector2(32, 32), position: position + lastDirectionVector * 16, attackFrom: AttackOriginEnum.PLAYER_OR_ALLY, )..removeFromParent(), ); } @override Future onLoad() { // Add collision hitbox add(RectangleHitbox( size: Vector2(16, 16), position: Vector2(8, 16), )); return super.onLoad(); } @override void onDie() { removeFromParent(); print('Player died!'); super.onDie(); } } ``` -------------------------------- ### Implement Sensor Collision in Dart Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Demonstrates implementing `Sensor` for interactive game objects that trigger events upon contact. The `InteractiveDoor` example shows how to detect collisions with a `Player` and change the object's state and appearance, in this case, opening the door. It utilizes `RectangleHitbox` for collision detection. ```dart import 'package:bonfire/bonfire.dart'; // Example 2: Interactive object with sensor collision class InteractiveDoor extends GameDecoration with Sensor { bool isOpen = false; InteractiveDoor({required Vector2 position}) : super.withSprite( sprite: Sprite.load('door_closed.png'), position: position, size: Vector2.all(32), ); @override Future onLoad() { add(RectangleHitbox(size: size)); return super.onLoad(); } @override void onContact(GameComponent component) { if (component is Player && !isOpen) { _openDoor(); } } void _openDoor() { isOpen = true; sprite = Sprite.load('door_open.png'); } } ``` -------------------------------- ### Implement BlockMovementCollision in Dart Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Shows how to implement `BlockMovementCollision` for game objects like walls and obstacles. This ensures that player characters and other movable entities cannot pass through these objects. The example includes creating a `Wall` class with a `RectangleHitbox` and a `CircularObstacle` with a `CircleHitbox`. ```dart import 'package:bonfire/bonfire.dart'; // Example 1: Decoration with collision (walls, obstacles) class Wall extends GameDecoration with BlockMovementCollision { Wall({required Vector2 position}) : super.withSprite( sprite: Sprite.load('wall.png'), position: position, size: Vector2.all(32), ); @override Future onLoad() { // Add rectangular collision hitbox add(RectangleHitbox(size: size)); return super.onLoad(); } } // Example 4: Polygon collision for irregular shapes class IrregularObstacle extends GameDecoration with BlockMovementCollision { IrregularObstacle({required Vector2 position}) : super.withSprite( sprite: Sprite.load('obstacle.png'), position: position, size: Vector2.all(64), ); @override Future onLoad() { // Custom polygon shape add(PolygonHitbox([ Vector2(10, 0), Vector2(54, 0), Vector2(64, 32), Vector2(32, 64), Vector2(0, 32), ])); return super.onLoad(); } } // Example 3: Custom collision shape class CircularObstacle extends GameDecoration with BlockMovementCollision { CircularObstacle({required Vector2 position}) : super.withSprite( sprite: Sprite.load('rock.png'), position: position, size: Vector2.all(48), ); @override Future onLoad() { // Add circular collision hitbox add(CircleHitbox( radius: 24, position: Vector2.all(24), )); return super.onLoad(); } } ``` -------------------------------- ### Load Tiled Maps with Dynamic Object Spawning in Dart Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Demonstrates loading a Tiled JSON map using `WorldMapByTiled` and `WorldMapReader`. It includes configuring tile size, handling errors, and defining custom builders for dynamic object spawning from Tiled properties, such as enemies, chests, NPCs, and doors. It also shows an alternative method for loading maps from a network URL. ```dart import 'package:bonfire/bonfire.dart'; class GameMapLoader { static WorldMapByTiled createMap() { return WorldMapByTiled( // Load from assets WorldMapReader.fromAsset('tiled/dungeon.tmj'), // Force specific tile size (optional) forceTileSize: Vector2.all(16), // Handle map loading errors onError: (error) { print('Map loading error: $error'); }, // Define builders for custom objects in Tiled objectsBuilder: { // Spawn enemies at marked locations 'goblin': (properties) => MeleeEnemy( position: properties.position, ), // Spawn treasure chests 'chest': (properties) { final isOpen = properties.get('isOpen') ?? false; return GameDecoration.withSprite( sprite: Sprite.load(isOpen ? 'chest_open.png' : 'chest_closed.png'), position: properties.position, size: Vector2.all(32), ); }, // Spawn NPCs with custom properties 'npc': (properties) { final npcName = properties.get('name') ?? 'Unknown'; final dialogue = properties.get('dialogue') ?? 'Hello!'; return SimpleNpc( position: properties.position, size: Vector2.all(32), // ... NPC configuration ); }, // Spawn interactive doors 'door': (properties) { final targetMap = properties.get('targetMap'); final targetX = properties.get('targetX') ?? 0.0; final targetY = properties.get('targetY') ?? 0.0; return GameDecoration.withCollision( sprite: Sprite.load('door.png'), position: properties.position, size: Vector2.all(32), ); }, }, ); } // Alternative: Load from network static WorldMapByTiled createMapFromNetwork(String url) { return WorldMapByTiled( WorldMapReader.fromNetwork(Uri.parse(url)), onError: (error) => print('Network error: $error'), ); } } ``` -------------------------------- ### Integrate BonfireWidget with Game Interface in Dart Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Demonstrates how to use the `BonfireWidget` to display a game with a custom interface. It sets up the game map, player, and the custom `GameInterface`. Dependencies include `bonfire` and `flutter/widgets`. It takes game assets and player configuration as input. ```dart // Usage in BonfireWidget class GameWithUI extends StatelessWidget { @override Widget build(BuildContext context) { return BonfireWidget( map: WorldMapByTiled( WorldMapReader.fromAsset('map.tmj'), ), player: SimplePlayer( position: Vector2(100, 100), size: Vector2.all(32), ), interface: GameInterface(), playerControllers: [ Joystick( directional: JoystickDirectional(), ), ], ); } } ``` -------------------------------- ### Bonfire Dart: Player with Light Source Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Demonstrates how to create a player character with a built-in light source using `SimplePlayer` and `LightingConfig`. This allows the player to emit light, influencing the surrounding environment. ```dart import 'package:bonfire/bonfire.dart'; import 'package:flutter/material.dart'; // Example 1: Player with light source class PlayerWithLight extends SimplePlayer { PlayerWithLight({required Vector2 position}) : super( position: position, size: Vector2.all(32), life: 100, speed: 80, // Add lighting configuration lightingConfig: LightingConfig( radius: 150, color: Colors.yellow.withOpacity(0.3), withPulse: false, blurBorder: 50, type: LightingType.circle, ), ); } ``` -------------------------------- ### Assemble Complete Game Interface in Dart Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Combines multiple interface components (health bar, coin counter, mini-map, text) into a single `GameInterface` class. It inherits from `GameInterface` and adds instances of the previously defined components. Requires `bonfire` and `flutter/material`. ```dart // Example 4: Complete game interface class GameInterface extends GameInterface { @override Future onLoad() { add(PlayerHealthBar()); add(CoinCounter()); add(MiniMap()); add(TextInterfaceComponent( text: 'Level 1', position: Vector2(20, 100), textConfig: TextStyle( color: Colors.white, fontSize: 18, ), )); return super.onLoad(); } } ``` -------------------------------- ### Create Coin Counter Interface Component in Dart Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Implements a coin counter display using `InterfaceComponent`. It increments a coin count and renders it using `TextPaint`. Requires `bonfire` and `flutter/material`. Input is triggered by `addCoin()` and output is the displayed coin count. ```dart // Example 2: Coin counter interface class CoinCounter extends InterfaceComponent with GameComponent { int coins = 0; late TextPaint _textPaint; CoinCounter() : super( id: 'coin_counter', position: Vector2(20, 60), size: Vector2(150, 40), ); @override Future onLoad() { _textPaint = TextPaint( style: TextStyle( color: Colors.yellow, fontSize: 24, fontWeight: FontWeight.bold, ), ); return super.onLoad(); } void addCoin() { coins++; } @override void render(Canvas canvas) { _textPaint.render( canvas, 'Coins: $coins', Vector2.zero(), ); super.render(canvas); } } ``` -------------------------------- ### Develop Mini-Map Interface Component in Dart Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Develops a mini-map using `InterfaceComponent` to display player and enemy positions. It scales world coordinates to the mini-map's size. Dependencies include `bonfire` and `flutter/material`. It takes game object positions as input and renders circles representing entities. ```dart // Example 3: Mini-map interface class MiniMap extends InterfaceComponent { MiniMap() : super( id: 'minimap', position: Vector2(10, 10), size: Vector2(150, 150), ); @override void render(Canvas canvas) { // Background canvas.drawRect( Rect.fromLTWH(0, 0, size.x, size.y), Paint()..color = Colors.black.withOpacity(0.7), ); // Draw player position final player = gameRef.player; if (player != null) { final mapSize = gameRef.map.size; final scale = size.x / mapSize.x; final playerPos = player.position * scale; canvas.drawCircle( Offset(playerPos.x, playerPos.y), 3, Paint()..color = Colors.blue, ); } // Draw enemies for (final enemy in gameRef.livingEnemies()) { final mapSize = gameRef.map.size; final scale = size.x / mapSize.x; final enemyPos = enemy.position * scale; canvas.drawCircle( Offset(enemyPos.x, enemyPos.y), 2, Paint()..color = Colors.red, ); } } } ``` -------------------------------- ### Bonfire Dart: Directional Spotlight Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Illustrates creating a directional spotlight effect using `GameDecoration` and `LightingConfig` with `useComponentAngle: true`. This allows light to follow the orientation of the game object. ```dart import 'package:bonfire/bonfire.dart'; import 'package:flutter/material.dart'; // Example 3: Directional light (spotlight) class Spotlight extends GameDecoration { Spotlight({required Vector2 position, required double angle}) : super.withSprite( sprite: Sprite.load('spotlight.png'), position: position, size: Vector2.all(32), angle: angle, lightingConfig: LightingConfig( radius: 200, color: Colors.white.withOpacity(0.5), useComponentAngle: true, type: LightingType.circle, ), ); } ``` -------------------------------- ### Bonfire Dart: Configure Global Dark Lighting Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Demonstrates how to set a global ambient lighting color for the entire game scene using `BonfireWidget`'s `lightingColorGame` property. This is useful for creating dark or atmospheric environments. ```dart import 'package:bonfire/bonfire.dart'; import 'package:flutter/material.dart'; // Example 4: Configure global lighting class DarkDungeonGame extends StatelessWidget { @override Widget build(BuildContext context) { return BonfireWidget( map: WorldMapByTiled( WorldMapReader.fromAsset('dungeon.tmj'), ), player: PlayerWithLight(position: Vector2(100, 100)), // Set dark ambient lighting lightingColorGame: Colors.black.withOpacity(0.8), // ... other configurations ); } } ``` -------------------------------- ### Bonfire: Basic Camera Following Player Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Configures the camera to automatically follow the player with smooth movement and adjustable zoom levels. It also supports setting camera boundaries to confine movement within the map area. ```dart import 'package:bonfire/bonfire.dart'; import 'package:flutter/material.dart'; // Example 1: Basic camera following player class GameWithCamera extends StatelessWidget { @override Widget build(BuildContext context) { return BonfireWidget( map: WorldMapByTiled( WorldMapReader.fromAsset('map.tmj'), ), player: SimplePlayer( position: Vector2(100, 100), size: Vector2.all(32), ), cameraConfig: CameraConfig( // Camera follows player automatically startFollowPlayer: true, // Smooth camera movement speed: 3, // Zoom level (calculated for 20 tiles visible) zoom: getZoomFromMaxVisibleTile(context, 16, 20), // Camera boundaries (optional) moveOnlyMapArea: true, // Initial position (if not following player) initPosition: Vector2(200, 200), ), ); } } ``` -------------------------------- ### Bonfire: Dynamic Camera Control Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Provides extension methods for BonfireGame to dynamically control the camera, allowing it to focus on specific enemies, return to the player, move to a position, and adjust zoom levels programmatically. ```dart // Example 2: Dynamic camera control extension CameraControl on BonfireGame { void focusOnEnemy(Enemy enemy) { camera.follow(enemy, snap: false); } void returnToPlayer() { if (player != null) { camera.follow(player!, snap: false); } } void moveToPosition(Vector2 position) { camera.moveToPosition(position); } void zoomIn() { camera.zoom = camera.zoom * 1.2; } void zoomOut() { camera.zoom = camera.zoom * 0.8; } } ``` -------------------------------- ### Bonfire Combo Attack System Implementation Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Implements a combo attack system for a player extending `SimplePlayer` in Bonfire. This system tracks the number of consecutive attacks within a time window and executes different strength attacks based on the combo count. It manages combo state using `_comboCount` and `_lastAttackTime` with a defined `comboWindow`. ```dart import 'package:bonfire/bonfire.dart'; // Example 4: Combo attack system class ComboPlayer extends SimplePlayer { int _comboCount = 0; double _lastAttackTime = 0; static const comboWindow = 1.0; // seconds void performComboAttack(double currentTime) { if (currentTime - _lastAttackTime > comboWindow) { _comboCount = 0; } _comboCount++; _lastAttackTime = currentTime; switch (_comboCount) { case 1: _lightAttack(); break; case 2: _mediumAttack(); break; case 3: _heavyAttack(); _comboCount = 0; break; } } void _lightAttack() { simpleAttackMelee(damage: 10, size: size * 1.2); } void _mediumAttack() { simpleAttackMelee(damage: 20, size: size * 1.5); } void _heavyAttack() { simpleAttackMelee(damage: 40, size: size * 2.0, withPush: true); } } ``` -------------------------------- ### Bonfire Ranged Projectile Attack Implementation Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Demonstrates how to implement a ranged projectile attack, such as shooting an arrow, using Bonfire. This involves creating a `FlyingAttackGameObject` with specified properties like speed, damage, sprite, and collision. The projectile is added to the game world and can trigger actions upon destruction. ```dart import 'package:bonfire/bonfire.dart'; // Example 2: Ranged projectile attack extension PlayerRangedAttack on SimplePlayer { void shootArrow() { final arrow = FlyingAttackGameObject( position: center, direction: lastDirectionVector, size: Vector2(16, 8), damage: 15, speed: 200, attackFrom: AttackOriginEnum.PLAYER_OR_ALLY, sprite: Sprite.load('arrow.png'), collision: RectangleHitbox(size: Vector2(16, 8)), onDestroy: () { print('Arrow destroyed'); }, ); gameRef.add(arrow); } } ``` -------------------------------- ### Bonfire: Gesture-Based Camera Movement Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Enables camera control through user gestures, including drag-to-move and pinch-to-zoom. This allows for interactive camera manipulation within the game world. ```dart // Example 5: Gesture-based camera movement class GameWithGestureCamera extends StatelessWidget { @override Widget build(BuildContext context) { return BonfireWidget( map: WorldMapByTiled( WorldMapReader.fromAsset('map.tmj'), ), cameraConfig: CameraConfig( startFollowPlayer: false, zoom: 1.0, ), components: [ // Enable camera movement with gestures MoveCameraUsingGestures(), ], onReady: (game) { // Enable pinch to zoom game.camera.viewport.add( UpdateCameraByPinchGesture(), ); }, ); } } ``` -------------------------------- ### Bonfire Dart: Torch with Pulsing Light Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Shows how to create a decorative torch that emits a pulsing light effect using `GameDecoration` and `LightingConfig` with pulse properties enabled. This adds dynamic visual flair to the game world. ```dart import 'package:bonfire/bonfire.dart'; import 'package:flutter/material.dart'; // Example 2: Torch with pulsing light class Torch extends GameDecoration { Torch({required Vector2 position}) : super.withAnimation( animation: SpriteAnimation.load( 'torch.png', SpriteAnimationData.sequenced( amount: 8, stepTime: 0.1, textureSize: Vector2.all(16), ), ), position: position, size: Vector2.all(16), // Pulsing light effect lightingConfig: LightingConfig( radius: 100, color: Colors.orange.withOpacity(0.4), withPulse: true, pulseVariation: 0.2, pulseSpeed: 0.5, pulseCurve: Curves.easeInOut, blurBorder: 60, ), ); } ``` -------------------------------- ### Implement Player Health Bar Interface in Dart Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Creates a visual health bar for the player using `InterfaceComponent`. It dynamically updates based on the player's current and maximum life. Dependencies include `bonfire` and `flutter/material`. It takes player life as input and renders a colored bar. ```dart import 'package:bonfire/bonfire.dart'; import 'package:flutter/material.dart'; // Example 1: Health bar interface class PlayerHealthBar extends InterfaceComponent { double _currentLife = 100; double _maxLife = 100; PlayerHealthBar() : super( id: 'health_bar', position: Vector2(20, 20), size: Vector2(200, 30), ); @override void update(double dt) { final player = gameRef.player; if (player is Attackable) { _currentLife = player.life; _maxLife = player.maxLife; } super.update(dt); } @override void render(Canvas canvas) { // Background canvas.drawRect( Rect.fromLTWH(0, 0, size.x, size.y), Paint()..color = Colors.black.withOpacity(0.5), ); // Health fill final healthWidth = (size.x - 4) * (_currentLife / _maxLife); canvas.drawRect( Rect.fromLTWH(2, 2, healthWidth, size.y - 4), Paint()..color = Colors.red, ); // Border canvas.drawRect( Rect.fromLTWH(0, 0, size.x, size.y), Paint() ..color = Colors.white ..style = PaintingStyle.stroke ..strokeWidth = 2, ); } } ``` -------------------------------- ### Bonfire: Fixed Resolution Viewport Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Sets up a BonfireWidget with a fixed resolution for the camera viewport, ensuring pixel-perfect rendering regardless of the device's screen size. This is useful for retro-style games. ```dart // Example 3: Fixed resolution viewport class PixelPerfectGame extends StatelessWidget { @override Widget build(BuildContext context) { return BonfireWidget( map: WorldMapByTiled( WorldMapReader.fromAsset('map.tmj'), ), player: SimplePlayer( position: Vector2(100, 100), size: Vector2.all(16), ), cameraConfig: CameraConfig( // Fixed resolution for pixel-perfect rendering resolution: Vector2(320, 240), startFollowPlayer: true, speed: 5, ), ); } } ``` -------------------------------- ### Implement Melee Enemy with AI and Attack - Dart Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt This Dart code defines a `MeleeEnemy` class that extends `SimpleEnemy` and implements `BlockMovementCollision`. It includes AI logic for detecting and moving towards the player, performing melee attacks with animations, and handling received damage and death. ```dart import 'package:bonfire/bonfire.dart'; import 'package:flutter/material.dart'; class MeleeEnemy extends SimpleEnemy with BlockMovementCollision { bool _attackInProgress = false; MeleeEnemy({required Vector2 position}) : super( position: position, size: Vector2.all(24), speed: 50, life: 50, initDirection: Direction.down, animation: SimpleDirectionAnimation( idleRight: SpriteAnimation.load( 'enemies/orc_idle_right.png', SpriteAnimationData.sequenced( amount: 4, stepTime: 0.2, textureSize: Vector2.all(24), ), ), runRight: SpriteAnimation.load( 'enemies/orc_run_right.png', SpriteAnimationData.sequenced( amount: 6, stepTime: 0.1, textureSize: Vector2.all(24), ), ), others: { 'attack_right': SpriteAnimation.load( 'enemies/orc_attack_right.png', SpriteAnimationData.sequenced( amount: 5, stepTime: 0.1, textureSize: Vector2.all(24), ), ), }, ), ); @override void update(double dt) { // AI behavior: see player and move towards them seeAndMoveToPlayer( closePlayer: (player) { // Highlight enemy when near player animation?.showStroke(Colors.red, 2); // Attack on interval if (checkInterval('attack', 800, dt) && !_attackInProgress) { _performAttack(); } }, notObserved: () { animation?.hideStroke(); return true; }, radiusVision: 100, ); super.update(dt); } void _performAttack() { _attackInProgress = true; // Play attack animation based on direction animation?.playOnceOther( 'attack_${lastDirection.name}', onFinish: () { _attackInProgress = false; }, ); // Deal damage to player if in range simpleAttackRange( direction: lastDirection, size: size * 1.5, damage: 10, attackFrom: AttackOriginEnum.ENEMY, ); } @override Future onLoad() { // Add collision hitbox (smaller than sprite) add(RectangleHitbox( size: size / 2, position: size / 4, )); return super.onLoad(); } @override void onReceiveDamage( AttackOriginEnum attacker, double damage, dynamic identify, ) { // Show damage text gameRef.add( TextDamageComponent( damage.toInt().toString(), position: position, config: TextStyle(fontSize: 10, color: Colors.white), ), ); super.onReceiveDamage(attacker, damage, identify); } @override void onDie() { // Play death animation and remove removeFromParent(); super.onDie(); } } ``` -------------------------------- ### Bonfire Dart: Implement Guard and Chase Behavior for Enemies Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Creates a guard behavior for an enemy that detects and chases the player, then attacks when close. It uses `BCanSeeType` to check for player visibility and `BSeeAndMoveToTarget` to pursue. If the player is lost, it returns to the guard position using `BMoveToPosition`. ```dart import 'package:bonfire/bonfire.dart'; // Example 2: Guard behavior (see player and chase) class GuardEnemy extends SimpleEnemy with UseBehavior { Vector2 guardPosition; GuardEnemy({required Vector2 position}) : guardPosition = position, super( position: position, size: Vector2.all(32), speed: 60, life: 80, ); @override Future onLoad() { addBehavior(BList([ // Check if can see player BCanSeeType( radiusVision: 150, onSee: (player) { // Chase player addBehavior(BSeeAndMoveToTarget( target: player, closeTarget: (target) { // Attack when close simpleAttackMelee(damage: 15, size: size * 1.5); }, )); }, onNotSee: () { // Return to guard position addBehavior(BMoveToPosition(guardPosition)); }, ), // Wait interval BInterval(Duration(seconds: 1)), ], loop: true)); return super.onLoad(); } } ``` -------------------------------- ### Bonfire Dart: Implement Patrol Behavior for Enemies Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Defines a patrol behavior for an enemy using `SimpleEnemy` and `UseBehavior`. It utilizes `BList` to chain multiple `BMoveToPosition` behaviors in a loop, allowing the enemy to move between predefined points. ```dart import 'package:bonfire/bonfire.dart'; // Example 1: Patrol behavior class PatrolEnemy extends SimpleEnemy with UseBehavior { PatrolEnemy({required Vector2 position}) : super( position: position, size: Vector2.all(32), speed: 40, life: 50, ); @override Future onLoad() { // Define patrol points final patrolPoints = [ position, position + Vector2(100, 0), position + Vector2(100, 100), position + Vector2(0, 100), ]; // Set up patrol behavior addBehavior(BList([ for (var point in patrolPoints) BMoveToPosition(point, onFinish: () { print('Reached patrol point: $point'); }), ], loop: true)); return super.onLoad(); } } ``` -------------------------------- ### Bonfire Melee Attack Implementation Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Implements a basic melee attack for a SimplePlayer in Bonfire. This involves playing an attack animation and creating a directional hitbox to deal damage. It uses the `simpleAttackMelee` method and `AttackOriginEnum.PLAYER_OR_ALLY`. ```dart import 'package:bonfire/bonfire.dart'; // Example 1: Melee attack with directional hitbox extension PlayerMeleeAttack on SimplePlayer { void executeMeleeAttack() { // Play attack animation animation?.playOnceOther('attack', onFinish: () { print('Attack complete'); }); // Create damage hitbox in front of player simpleAttackMelee( damage: 25, size: size * 1.5, direction: lastDirection, attackFrom: AttackOriginEnum.PLAYER_OR_ALLY, withPush: true, ); } } ``` -------------------------------- ### Bonfire Dart: Implement Random Movement Behavior for NPCs Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Implements a wandering behavior for an NPC using `SimpleNpc` and `UseBehavior`. It employs `BRandomMovement` to move the NPC within a specified distance range and `BInterval` to introduce pauses between movements, creating a natural wandering effect. ```dart import 'package:bonfire/bonfire.dart'; // Example 3: Random movement behavior class WanderingNPC extends SimpleNpc with UseBehavior { WanderingNPC({required Vector2 position}) : super( position: position, size: Vector2.all(32), speed: 30, ); @override Future onLoad() { addBehavior(BList([ BRandomMovement( minDistance: 50, maxDistance: 150, speed: 30, ), BInterval(Duration(seconds: 2)), ], loop: true)); return super.onLoad(); } } ``` -------------------------------- ### Bonfire: Camera Shake Effect Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Implements camera shake functionality within Bonfire using extension methods. It allows triggering shakes with adjustable intensity and duration for events like explosions or hits. ```dart // Example 4: Camera shake effect extension CameraShake on BonfireGame { void shake({double intensity = 10, Duration? duration}) { camera.shake( intensity: intensity, duration: duration ?? Duration(milliseconds: 300), ); } void onExplosion() { shake(intensity: 15, duration: Duration(milliseconds: 500)); } void onHit() { shake(intensity: 5, duration: Duration(milliseconds: 200)); } } ``` -------------------------------- ### Bonfire Area of Effect (AoE) Attack Implementation Source: https://context7.com/rafaelbarbosatec/bonfire/llms.txt Details the implementation of an Area of Effect (AoE) attack, like a fireball explosion, in Bonfire. This involves launching a projectile that, upon destruction at a target position, deals damage to nearby enemies and spawns a visual explosion effect. It utilizes `FlyingAttackGameObject` and `AnimatedGameObject`. ```dart import 'package:bonfire/bonfire.dart'; // Example 3: Area of effect attack extension PlayerAoeAttack on SimplePlayer { void castFireball() { final targetPosition = position + lastDirectionVector * 100; // Create projectile final fireball = FlyingAttackGameObject( position: center, direction: lastDirectionVector, size: Vector2.all(32), damage: 0, // No damage on flight speed: 150, attackFrom: AttackOriginEnum.PLAYER_OR_ALLY, sprite: Sprite.load('fireball.png'), collision: CircleHitbox(radius: 16), onDestroy: () { _explode(targetPosition); }, ); gameRef.add(fireball); } void _explode(Vector2 position) { // Area damage gameRef.attackables().forEach((enemy) { if (enemy.position.distanceTo(position) < 80) { enemy.handleAttack( AttackOriginEnum.PLAYER_OR_ALLY, 40, 'fireball_explosion', ); } }); // Visual effect gameRef.add( AnimatedGameObject( position: position - Vector2.all(40), size: Vector2.all(80), animation: SpriteAnimation.load( 'explosion.png', SpriteAnimationData.sequenced( amount: 8, stepTime: 0.08, textureSize: Vector2.all(64), loop: false, ), ), )..removeFromParent(), ); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.