diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 92638a8be..b87a8c29c 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,8 +1,9 @@ name: Publish plugin on: - release: - types: [published] + push: + tags: + - 'v[0-9]+.[0-9]+.[0-9]+*' jobs: publish: diff --git a/.github/workflows/unit.yml b/.github/workflows/unit.yml index e86f968b4..c21f9d8ef 100644 --- a/.github/workflows/unit.yml +++ b/.github/workflows/unit.yml @@ -1,29 +1,34 @@ -name: unit-tests +name: Code Quality + on: push: branches: - - master + - main pull_request: types: [opened,ready_for_review,synchronize] - + jobs: - test-analyze: - name: Lint and Tests - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [macOS-12] - if: github.event.pull_request.draft == false + format-and-fix: + if: ${{ !github.event.pull_request.draft }} + runs-on: ubuntu-latest steps: - - name: Checkout code - uses: actions/checkout@v3 - - name: Intall dart - uses: dart-lang/setup-dart@v1 - - name: Setup Flutter - uses: subosito/flutter-action@v2 - with: - channel: 'stable' - cache: true - - run: flutter pub get - - run: flutter analyze - - run: dart format --output=none --set-exit-if-changed . + - name: Checkout + uses: actions/checkout@v2 + + - name: Intall dart + uses: dart-lang/setup-dart@v1 + + - name: Setup flutter + uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + + - name: Get packages + run: flutter pub get + + - name: Check format errors + run: dart format --output=none --set-exit-if-changed . + + # - name: Check lint errors + # run: flutter analyze . \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f36b73c8..f13d8921f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# 3.12.5 +- Update `a_star_algorithm`. +- InitialMapZoomFitEnum improvements + +# 3.12.4 +- Switched to declarative mode to apply Grandle plugins + # 3.12.3 - `RandomMovement` improvements diff --git a/analysis_options.yaml b/analysis_options.yaml index 61b6c4de1..7b45d876b 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,29 +1,14 @@ -# This file configures the analyzer, which statically analyzes Dart code to -# check for errors, warnings, and lints. -# -# The issues identified by the analyzer are surfaced in the UI of Dart-enabled -# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be -# invoked from the command line by running `flutter analyze`. +include: package:flame_lint/analysis_options.yaml -# The following line activates a set of recommended lints for Flutter apps, -# packages, and plugins designed to encourage good coding practices. -include: package:flutter_lints/flutter.yaml - -linter: - # The lint rules applied to this project can be customized in the - # section below to disable rules from the `package:flutter_lints/flutter.yaml` - # included above or to enable additional rules. A list of all available lints - # and their documentation is published at - # https://dart-lang.github.io/linter/lints/index.html. - # - # Instead of disabling a lint rule for the entire project in the - # section below, it can also be suppressed for a single line of code - # or a specific dart file by using the `// ignore: name_of_lint` and - # `// ignore_for_file: name_of_lint` syntax on the line or in the file - # producing the lint. - rules: - # avoid_print: false # Uncomment to disable the `avoid_print` rule - # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options +analyzer: + errors: + avoid_bool_literals_in_conditional_expressions: ignore + avoid_catches_without_on_clauses: ignore + avoid_positional_boolean_parameters: ignore + comment_references: ignore + lines_longer_than_80_chars: ignore + type_literal_in_constant_pattern: ignore + use_if_null_to_convert_nulls_to_bools: ignore + use_setters_to_change_properties: ignore + exclude: + - 'example/**' \ No newline at end of file diff --git a/example/.metadata b/example/.metadata index 72aedebfa..714755531 100644 --- a/example/.metadata +++ b/example/.metadata @@ -4,7 +4,7 @@ # This file should be version controlled and should not be manually edited. version: - revision: "5dcb86f68f239346676ceb1ed1ea385bd215fba1" + revision: "8495dee1fd4aacbe9de707e7581203232f591b2f" channel: "stable" project_type: app @@ -13,11 +13,11 @@ project_type: app migration: platforms: - platform: root - create_revision: 5dcb86f68f239346676ceb1ed1ea385bd215fba1 - base_revision: 5dcb86f68f239346676ceb1ed1ea385bd215fba1 - - platform: web - create_revision: 5dcb86f68f239346676ceb1ed1ea385bd215fba1 - base_revision: 5dcb86f68f239346676ceb1ed1ea385bd215fba1 + create_revision: 8495dee1fd4aacbe9de707e7581203232f591b2f + base_revision: 8495dee1fd4aacbe9de707e7581203232f591b2f + - platform: linux + create_revision: 8495dee1fd4aacbe9de707e7581203232f591b2f + base_revision: 8495dee1fd4aacbe9de707e7581203232f591b2f # User provided section diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle index d40f080fb..ee17a50bf 100644 --- a/example/android/app/build.gradle +++ b/example/android/app/build.gradle @@ -1,3 +1,9 @@ +plugins { + id "com.android.application" + id "kotlin-android" + id "dev.flutter.flutter-gradle-plugin" +} + def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { @@ -6,11 +12,6 @@ if (localPropertiesFile.exists()) { } } -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") -} - def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' @@ -21,9 +22,7 @@ if (flutterVersionName == null) { flutterVersionName = '1.0' } -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" + android { namespace "com.bonfire.example" @@ -68,5 +67,4 @@ flutter { } dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" } diff --git a/example/android/build.gradle b/example/android/build.gradle index f7eb7f63c..bc157bd1a 100644 --- a/example/android/build.gradle +++ b/example/android/build.gradle @@ -1,16 +1,3 @@ -buildscript { - ext.kotlin_version = '1.7.10' - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:7.3.0' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - allprojects { repositories { google() diff --git a/example/android/settings.gradle b/example/android/settings.gradle index 44e62bcf0..7d0644936 100644 --- a/example/android/settings.gradle +++ b/example/android/settings.gradle @@ -1,11 +1,25 @@ -include ':app' +pluginManagement { + def flutterSdkPath = { + def properties = new Properties() + file("local.properties").withInputStream { properties.load(it) } + def flutterSdkPath = properties.getProperty("flutter.sdk") + assert flutterSdkPath != null, "flutter.sdk not set in local.properties" + return flutterSdkPath + }() -def localPropertiesFile = new File(rootProject.projectDir, "local.properties") -def properties = new Properties() + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") -assert localPropertiesFile.exists() -localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} -def flutterSdkPath = properties.getProperty("flutter.sdk") -assert flutterSdkPath != null, "flutter.sdk not set in local.properties" -apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "7.3.0" apply false + id "org.jetbrains.kotlin.android" version "1.7.10" apply false +} + +include ":app" \ No newline at end of file diff --git a/example/ios/.gitignore b/example/ios/.gitignore deleted file mode 100644 index 7a7f9873a..000000000 --- a/example/ios/.gitignore +++ /dev/null @@ -1,34 +0,0 @@ -**/dgph -*.mode1v3 -*.mode2v3 -*.moved-aside -*.pbxuser -*.perspectivev3 -**/*sync/ -.sconsign.dblite -.tags* -**/.vagrant/ -**/DerivedData/ -Icon? -**/Pods/ -**/.symlinks/ -profile -xcuserdata -**/.generated/ -Flutter/App.framework -Flutter/Flutter.framework -Flutter/Flutter.podspec -Flutter/Generated.xcconfig -Flutter/ephemeral/ -Flutter/app.flx -Flutter/app.zip -Flutter/flutter_assets/ -Flutter/flutter_export_environment.sh -ServiceDefinitions.json -Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!default.mode1v3 -!default.mode2v3 -!default.pbxuser -!default.perspectivev3 diff --git a/example/ios/Flutter/AppFrameworkInfo.plist b/example/ios/Flutter/AppFrameworkInfo.plist deleted file mode 100644 index 9625e105d..000000000 --- a/example/ios/Flutter/AppFrameworkInfo.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - App - CFBundleIdentifier - io.flutter.flutter.app - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - App - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 1.0 - MinimumOSVersion - 11.0 - - diff --git a/example/ios/Flutter/Debug.xcconfig b/example/ios/Flutter/Debug.xcconfig deleted file mode 100644 index ec97fc6f3..000000000 --- a/example/ios/Flutter/Debug.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" -#include "Generated.xcconfig" diff --git a/example/ios/Flutter/Release.xcconfig b/example/ios/Flutter/Release.xcconfig deleted file mode 100644 index c4855bfe2..000000000 --- a/example/ios/Flutter/Release.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" -#include "Generated.xcconfig" diff --git a/example/ios/Podfile b/example/ios/Podfile deleted file mode 100644 index 3c6dbb6d2..000000000 --- a/example/ios/Podfile +++ /dev/null @@ -1,44 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '11.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - use_modular_headers! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) - # target 'RunnerTests' do - # inherit! :search_paths - # end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock deleted file mode 100644 index 261aff037..000000000 --- a/example/ios/Podfile.lock +++ /dev/null @@ -1,22 +0,0 @@ -PODS: - - Flutter (1.0.0) - - url_launcher_ios (0.0.1): - - Flutter - -DEPENDENCIES: - - Flutter (from `Flutter`) - - url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`) - -EXTERNAL SOURCES: - Flutter: - :path: Flutter - url_launcher_ios: - :path: ".symlinks/plugins/url_launcher_ios/ios" - -SPEC CHECKSUMS: - Flutter: f04841e97a9d0b0a8025694d0796dd46242b2854 - url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 - -PODFILE CHECKSUM: aa3b1d9cb94e8055dc6468141196cf9e4c8e33df - -COCOAPODS: 1.11.3 diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj deleted file mode 100644 index 0df7b5ff5..000000000 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ /dev/null @@ -1,555 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 54; - objects = { - -/* Begin PBXBuildFile section */ - 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; - 81877AFC5DB99A2C3B6BC794 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C5BDCA5A1D8356E4EBF1A2FA /* Pods_Runner.framework */; }; - 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; - 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; - 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; -/* End PBXBuildFile section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 9705A1C41CF9048500538489 /* Embed Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - ); - name = "Embed Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; - 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 24ED7860216D604779579C52 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 4D9508985911E827406DAFF4 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; - 605516D814B7A20DB9A53C05 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; - 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; - 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; - 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - C5BDCA5A1D8356E4EBF1A2FA /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 97C146EB1CF9000F007C117D /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 81877AFC5DB99A2C3B6BC794 /* Pods_Runner.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 28E14DBFFC3794B03AE1E5A9 /* Frameworks */ = { - isa = PBXGroup; - children = ( - C5BDCA5A1D8356E4EBF1A2FA /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 4E7B3CDCDFC936CAFEE4EE90 /* Pods */ = { - isa = PBXGroup; - children = ( - 24ED7860216D604779579C52 /* Pods-Runner.debug.xcconfig */, - 605516D814B7A20DB9A53C05 /* Pods-Runner.release.xcconfig */, - 4D9508985911E827406DAFF4 /* Pods-Runner.profile.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; - 9740EEB11CF90186004384FC /* Flutter */ = { - isa = PBXGroup; - children = ( - 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, - 9740EEB21CF90195004384FC /* Debug.xcconfig */, - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, - 9740EEB31CF90195004384FC /* Generated.xcconfig */, - ); - name = Flutter; - sourceTree = ""; - }; - 97C146E51CF9000F007C117D = { - isa = PBXGroup; - children = ( - 9740EEB11CF90186004384FC /* Flutter */, - 97C146F01CF9000F007C117D /* Runner */, - 97C146EF1CF9000F007C117D /* Products */, - 4E7B3CDCDFC936CAFEE4EE90 /* Pods */, - 28E14DBFFC3794B03AE1E5A9 /* Frameworks */, - ); - sourceTree = ""; - }; - 97C146EF1CF9000F007C117D /* Products */ = { - isa = PBXGroup; - children = ( - 97C146EE1CF9000F007C117D /* Runner.app */, - ); - name = Products; - sourceTree = ""; - }; - 97C146F01CF9000F007C117D /* Runner */ = { - isa = PBXGroup; - children = ( - 97C146FA1CF9000F007C117D /* Main.storyboard */, - 97C146FD1CF9000F007C117D /* Assets.xcassets */, - 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, - 97C147021CF9000F007C117D /* Info.plist */, - 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, - 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, - 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, - 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, - ); - path = Runner; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 97C146ED1CF9000F007C117D /* Runner */ = { - isa = PBXNativeTarget; - buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; - buildPhases = ( - A677980D24222FD7297BC793 /* [CP] Check Pods Manifest.lock */, - 9740EEB61CF901F6004384FC /* Run Script */, - 97C146EA1CF9000F007C117D /* Sources */, - 97C146EB1CF9000F007C117D /* Frameworks */, - 97C146EC1CF9000F007C117D /* Resources */, - 9705A1C41CF9048500538489 /* Embed Frameworks */, - 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - 9D30A9481ECB5A514B0D6D58 /* [CP] Embed Pods Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Runner; - productName = Runner; - productReference = 97C146EE1CF9000F007C117D /* Runner.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 97C146E61CF9000F007C117D /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 1430; - ORGANIZATIONNAME = ""; - TargetAttributes = { - 97C146ED1CF9000F007C117D = { - CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 1100; - }; - }; - }; - buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 97C146E51CF9000F007C117D; - productRefGroup = 97C146EF1CF9000F007C117D /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 97C146ED1CF9000F007C117D /* Runner */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 97C146EC1CF9000F007C117D /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, - 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, - 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, - 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { - isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", - ); - name = "Thin Binary"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; - }; - 9740EEB61CF901F6004384FC /* Run Script */ = { - isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Run Script"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; - }; - 9D30A9481ECB5A514B0D6D58 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - A677980D24222FD7297BC793 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 97C146EA1CF9000F007C117D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, - 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 97C146FA1CF9000F007C117D /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 97C146FB1CF9000F007C117D /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 97C147001CF9000F007C117D /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 249021D3217E4FDB00AE95B9 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - SUPPORTED_PLATFORMS = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Profile; - }; - 249021D4217E4FDB00AE95B9 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 2S2LBSQSMB; - ENABLE_BITCODE = NO; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.bonfire.example; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Profile; - }; - 97C147031CF9000F007C117D /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 97C147041CF9000F007C117D /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - SUPPORTED_PLATFORMS = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 97C147061CF9000F007C117D /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 2S2LBSQSMB; - ENABLE_BITCODE = NO; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.bonfire.example; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Debug; - }; - 97C147071CF9000F007C117D /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 2S2LBSQSMB; - ENABLE_BITCODE = NO; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.bonfire.example; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 97C147031CF9000F007C117D /* Debug */, - 97C147041CF9000F007C117D /* Release */, - 249021D3217E4FDB00AE95B9 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 97C147061CF9000F007C117D /* Debug */, - 97C147071CF9000F007C117D /* Release */, - 249021D4217E4FDB00AE95B9 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 97C146E61CF9000F007C117D /* Project object */; -} diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 919434a62..000000000 --- a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d981003..000000000 --- a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings deleted file mode 100644 index f9b0d7c5e..000000000 --- a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings +++ /dev/null @@ -1,8 +0,0 @@ - - - - - PreviewsEnabled - - - diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme deleted file mode 100644 index a6b826db2..000000000 --- a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 21a3cc14c..000000000 --- a/example/ios/Runner.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - diff --git a/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d981003..000000000 --- a/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings deleted file mode 100644 index f9b0d7c5e..000000000 --- a/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings +++ /dev/null @@ -1,8 +0,0 @@ - - - - - PreviewsEnabled - - - diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift deleted file mode 100644 index 70693e4a8..000000000 --- a/example/ios/Runner/AppDelegate.swift +++ /dev/null @@ -1,13 +0,0 @@ -import UIKit -import Flutter - -@UIApplicationMain -@objc class AppDelegate: FlutterAppDelegate { - override func application( - _ application: UIApplication, - didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? - ) -> Bool { - GeneratedPluginRegistrant.register(with: self) - return super.application(application, didFinishLaunchingWithOptions: launchOptions) - } -} diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index d36b1fab2..000000000 --- a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "images" : [ - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@3x.png", - "scale" : "3x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@3x.png", - "scale" : "3x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@3x.png", - "scale" : "3x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@2x.png", - "scale" : "2x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@3x.png", - "scale" : "3x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@1x.png", - "scale" : "1x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@1x.png", - "scale" : "1x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@1x.png", - "scale" : "1x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@2x.png", - "scale" : "2x" - }, - { - "size" : "83.5x83.5", - "idiom" : "ipad", - "filename" : "Icon-App-83.5x83.5@2x.png", - "scale" : "2x" - }, - { - "size" : "1024x1024", - "idiom" : "ios-marketing", - "filename" : "Icon-App-1024x1024@1x.png", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png deleted file mode 100644 index dc9ada472..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png deleted file mode 100644 index 28c6bf030..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png deleted file mode 100644 index 2ccbfd967..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png deleted file mode 100644 index f091b6b0b..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png deleted file mode 100644 index 4cde12118..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png deleted file mode 100644 index d0ef06e7e..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png deleted file mode 100644 index dcdc2306c..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png deleted file mode 100644 index 2ccbfd967..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png deleted file mode 100644 index c8f9ed8f5..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png deleted file mode 100644 index a6d6b8609..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png deleted file mode 100644 index a6d6b8609..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png deleted file mode 100644 index 75b2d164a..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png deleted file mode 100644 index c4df70d39..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png deleted file mode 100644 index 6a84f41e1..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png deleted file mode 100644 index d0e1f5853..000000000 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json deleted file mode 100644 index 0bedcf2fd..000000000 --- a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "LaunchImage.png", - "scale" : "1x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@2x.png", - "scale" : "2x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@3x.png", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png deleted file mode 100644 index 9da19eaca..000000000 Binary files a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png deleted file mode 100644 index 9da19eaca..000000000 Binary files a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png deleted file mode 100644 index 9da19eaca..000000000 Binary files a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png and /dev/null differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md deleted file mode 100644 index 89c2725b7..000000000 --- a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Launch Screen Assets - -You can customize the launch screen with your own desired assets by replacing the image files in this directory. - -You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/example/ios/Runner/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index f2e259c7c..000000000 --- a/example/ios/Runner/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/example/ios/Runner/Base.lproj/Main.storyboard b/example/ios/Runner/Base.lproj/Main.storyboard deleted file mode 100644 index f3c28516f..000000000 --- a/example/ios/Runner/Base.lproj/Main.storyboard +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist deleted file mode 100644 index 7f553465b..000000000 --- a/example/ios/Runner/Info.plist +++ /dev/null @@ -1,51 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleDisplayName - Example - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - example - CFBundlePackageType - APPL - CFBundleShortVersionString - $(FLUTTER_BUILD_NAME) - CFBundleSignature - ???? - CFBundleVersion - $(FLUTTER_BUILD_NUMBER) - LSRequiresIPhoneOS - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UIViewControllerBasedStatusBarAppearance - - CADisableMinimumFrameDurationOnPhone - - UIApplicationSupportsIndirectInputEvents - - - diff --git a/example/ios/Runner/Runner-Bridging-Header.h b/example/ios/Runner/Runner-Bridging-Header.h deleted file mode 100644 index 308a2a560..000000000 --- a/example/ios/Runner/Runner-Bridging-Header.h +++ /dev/null @@ -1 +0,0 @@ -#import "GeneratedPluginRegistrant.h" diff --git a/example/ios/RunnerTests/RunnerTests.swift b/example/ios/RunnerTests/RunnerTests.swift deleted file mode 100644 index 86a7c3b1b..000000000 --- a/example/ios/RunnerTests/RunnerTests.swift +++ /dev/null @@ -1,12 +0,0 @@ -import Flutter -import UIKit -import XCTest - -class RunnerTests: XCTestCase { - - func testExample() { - // If you add code to the Runner application, consider adding tests here. - // See https://developer.apple.com/documentation/xctest for more information about using XCTest. - } - -} diff --git a/example/lib/shared/decoration/spikes.dart b/example/lib/shared/decoration/spikes.dart index bfacbca58..d74ac985e 100644 --- a/example/lib/shared/decoration/spikes.dart +++ b/example/lib/shared/decoration/spikes.dart @@ -9,7 +9,7 @@ class Spikes extends GameDecoration with Sensor { position: position, size: size ?? Vector2.all(DungeonMap.tileSize / 1.5), ) { - setSensorInterval(500); + sensorInterval = 500; } @override diff --git a/example/pubspec.lock b/example/pubspec.lock index d29b2ea72..a91a15d61 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -13,10 +13,10 @@ packages: dependency: transitive description: name: a_star_algorithm - sha256: c9a92079331f8229f572718ed12c25b0e3adf3570318becfa689f5554e6ffd30 + sha256: efc131ca9a3eaceebe09fa67b9a7235d6e0a6e23ff0de4c009c60d506f791349 url: "https://pub.dev" source: hosted - version: "0.3.2" + version: "0.4.1" analyzer: dependency: transitive description: @@ -55,7 +55,7 @@ packages: path: ".." relative: true source: path - version: "3.12.0" + version: "3.12.4" boolean_selector: dependency: transitive description: @@ -76,10 +76,10 @@ packages: dependency: transitive description: name: collection - sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf url: "https://pub.dev" source: hosted - version: "1.18.0" + version: "1.19.0" convert: dependency: transitive description: @@ -254,18 +254,18 @@ packages: dependency: transitive description: name: material_color_utilities - sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a" + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec url: "https://pub.dev" source: hosted - version: "0.8.0" + version: "0.11.1" meta: dependency: transitive description: name: meta - sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136" + sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7 url: "https://pub.dev" source: hosted - version: "1.12.0" + version: "1.15.0" mime: dependency: transitive description: @@ -366,7 +366,7 @@ packages: dependency: transitive description: flutter source: sdk - version: "0.0.99" + version: "0.0.0" source_map_stack_trace: dependency: transitive description: diff --git a/lib/background/background_image_game.dart b/lib/background/background_image_game.dart index 7589b0d2c..a83531881 100644 --- a/lib/background/background_image_game.dart +++ b/lib/background/background_image_game.dart @@ -1,14 +1,3 @@ -/// -/// Created by -/// -/// ─▄▀─▄▀ -/// ──▀──▀ -/// █▀▀▀▀▀█▄ -/// █░░░░░█─█ -/// ▀▄▄▄▄▄▀▀ -/// -/// Rafaelbarbosatec -/// on 30/11/21 import 'package:bonfire/bonfire.dart'; import 'package:bonfire/camera/bonfire_camera.dart'; import 'package:bonfire/map/util/map_assets_manager.dart'; @@ -48,8 +37,8 @@ class BackgroundImageGame extends GameBackground with UseSprite { if (camera.position != _lastPosition) { _lastPosition = camera.position.clone(); position = _parallaxOffset.translated( - (camera.position.x * -(parallaxX / camera.zoom)), - (camera.position.y * -(parallaxY / camera.zoom)), + camera.position.x * -(parallaxX / camera.zoom), + camera.position.y * -(parallaxY / camera.zoom), ); } } diff --git a/lib/base/base_game.dart b/lib/base/base_game.dart index 84b4dbedf..ea5952898 100644 --- a/lib/base/base_game.dart +++ b/lib/base/base_game.dart @@ -23,7 +23,7 @@ abstract class BaseGame extends FlameGame @override void updateTree(double dt) { _gesturesComponents = [...world.children, ...camera.viewport.children] - .where((c) => _hasGesture(c)) + .where(_hasGesture) .cast(); super.updateTree(dt); } @@ -38,7 +38,9 @@ abstract class BaseGame extends FlameGame @override void onPointerCancel(PointerCancelEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerCancel(event)) { return; @@ -48,7 +50,9 @@ abstract class BaseGame extends FlameGame @override void onPointerUp(PointerUpEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerUp(event)) { return; @@ -58,7 +62,9 @@ abstract class BaseGame extends FlameGame @override void onPointerMove(PointerMoveEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerMove(event)) { return; @@ -68,7 +74,9 @@ abstract class BaseGame extends FlameGame @override void onPointerDown(PointerDownEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerDown(event)) { return; @@ -78,7 +86,9 @@ abstract class BaseGame extends FlameGame @override void onPointerHover(PointerHoverEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerHover(event)) { return; @@ -88,7 +98,9 @@ abstract class BaseGame extends FlameGame @override void onPointerSignal(PointerSignalEvent event) { - if (!hasLayout || !enabledGestures) return; + if (!hasLayout || !enabledGestures) { + return; + } for (final c in _gesturesComponents) { if (c.handlerPointerSignal(event)) { return; @@ -101,11 +113,11 @@ abstract class BaseGame extends FlameGame KeyEvent event, Set keysPressed, ) { - KeyEventResult result = KeyEventResult.ignored; + var result = KeyEventResult.ignored; if (!enabledKeyboard) { return result; } - for (var listener in _keyboardComponents) { + for (final listener in _keyboardComponents) { if (listener.onKeyboard(event, keysPressed)) { result = KeyEventResult.handled; } @@ -115,7 +127,7 @@ abstract class BaseGame extends FlameGame /// Verify if the Component contain gestures. bool _hasGesture(Component c) { - return ((c is GameComponent && c.isVisible)) && ((c).hasGesture()); + return (c is GameComponent && c.isVisible) && (c.hasGesture()); } @override diff --git a/lib/base/bonfire_game.dart b/lib/base/bonfire_game.dart index b06340458..e1190c070 100644 --- a/lib/base/bonfire_game.dart +++ b/lib/base/bonfire_game.dart @@ -10,7 +10,7 @@ import 'package:bonfire/joystick/joystick_map_explorer.dart'; import 'package:bonfire/lighting/lighting_component.dart'; import 'package:flame/camera.dart'; // ignore: implementation_imports -import 'package:flutter/widgets.dart'; +import 'package:flutter/widgets.dart' hide Viewport; /// Is a customGame where all magic of the Bonfire happen. class BonfireGame extends BaseGame implements BonfireGameInterface { @@ -21,11 +21,13 @@ class BonfireGame extends BaseGame implements BonfireGameInterface { @override final BuildContext context; - /// Represents the character controlled by the user in the game. Instances of this class has actions and movements ready to be used and configured. + /// Represents the character controlled by the user in the game. Instances of + /// this class has actions and movements ready to be used and configured. @override final Player? player; - /// The way you can draw things like life bars, stamina and settings. In another words, anything that you may add to the interface to the game. + /// The way you can draw things like life bars, stamina and settings. + /// In another words, anything that you may add to the interface to the game. @override final GameInterface? interface; @@ -87,7 +89,9 @@ class BonfireGame extends BaseGame implements BonfireGameInterface { throw Exception('Is forbiden updade camera'); } - /// variable that keeps the highest rendering priority per frame. This is used to determine the order in which to render the `interface`, `lighting` and `joystick` + /// variable that keeps the highest rendering priority per frame. + /// This is used to determine the order in which to render the `interface`, + /// `lighting` and `joystick` int _highestPriority = 1000000; /// Get of the _highestPriority @@ -127,7 +131,7 @@ class BonfireGame extends BaseGame implements BonfireGameInterface { ), ...playerControllers ?? [], if (interface != null) interface, - ...hudComponents ?? [] + ...hudComponents ?? [], ], ), world: World( @@ -188,7 +192,8 @@ class BonfireGame extends BaseGame implements BonfireGameInterface { super.update(dt); _intervalUpdateOder.update(dt); _intervalOprimizeTree.update(dt); - if (!_gameMounted && camera.world?.children.isNotEmpty == true) { + final containsChildren = camera.world?.children.isNotEmpty == true; + if (!_gameMounted && containsChildren) { _gameMounted = true; Future.delayed(Duration.zero, _notifyGameMounted); } @@ -223,7 +228,7 @@ class BonfireGame extends BaseGame implements BonfireGameInterface { @override Iterable collisions({bool onlyVisible = false}) { if (onlyVisible) { - List tilesCollision = []; + final tilesCollision = []; map .getRenderedTiles() .where((element) => element.containsShapeHitbox) @@ -274,8 +279,12 @@ class BonfireGame extends BaseGame implements BonfireGameInterface { @override bool isVisibleInCamera(GameComponent c) { - if (!hasLayout) return false; - if (c.isRemoving) return false; + if (!hasLayout) { + return false; + } + if (c.isRemoving) { + return false; + } return camera.canSee(c); } @@ -308,13 +317,10 @@ class BonfireGame extends BaseGame implements BonfireGameInterface { @override void stopScene() { - try { - world.children - .firstWhere((value) => value is SceneBuilderComponent) - .removeFromParent(); - } catch (e) { - /// Not found SceneBuilderComponent - } + world.children + .whereType() + .firstOrNull + ?.removeFromParent(); } @override @@ -333,9 +339,7 @@ class BonfireGame extends BaseGame implements BonfireGameInterface { void removeVisible(GameComponent obj) { _visibleComponents.remove(obj); if (obj.containsShapeHitbox) { - obj.children.query().forEach((element) { - _visibleCollisions.remove(element); - }); + obj.children.query().forEach(_visibleCollisions.remove); } } @@ -477,7 +481,7 @@ class BonfireGame extends BaseGame implements BonfireGameInterface { FollowerWidget.removeAll(); void gameDetachComp(GameComponent c) => c.onGameDetach(); query().forEach(gameDetachComp); - for (var child in camera.children) { + for (final child in camera.children) { if (child is GameComponent) { child.onGameDetach(); } @@ -498,7 +502,7 @@ class BonfireGame extends BaseGame implements BonfireGameInterface { return camera.viewport.add(component); } - static _getViewPort(CameraConfig? cameraConfig) { + static Viewport? _getViewPort(CameraConfig? cameraConfig) { if (cameraConfig?.resolution != null) { return FixedResolutionViewport( resolution: cameraConfig!.resolution!, diff --git a/lib/base/bonfire_game_interface.dart b/lib/base/bonfire_game_interface.dart index c89fcd139..4f94ecd89 100644 --- a/lib/base/bonfire_game_interface.dart +++ b/lib/base/bonfire_game_interface.dart @@ -4,7 +4,6 @@ import 'package:bonfire/bonfire.dart'; import 'package:bonfire/camera/bonfire_camera.dart'; import 'package:bonfire/color_filter/color_filter_component.dart'; import 'package:bonfire/lighting/lighting_component.dart'; -import 'package:flame/game.dart'; // ignore: implementation_imports import 'package:flame/src/game/overlay_manager.dart'; import 'package:flutter/widgets.dart'; @@ -40,23 +39,6 @@ abstract class BonfireGameInterface { SceneBuilderStatus sceneBuilderStatus = SceneBuilderStatus(); double timeScale = 1.0; - /// A property that stores an [ActiveOverlaysNotifier] - /// - /// This is useful to render widgets above a game, like a pause menu for - /// example. - /// Overlays visible or hidden via [overlays].add or [overlays].remove, - /// respectively. - /// - /// Ex: - /// ``` - /// final pauseOverlayIdentifier = 'PauseMenu'; - /// overlays.add(pauseOverlayIdentifier); // marks 'PauseMenu' to be rendered. - /// overlays.remove(pauseOverlayIdentifier); // marks 'PauseMenu' to not be rendered. - /// ``` - /// - /// See also: - /// - GameWidget - /// - [Game.overlayManager] // ignore: invalid_use_of_internal_member OverlayManager get overlays; diff --git a/lib/base/game_component.dart b/lib/base/game_component.dart index e2bcfe6d1..3ab788526 100644 --- a/lib/base/game_component.dart +++ b/lib/base/game_component.dart @@ -12,7 +12,7 @@ abstract class GameComponent extends PositionComponent InternalChecker, HasPaint, CollisionCallbacks { - final String _keyIntervalCheckIsVisible = "CHECK_VISIBLE"; + final String _keyIntervalCheckIsVisible = 'CHECK_VISIBLE'; final int _intervalCheckIsVisible = 100; Map? properties; @@ -22,7 +22,14 @@ abstract class GameComponent extends PositionComponent /// Param checks if this component is visible on the screen bool _isVisibleInScreen = false; - bool get isVisible => _visible ? _isVisibleInScreen : false; + bool get isVisible { + if (_visible) { + return _isVisibleInScreen; + } + + return false; + } + set isVisible(bool visible) { _visible = visible; } @@ -67,7 +74,9 @@ abstract class GameComponent extends PositionComponent } void _checkIsVisible(double dt) { - if (!enabledCheckIsVisible) return; + if (!enabledCheckIsVisible) { + return; + } if (checkInterval( _keyIntervalCheckIsVisible, _intervalCheckIsVisible, @@ -90,7 +99,10 @@ abstract class GameComponent extends PositionComponent /// Method that checks if this component is visible on the screen @mustCallSuper bool isVisibleInCamera() { - return hasGameRef ? gameRef.isVisibleInCamera(this) : false; + if (hasGameRef) { + return gameRef.isVisibleInCamera(this); + } + return false; } @override @@ -101,8 +113,10 @@ abstract class GameComponent extends PositionComponent } void _onSetIfVisible() { - if (!_visible) return; - bool nowIsVisible = isVisibleInCamera(); + if (!_visible) { + return; + } + var nowIsVisible = isVisibleInCamera(); if (isHud) { nowIsVisible = true; enabledCheckIsVisible = false; @@ -134,7 +148,7 @@ abstract class GameComponent extends PositionComponent void _confHitBoxRender(Component component) { if (component is ShapeHitbox) { if (gameRef.showCollisionArea) { - var paintCollition = Paint() + final paintCollition = Paint() ..color = gameRef.collisionAreaColor ?? const Color(0xffffffff); if (this is Sensor) { paintCollition.color = Sensor.color; @@ -153,7 +167,7 @@ abstract class GameComponent extends PositionComponent Rect get rectCollision { if (_rectCollision == null) { - var list = children.query(); + final list = children.query(); if (list.isNotEmpty) { _rectCollision = list.fold( list.first.toRect(), @@ -163,7 +177,7 @@ abstract class GameComponent extends PositionComponent ); } } - var absoluteRect = toAbsoluteRect(); + final absoluteRect = toAbsoluteRect(); if (_rectCollision != null) { return _rectCollision!.translate(absoluteRect.left, absoluteRect.top); @@ -245,7 +259,7 @@ abstract class GameComponent extends PositionComponent } List _getSensorsHitbox() { - var sensorHitBox = []; + final sensorHitBox = []; gameRef.query(onlyVisible: true).forEach((e) { sensorHitBox.addAll(e.children.query()); }); diff --git a/lib/base/listener_game_widget.dart b/lib/base/listener_game_widget.dart index 411af5df2..43d2de427 100644 --- a/lib/base/listener_game_widget.dart +++ b/lib/base/listener_game_widget.dart @@ -32,8 +32,8 @@ typedef GameFactory = T Function(); class ListenerGameWidget extends StatefulWidget { /// The game instance which this widget will render, if the normal constructor /// is used. - /// If the [ListenerGameWidget.controlled] constructor is used, this will always be - /// `null`. + /// If the [ListenerGameWidget.controlled] constructor is used, this will + /// aways be `null`. final T? game; /// A function that creates a [Game] that this widget will render. @@ -121,8 +121,8 @@ class ListenerGameWidget extends StatefulWidget { /// game.overlays.add('PauseMenu'); /// ``` ListenerGameWidget({ - Key? key, required T this.game, + super.key, this.textDirection, this.loadingBuilder, this.errorBuilder, @@ -133,8 +133,7 @@ class ListenerGameWidget extends StatefulWidget { this.autofocus = true, this.mouseCursor, this.addRepaintBoundary = true, - }) : gameFactory = null, - super(key: key) { + }) : gameFactory = null { _initializeGame(game!); } @@ -198,11 +197,12 @@ class ListenerGameWidgetState /// /// This is needed because our build function invokes user code, which in turn /// may change some of the [Game]'s properties which would require the - /// [ListenerGameWidget] to be rebuilt. However, Flutter doesn't allow widgets to be + /// [ListenerGameWidget] to be rebuilt. However, Flutter doesn't allow widgets + /// to be /// marked dirty while they are building. So, this method is needed to avoid /// such a limitation and ensure that the user code can set [Game]'s - /// properties freely, and that they will be propagated to the [ListenerGameWidget] - /// at the earliest opportunity. + /// properties freely, and that they will be propagated to the + /// [ListenerGameWidget] at the earliest opportunity. Widget _protectedBuild(Widget Function() build) { late final Widget result; try { @@ -382,9 +382,10 @@ class ListenerGameWidgetState Container(); } currentGame.onGameResize(size); - // This should only be called if the game has already been - // loaded (in the case of resizing for example), since - // update otherwise should be called after onMount. + // This should only be called if the game has already + // been loaded (in the case of resizing for example), + // since update otherwise should be called after + // onMount. if (!currentGame.paused && currentGame.isAttached) { currentGame.update(0); } diff --git a/lib/behavior/behavior_manager.dart b/lib/behavior/behavior_manager.dart index 9c4973dea..86fc633f3 100644 --- a/lib/behavior/behavior_manager.dart +++ b/lib/behavior/behavior_manager.dart @@ -23,7 +23,7 @@ class BehaviorManager extends Component with BonfireHasGameRef { @override void onMount() { - _comp = parent as GameComponent; + _comp = parent! as GameComponent; super.onMount(); } } diff --git a/lib/behavior/behaviors/b_contition/b_condition.dart b/lib/behavior/behaviors/b_contition/b_condition.dart index 59dbf4905..b06a2f44f 100644 --- a/lib/behavior/behaviors/b_contition/b_condition.dart +++ b/lib/behavior/behaviors/b_contition/b_condition.dart @@ -9,9 +9,9 @@ class BCondition extends Behavior { final Behavior? doElseBehavior; BCondition({ - dynamic id, required this.condition, required this.doBehavior, + dynamic id, this.doElseBehavior, }) : super(id); diff --git a/lib/behavior/behaviors/b_contition/conditions/c_can_see.dart b/lib/behavior/behaviors/b_contition/conditions/c_can_see.dart index 31dddfc7d..75aec5926 100644 --- a/lib/behavior/behaviors/b_contition/conditions/c_can_see.dart +++ b/lib/behavior/behaviors/b_contition/conditions/c_can_see.dart @@ -18,7 +18,7 @@ class CCanSee extends Condition { @override bool execute(GameComponent comp, BonfireGameInterface game) { if (comp is Vision) { - bool see = false; + var see = false; comp.seeComponent( target, radiusVision: radiusVision, @@ -26,7 +26,7 @@ class CCanSee extends Condition { angle: angle, observed: (c) { observed?.call(c); - return see = true; + see = true; }, ); return see; diff --git a/lib/behavior/behaviors/b_contition/conditions/c_can_see_type.dart b/lib/behavior/behaviors/b_contition/conditions/c_can_see_type.dart index f3195550f..cf34e148c 100644 --- a/lib/behavior/behaviors/b_contition/conditions/c_can_see_type.dart +++ b/lib/behavior/behaviors/b_contition/conditions/c_can_see_type.dart @@ -16,14 +16,14 @@ class CCanSeeType extends Condition { @override bool execute(GameComponent comp, BonfireGameInterface game) { if (comp is Vision) { - bool see = false; + var see = false; comp.seeComponentType( radiusVision: radiusVision, visionAngle: visionAngle, angle: angle, observed: (c) { observed?.call(c); - return see = true; + see = true; }, ); return see; diff --git a/lib/behavior/behaviors/b_custom.dart b/lib/behavior/behaviors/b_custom.dart index 7bcd22263..c6291c45b 100644 --- a/lib/behavior/behaviors/b_custom.dart +++ b/lib/behavior/behaviors/b_custom.dart @@ -3,10 +3,16 @@ import 'package:bonfire/base/game_component.dart'; import 'package:bonfire/behavior/behavior.dart'; class BCustom extends Behavior { - final bool Function(double dt, GameComponent comp, BonfireGameInterface game) - behavior; + final bool Function( + double dt, + GameComponent comp, + BonfireGameInterface game, + ) behavior; - BCustom({dynamic id, required this.behavior}) : super(id); + BCustom({ + required this.behavior, + dynamic id, + }) : super(id); @override bool runAction(double dt, GameComponent comp, BonfireGameInterface game) { return behavior(dt, comp, game); diff --git a/lib/behavior/behaviors/b_move_to_component.dart b/lib/behavior/behaviors/b_move_to_component.dart index a4845af41..21e62b98b 100644 --- a/lib/behavior/behaviors/b_move_to_component.dart +++ b/lib/behavior/behaviors/b_move_to_component.dart @@ -7,8 +7,8 @@ class BMoveToComponent extends Behavior { final MovementAxis movementAxis; BMoveToComponent({ - dynamic id, required this.target, + dynamic id, this.margin = 0, this.movementAxis = MovementAxis.all, }) : super(id); diff --git a/lib/bonfire.dart b/lib/bonfire.dart index 30a55b799..0ad42f680 100644 --- a/lib/bonfire.dart +++ b/lib/bonfire.dart @@ -35,7 +35,6 @@ export 'package:bonfire/map/tiled/world_map_by_tiled.dart'; export 'package:bonfire/map/util/world_map_reader.dart'; export 'package:bonfire/map/world_map.dart'; export 'package:bonfire/mixins/attackable.dart'; -export 'package:bonfire/mixins/random_movement.dart'; export 'package:bonfire/mixins/elastic_collision.dart'; export 'package:bonfire/mixins/flip_render.dart'; export 'package:bonfire/mixins/follower.dart'; @@ -47,12 +46,13 @@ export 'package:bonfire/mixins/movement.dart'; export 'package:bonfire/mixins/movement_by_joystick.dart'; export 'package:bonfire/mixins/path_finding.dart'; export 'package:bonfire/mixins/pushable.dart'; +export 'package:bonfire/mixins/random_movement.dart'; export 'package:bonfire/mixins/sensor.dart'; +export 'package:bonfire/mixins/shader/use_shader.dart'; export 'package:bonfire/mixins/tile_recognizer.dart'; export 'package:bonfire/mixins/update_camera_by_pinch_gesture.dart'; export 'package:bonfire/mixins/use_assets_loader.dart'; export 'package:bonfire/mixins/use_barlife.dart'; -export 'package:bonfire/mixins/shader/use_shader.dart'; export 'package:bonfire/mixins/use_sprite.dart'; export 'package:bonfire/mixins/use_sprite_animation.dart'; export 'package:bonfire/mixins/vision.dart'; diff --git a/lib/camera/bonfire_camera.dart b/lib/camera/bonfire_camera.dart index 242c506b4..63905f1c9 100644 --- a/lib/camera/bonfire_camera.dart +++ b/lib/camera/bonfire_camera.dart @@ -1,5 +1,3 @@ -import 'dart:math'; - import 'package:bonfire/bonfire.dart'; import 'package:bonfire/camera/camera_effects.dart'; import 'package:flame/experimental.dart'; @@ -44,6 +42,7 @@ class BonfireCamera extends CameraComponent with BonfireHasGameRef { return cameraRectWithSpacing.overlaps(component.toAbsoluteRect()); } + // ignore: use_setters_to_change_properties void updateSpacingVisibleMap(double space) { _spacingMap = space; } @@ -76,7 +75,7 @@ class BonfireCamera extends CameraComponent with BonfireHasGameRef { Function()? onComplete, }) { stop(); - var controller = effectController ?? EffectController(duration: 1); + final controller = effectController ?? EffectController(duration: 1); final moveToEffect = MoveToEffect( position, controller, @@ -216,7 +215,7 @@ class BonfireCamera extends CameraComponent with BonfireHasGameRef { set mapZoomFit(InitialMapZoomFitEnum value) { config.initialMapZoomFit = value; - Vector2 sizeScreen = canvasSize; + final sizeScreen = canvasSize; switch (value) { case InitialMapZoomFitEnum.none: break; @@ -227,12 +226,11 @@ class BonfireCamera extends CameraComponent with BonfireHasGameRef { zoom = sizeScreen.y / gameRef.map.getMapSize().y; break; case InitialMapZoomFitEnum.fit: - double minScreenDimension = min(sizeScreen.x, sizeScreen.y); - double minMapDimension = max( - gameRef.map.getMapSize().x, - gameRef.map.getMapSize().y, - ); - zoom = minScreenDimension / minMapDimension; + if (sizeScreen.x > sizeScreen.y) { + zoom = sizeScreen.x / gameRef.map.getMapSize().x; + } else { + zoom = sizeScreen.y / gameRef.map.getMapSize().y; + } break; } } diff --git a/lib/camera/camera_effects.dart b/lib/camera/camera_effects.dart index 01a72a73a..887e5bb9a 100644 --- a/lib/camera/camera_effects.dart +++ b/lib/camera/camera_effects.dart @@ -29,7 +29,9 @@ class MyFollowBehavior extends FollowBehavior { delta = _moveVertical(delta); } - if (delta.isZero()) return; + if (delta.isZero()) { + return; + } if (delta.length <= maxSpeed * dt) { owner.position = delta..add(owner.position); } else { @@ -68,7 +70,7 @@ class MyFollowBehavior extends FollowBehavior { class ShakeEffect extends Component { final double intensity; final Duration duration; - PositionProvider get target => parent as PositionProvider; + PositionProvider get target => parent! as PositionProvider; final void Function()? onComplete; double _shakeTimer = 0.0; late Vector2 initialPosition; diff --git a/lib/collision/block_movement_collision.dart b/lib/collision/block_movement_collision.dart index 6037e6a87..10d79a0a5 100644 --- a/lib/collision/block_movement_collision.dart +++ b/lib/collision/block_movement_collision.dart @@ -21,7 +21,7 @@ mixin BlockMovementCollision on Movement { bool get blockMovementCollisionEnabled => _blockMovementCollisionEnabled; final Map _collisionsResolution = {}; CollisionData? _lastCollisionData; - CollisionData? get lastCollisionData => _lastCollisionData!; + CollisionData? get lastCollisionData => _lastCollisionData; void setupBlockMovementCollision({bool? enabled, BodyType? bodyType}) { _bodyType = bodyType ?? _bodyType; @@ -50,14 +50,14 @@ mixin BlockMovementCollision on Movement { if (_bodyType.isDynamic) { Vector2 correction; - double depth = collisionData.depth.abs(); + var depth = collisionData.depth.abs(); if (depth > 0) { depth += 0.08; } - correction = (-collisionData.normal * depth); + correction = -collisionData.normal * depth; if ((other is BlockMovementCollision) && other._bodyType.isDynamic) { - correction = (-collisionData.normal * depth / 2); + correction = -collisionData.normal * depth / 2; } correctPositionFromCollision(position + correction); @@ -82,8 +82,8 @@ mixin BlockMovementCollision on Movement { super.onCollision(intersectionPoints, other); return; } - bool stopOtherMovement = true; - bool stopMovement = other is GameComponent + var stopOtherMovement = true; + final stopMovement = other is GameComponent ? onBlockMovement(intersectionPoints, other) : true; if (other is BlockMovementCollision) { @@ -108,11 +108,11 @@ mixin BlockMovementCollision on Movement { return; } - ShapeHitbox? shape1 = _getCollisionShapeHitbox( + final shape1 = _getCollisionShapeHitbox( shapeHitboxes, intersectionPoints, ); - ShapeHitbox? shape2 = _getCollisionShapeHitbox( + final shape2 = _getCollisionShapeHitbox( other.children.query(), intersectionPoints, ); @@ -167,13 +167,13 @@ mixin BlockMovementCollision on Movement { ShapeHitbox shapeB, PositionComponent other, ) { - Vector2 normal = Vector2.zero(); - double depth = double.maxFinite; + var normal = Vector2.zero(); + var depth = double.maxFinite; - List verticesA = CollisionUtil.getPolygonVertices(shapeA); - List verticesB = CollisionUtil.getPolygonVertices(shapeB); + final verticesA = CollisionUtil.getPolygonVertices(shapeA); + final verticesB = CollisionUtil.getPolygonVertices(shapeB); - var normalAndDepthA = CollisionUtil.getNormalAndDepth( + final normalAndDepthA = CollisionUtil.getNormalAndDepth( verticesA, verticesB, ); @@ -182,7 +182,7 @@ mixin BlockMovementCollision on Movement { depth = normalAndDepthA.depth; normal = normalAndDepthA.normal; } - var normalAndDepthB = CollisionUtil.getNormalAndDepth( + final normalAndDepthB = CollisionUtil.getNormalAndDepth( verticesB, verticesA, insverted: true, @@ -193,7 +193,7 @@ mixin BlockMovementCollision on Movement { normal = normalAndDepthB.normal; } - Vector2 direction = shapeB.absoluteCenter - shapeA.absoluteCenter; + final direction = shapeB.absoluteCenter - shapeA.absoluteCenter; if (direction.dot(normal) < 0) { normal = -normal; @@ -208,18 +208,18 @@ mixin BlockMovementCollision on Movement { PositionComponent other, { bool inverted = false, }) { - Vector2 normal = Vector2.zero(); - double depth = double.maxFinite; - Vector2 axis = Vector2.zero(); + var normal = Vector2.zero(); + var depth = double.maxFinite; + var axis = Vector2.zero(); double axisDepth = 0; - List vertices = CollisionUtil.getPolygonVertices(shapeA); + final vertices = CollisionUtil.getPolygonVertices(shapeA); - for (int i = 0; i < vertices.length; i++) { - Vector2 va = vertices[i]; - Vector2 vb = vertices[(i + 1) % vertices.length]; + for (var i = 0; i < vertices.length; i++) { + final va = vertices[i]; + final vb = vertices[(i + 1) % vertices.length]; - Vector2 edge = vb - va; + final edge = vb - va; axis = Vector2(-edge.y, edge.x); axis = axis.normalized(); @@ -238,11 +238,11 @@ mixin BlockMovementCollision on Movement { } } - int cpIndex = CollisionUtil.findClosesPointOnPolygon( + final cpIndex = CollisionUtil.findClosesPointOnPolygon( shapeB.absoluteCenter, vertices, ); - Vector2 cp = vertices[cpIndex]; + final cp = vertices[cpIndex]; axis = cp - shapeB.absoluteCenter; axis = axis.normalized(); @@ -261,7 +261,7 @@ mixin BlockMovementCollision on Movement { normal = axis; } - Vector2 direction = inverted + final direction = inverted ? shapeA.absoluteCenter - shapeB.absoluteCenter : shapeB.absoluteCenter - shapeA.absoluteCenter; @@ -273,12 +273,14 @@ mixin BlockMovementCollision on Movement { } ({Vector2 normal, double depth}) _intersectCircles( - CircleHitbox shapeA, CircleHitbox shapeB) { - Vector2 normal = Vector2.zero(); - double depth = double.maxFinite; + CircleHitbox shapeA, + CircleHitbox shapeB, + ) { + var normal = Vector2.zero(); + var depth = double.maxFinite; - double distance = shapeA.absoluteCenter.distanceTo(shapeB.absoluteCenter); - double radii = shapeA.radius + shapeB.radius; + final distance = shapeA.absoluteCenter.distanceTo(shapeB.absoluteCenter); + final radii = shapeA.radius + shapeB.radius; normal = (shapeB.absoluteCenter - shapeA.absoluteCenter).normalized(); depth = radii - distance; @@ -290,13 +292,15 @@ mixin BlockMovementCollision on Movement { Iterable shapeHitboxes, Set intersectionPoints, ) { - if (shapeHitboxes.isEmpty || intersectionPoints.isEmpty) return null; + if (shapeHitboxes.isEmpty || intersectionPoints.isEmpty) { + return null; + } if (shapeHitboxes.length == 1) { return shapeHitboxes.first; } - Map distances = {}; - for (var hitbox in shapeHitboxes) { - for (var element in intersectionPoints) { + final distances = {}; + for (final hitbox in shapeHitboxes) { + for (final element in intersectionPoints) { distances[hitbox] = hitbox.absoluteCenter.distanceTo(element); if (hitbox.containsPoint(element)) { return hitbox; diff --git a/lib/collision/collision_util.dart b/lib/collision/collision_util.dart index e46e57837..4e5ed2551 100644 --- a/lib/collision/collision_util.dart +++ b/lib/collision/collision_util.dart @@ -15,20 +15,20 @@ class CollisionUtil { List verticesB, { bool insverted = false, }) { - Vector2 normal = Vector2.zero(); - double depth = double.maxFinite; - for (int i = 0; i < verticesA.length; i++) { - Vector2 va = verticesA[i]; - Vector2 vb = verticesA[(i + 1) % verticesA.length]; - - Vector2 edge = vb - va; - Vector2 axis = Vector2(-edge.y, edge.x); + var normal = Vector2.zero(); + var depth = double.maxFinite; + for (var i = 0; i < verticesA.length; i++) { + final va = verticesA[i]; + final vb = verticesA[(i + 1) % verticesA.length]; + + final edge = vb - va; + var axis = Vector2(-edge.y, edge.x); axis = axis.normalized(); final pA = projectVertices(insverted ? verticesB : verticesA, axis); final pB = projectVertices(insverted ? verticesA : verticesB, axis); - double axisDepth = min(pB.max - pA.min, pA.max - pB.min); + final double axisDepth = min(pB.max - pA.min, pA.max - pB.min); if (axisDepth < depth) { depth = axisDepth; normal = axis; @@ -41,10 +41,10 @@ class CollisionUtil { List vertices, Vector2 axis, ) { - double min = double.maxFinite; - double max = -double.maxFinite; - for (var v in vertices) { - double proj = v.dot(axis); + var min = double.maxFinite; + var max = -double.maxFinite; + for (final v in vertices) { + final proj = v.dot(axis); if (proj < min) { min = proj; @@ -57,19 +57,22 @@ class CollisionUtil { } static ({double min, double max}) projectCircle( - Vector2 center, double radius, Vector2 axis) { - Vector2 direction = axis.normalized(); - Vector2 directionAndRadius = direction * radius; + Vector2 center, + double radius, + Vector2 axis, + ) { + final direction = axis.normalized(); + final directionAndRadius = direction * radius; - Vector2 p1 = center + directionAndRadius; - Vector2 p2 = center - directionAndRadius; + final p1 = center + directionAndRadius; + final p2 = center - directionAndRadius; - double min = p1.dot(axis); - double max = p2.dot(axis); + var min = p1.dot(axis); + var max = p2.dot(axis); if (min > max) { // swap the min and max values. - double t = min; + final t = min; min = max; max = t; } @@ -80,12 +83,12 @@ class CollisionUtil { Vector2 circleCenter, List vertices, ) { - int result = -1; - double minDistance = double.maxFinite; + var result = -1; + var minDistance = double.maxFinite; - for (int i = 0; i < vertices.length; i++) { - Vector2 v = vertices[i]; - double distance = v.distanceTo(circleCenter); + for (var i = 0; i < vertices.length; i++) { + final v = vertices[i]; + final distance = v.distanceTo(circleCenter); if (distance < minDistance) { minDistance = distance; @@ -101,7 +104,7 @@ final _cachedGlobalVertices = ValueCache>(); extension PolygonComponentExt on PolygonComponent { List get absoluteVertices { - final Vector2 p = absoluteTopLeftPosition; + final p = absoluteTopLeftPosition; final adjustedVerticies = absoluteAngle == 0 ? vertices : rotatedVerticesBonfire(absoluteAngle); diff --git a/lib/color_filter/color_filter_component.dart b/lib/color_filter/color_filter_component.dart index ffd7038d2..a4e2f4683 100644 --- a/lib/color_filter/color_filter_component.dart +++ b/lib/color_filter/color_filter_component.dart @@ -44,7 +44,7 @@ class ColorFilterComponent extends GameComponent Color color, { BlendMode? blendMode, Duration duration = const Duration(milliseconds: 500), - curve = Curves.decelerate, + Curve curve = Curves.decelerate, VoidCallback? onFinish, }) { if (blendMode != null) { diff --git a/lib/decoration/decoration.dart b/lib/decoration/decoration.dart index de1bade41..81261550d 100644 --- a/lib/decoration/decoration.dart +++ b/lib/decoration/decoration.dart @@ -33,7 +33,9 @@ class GameDecoration extends AnimatedGameObject { super.lightingConfig, super.renderAboveComponents, }) { - loader?.add(AssetToLoad(sprite, (value) => this.sprite = value)); + loader?.add( + AssetToLoad(sprite, (value) => this.sprite = value), + ); applyBleedingPixel(position: position, size: size); } @@ -46,7 +48,7 @@ class GameDecoration extends AnimatedGameObject { super.lightingConfig, super.renderAboveComponents, }) { - loader?.add(AssetToLoad(animation, (value) => setAnimation(value))); + loader?.add(AssetToLoad(animation, setAnimation)); applyBleedingPixel(position: position, size: size); } diff --git a/lib/decoration/decoration_with_collision.dart b/lib/decoration/decoration_with_collision.dart index ed6783dbf..184b18559 100644 --- a/lib/decoration/decoration_with_collision.dart +++ b/lib/decoration/decoration_with_collision.dart @@ -4,48 +4,29 @@ import 'package:bonfire/bonfire.dart'; class GameDecorationWithCollision extends GameDecoration { Iterable? collisions; GameDecorationWithCollision({ - required Vector2 position, - required Vector2 size, - Sprite? sprite, - SpriteAnimation? animation, + required super.position, + required super.size, + super.sprite, + super.animation, this.collisions, - double offsetX = 0, - double offsetY = 0, super.renderAboveComponents, - }) : super( - position: position, - size: size, - animation: animation, - sprite: sprite, - ); + }); GameDecorationWithCollision.withSprite({ - required Future sprite, - required Vector2 position, - required Vector2 size, + required Future super.sprite, + required super.position, + required super.size, this.collisions, - double offsetX = 0, - double offsetY = 0, super.renderAboveComponents, - }) : super.withSprite( - sprite: sprite, - position: position, - size: size, - ); + }) : super.withSprite(); GameDecorationWithCollision.withAnimation({ - required Future animation, - required Vector2 position, - required Vector2 size, + required Future super.animation, + required super.position, + required super.size, this.collisions, - double offsetX = 0, - double offsetY = 0, super.renderAboveComponents, - }) : super.withAnimation( - animation: animation, - position: position, - size: size, - ); + }) : super.withAnimation(); @override Future onLoad() { diff --git a/lib/forces/handle_forces.dart b/lib/forces/handle_forces.dart index 0e676fc19..749b085ec 100644 --- a/lib/forces/handle_forces.dart +++ b/lib/forces/handle_forces.dart @@ -3,7 +3,8 @@ import 'package:bonfire/bonfire.dart'; export 'package:bonfire/forces/forces_2d.dart'; /// Mixin that makes the component suffer influences from global or local forces. -/// To adds local forces just call `addForce` method. To adds global foreces use the param `globalForces` in `BonfireWidget`. +/// To adds local forces just call `addForce` method. To adds global foreces use +/// the param `globalForces` in `BonfireWidget`. mixin HandleForces on Movement { /// Mass of the Component double _mass = 1.0; @@ -34,12 +35,12 @@ mixin HandleForces on Movement { return super.onVelocityUpdate(dt, velocity); } final oldVelocity = velocity.clone(); - List mergeForces = [..._forces, ...gameRef.globalForces]; + final mergeForces = [..._forces, ...gameRef.globalForces]; final acceleration = mergeForces.whereType(); final resistence = mergeForces.whereType(); final linear = mergeForces.whereType(); - Vector2 newVel = onApplyAccelerationForces(acceleration, velocity, dt); + var newVel = onApplyAccelerationForces(acceleration, velocity, dt); newVel = onApplyLinearForces(linear, newVel, dt); newVel = onApplyResistenceForces(resistence, newVel, dt); diff --git a/lib/game_interface/game_interface.dart b/lib/game_interface/game_interface.dart index c91ee9e5b..16c73980d 100644 --- a/lib/game_interface/game_interface.dart +++ b/lib/game_interface/game_interface.dart @@ -20,7 +20,9 @@ class GameInterface extends GameComponent { /// Used to remove component of the interface by id void removeById(int id) { - if (children.isEmpty) return; + if (children.isEmpty) { + return; + } removeWhere( (component) => component is InterfaceComponent && component.id == id, ); diff --git a/lib/game_interface/interface_component.dart b/lib/game_interface/interface_component.dart index 50158557e..0e0029627 100644 --- a/lib/game_interface/interface_component.dart +++ b/lib/game_interface/interface_component.dart @@ -13,7 +13,8 @@ class InterfaceComponent extends GameComponent /// sprite that will be render when pressed Sprite? spriteSelected; - /// Callback used to receive onTab gesture in your component. this return if is selected + /// Callback used to receive onTab gesture in your component. + /// this return if is selected final ValueChanged? onTapComponent; final bool selectable; bool _lastSelected = false; @@ -28,12 +29,16 @@ class InterfaceComponent extends GameComponent this.selectable = false, this.onTapComponent, }) { - loader?.add(AssetToLoad(spriteUnselected, (value) { - this.spriteUnselected = value; - })); - loader?.add(AssetToLoad(spriteSelected, (value) { - this.spriteSelected = value; - })); + loader?.add( + AssetToLoad(spriteUnselected, (value) { + this.spriteUnselected = value; + }), + ); + loader?.add( + AssetToLoad(spriteSelected, (value) { + this.spriteSelected = value; + }), + ); this.position = position; this.size = size; } @@ -46,7 +51,9 @@ class InterfaceComponent extends GameComponent @override void onTapCancel() { - if (selectable) return; + if (selectable) { + return; + } selected = !selected; } diff --git a/lib/game_interface/text_interface_component.dart b/lib/game_interface/text_interface_component.dart index d10b6b94d..369cad921 100644 --- a/lib/game_interface/text_interface_component.dart +++ b/lib/game_interface/text_interface_component.dart @@ -1,23 +1,17 @@ import 'package:bonfire/bonfire.dart'; -import 'package:flutter/widgets.dart'; /// Component used to add Text in your [GameInterface] class TextInterfaceComponent extends InterfaceComponent { String text; - double? _measuredWidth; - double? _measuredHeight; late TextPaint textConfig; TextInterfaceComponent({ - required int id, - required Vector2 position, + required super.id, + required super.position, this.text = '', - ValueChanged? onTapComponent, + super.onTapComponent, TextStyle? textConfig, }) : super( - id: id, - position: position, size: Vector2.zero(), - onTapComponent: onTapComponent, ) { this.textConfig = TextPaint(style: textConfig); } @@ -35,9 +29,10 @@ class TextInterfaceComponent extends InterfaceComponent { @override void update(double dt) { if (size == Vector2.zero()) { - _measuredWidth = textConfig.getLineMetrics(text).width; - _measuredHeight = textConfig.getLineMetrics(text).height; - size = Vector2(_measuredWidth!, _measuredHeight!); + size = Vector2( + textConfig.getLineMetrics(text).width, + textConfig.getLineMetrics(text).height, + ); } super.update(dt); } diff --git a/lib/geometry/circle.dart b/lib/geometry/circle.dart index c51e74932..7143fa57f 100644 --- a/lib/geometry/circle.dart +++ b/lib/geometry/circle.dart @@ -1,10 +1,9 @@ import 'dart:ui'; +import 'package:bonfire/geometry/rectangle.dart'; +import 'package:bonfire/geometry/shape.dart'; import 'package:flame/extensions.dart'; -import 'rectangle.dart'; -import 'shape.dart'; - class CircleShape extends Shape { final double radius; final RectangleShape rect; diff --git a/lib/geometry/polygon.dart b/lib/geometry/polygon.dart index 7ca268560..314be578b 100644 --- a/lib/geometry/polygon.dart +++ b/lib/geometry/polygon.dart @@ -37,12 +37,12 @@ class PolygonShape extends Shape { double height = 0; double width = 0; - double minX = relativePoints.first.x; - double maxX = relativePoints.first.x; + var minX = relativePoints.first.x; + var maxX = relativePoints.first.x; - double minY = relativePoints.first.y; - double maxY = relativePoints.first.y; - for (var offset in relativePoints) { + var minY = relativePoints.first.y; + var maxY = relativePoints.first.y; + for (final offset in relativePoints) { if (offset.x < minX) { minX = offset.x; } diff --git a/lib/geometry/shape_collision.dart b/lib/geometry/shape_collision.dart index 1960698f7..3dd39350e 100644 --- a/lib/geometry/shape_collision.dart +++ b/lib/geometry/shape_collision.dart @@ -1,12 +1,11 @@ import 'dart:math'; +import 'package:bonfire/geometry/circle.dart'; +import 'package:bonfire/geometry/polygon.dart'; +import 'package:bonfire/geometry/rectangle.dart'; +import 'package:bonfire/geometry/shape.dart'; import 'package:flame/extensions.dart'; -import 'circle.dart'; -import 'polygon.dart'; -import 'rectangle.dart'; -import 'shape.dart'; - /// Class responsible to verify collision of the Shapes. /// Code based from: https://github.com/hahafather007/collision_check class ShapeCollision { @@ -49,7 +48,9 @@ class ShapeCollision { } static bool rectToCircle(RectangleShape a, CircleShape b) { - if (!rectToRect(a, b.rect)) return false; + if (!rectToRect(a, b.rect)) { + return false; + } final points = [ a.leftTop, @@ -60,21 +61,27 @@ class ShapeCollision { ]; for (var i = 0; i < points.length - 1; i++) { final distance = getNearestDistance(points[i], points[i + 1], b.center); - if (_getFixDouble(distance) <= b.radius) return true; + if (_getFixDouble(distance) <= b.radius) { + return true; + } } return false; } static bool rectToPolygon(RectangleShape a, PolygonShape b) { - if (!rectToRect(a, b.rect)) return false; + if (!rectToRect(a, b.rect)) { + return false; + } if (!isLinesShadowOver( a.leftTop, a.rightBottom, b.rect.leftTop, b.rect.rightBottom, - )) return false; + )) { + return false; + } if (polygonPoint(b, a.position)) { return true; @@ -110,7 +117,9 @@ class ShapeCollision { } static bool circleToCircle(CircleShape a, CircleShape b) { - if (!rectToRect(a.rect, b.rect)) return false; + if (!rectToRect(a.rect, b.rect)) { + return false; + } final distance = a.radius + b.radius; final w = a.center.x - b.center.x; @@ -120,7 +129,9 @@ class ShapeCollision { } static bool circleToPolygon(CircleShape a, PolygonShape b) { - if (!rectToRect(a.rect, b.rect)) return false; + if (!rectToRect(a.rect, b.rect)) { + return false; + } if (b.points.isNotEmpty) { final points = b.points.toList(); @@ -137,7 +148,9 @@ class ShapeCollision { } static bool polygonToPolygon(PolygonShape a, PolygonShape b) { - if (!rectToRect(a.rect, b.rect)) return false; + if (!rectToRect(a.rect, b.rect)) { + return false; + } final pointsA = a.points.toList()..add(a.points.first); final pointsB = b.points.toList()..add(b.points.first); @@ -146,7 +159,11 @@ class ShapeCollision { final pointB = pointsA[i + 1]; if (!isLinesShadowOver( - pointA, pointB, b.rect.leftTop, b.rect.rightBottom)) { + pointA, + pointB, + b.rect.leftTop, + b.rect.rightBottom, + )) { continue; } @@ -170,14 +187,20 @@ class ShapeCollision { /// Get [o] point distance [o1] and [o2] line segment distance /// https://blog.csdn.net/yjukh/article/details/5213577 static double getNearestDistance(Vector2 o1, Vector2 o2, Vector2 o) { - if (o1 == o || o2 == o) return 0; + if (o1 == o || o2 == o) { + return 0; + } final a = o2.distanceTo(o); final b = o1.distanceTo(o); final c = o1.distanceTo(o2); - if (a * a >= b * b + c * c) return b; - if (b * b >= a * a + c * c) return a; + if (a * a >= b * b + c * c) { + return b; + } + if (b * b >= a * a + c * c) { + return a; + } // 海伦公式 final l = (a + b + c) / 2; @@ -229,22 +252,24 @@ class ShapeCollision { // only needed if you're going to check if the rectangle // is INSIDE the polygon static bool polygonPoint(PolygonShape b, Vector2 point) { - bool collision = false; + var collision = false; // go through each of the vertices, plus the next // vertex in the list - List vertices = b.points; - int next = 0; - for (int current = 0; current < vertices.length; current++) { + final vertices = b.points; + var next = 0; + for (var current = 0; current < vertices.length; current++) { // get next vertex in list // if we've hit the end, wrap around to 0 next = current + 1; - if (next == vertices.length) next = 0; + if (next == vertices.length) { + next = 0; + } // get the PVectors at our current position // this makes our if statement a little cleaner - Vector2 vc = vertices[current]; // c for "current" - Vector2 vn = vertices[next]; // n for "next" + final vc = vertices[current]; // c for "current" + final vn = vertices[next]; // n for "next" // compare position, flip 'collision' variable // back and forth diff --git a/lib/input/gestures/drag_gesture.dart b/lib/input/gestures/drag_gesture.dart index fa4e059f8..053cd0779 100644 --- a/lib/input/gestures/drag_gesture.dart +++ b/lib/input/gestures/drag_gesture.dart @@ -19,7 +19,7 @@ mixin DragGesture on GameComponent { screenToWorld: gameRef.screenToWorld, globalToViewportPosition: gameRef.globalToViewportPosition, ); - bool handler = false; + var handler = false; if (enableDrag && hasGameRef) { if (isHud) { @@ -49,7 +49,7 @@ mixin DragGesture on GameComponent { screenToWorld: gameRef.screenToWorld, globalToViewportPosition: gameRef.globalToViewportPosition, ); - bool canMove = hasGameRef && + final canMove = hasGameRef && _startDragPosition != null && enableDrag && gEvent.pointer == _pointer; diff --git a/lib/input/gestures/move_camera_using_gestures.dart b/lib/input/gestures/move_camera_using_gestures.dart index 9743cf951..826a8a536 100644 --- a/lib/input/gestures/move_camera_using_gestures.dart +++ b/lib/input/gestures/move_camera_using_gestures.dart @@ -25,12 +25,12 @@ mixin MoveCameraUsingGesture on GameComponent { @override bool handlerPointerMove(PointerMoveEvent event) { - double distance = _startPoint.distanceTo(event.position.toVector2()); + final distance = _startPoint.distanceTo(event.position.toVector2()); if (distance > 1) { if (_acceptGesture(event, _mouseButton)) { - double zoom = gameRef.camera.zoom; - double px = _startPoint.x - event.position.dx; - double py = _startPoint.y - event.position.dy; + final zoom = gameRef.camera.zoom; + final px = _startPoint.x - event.position.dx; + final py = _startPoint.y - event.position.dy; gameRef.camera.stop(); gameRef.camera.moveTo( _startCameraPosition.translated( @@ -45,7 +45,7 @@ mixin MoveCameraUsingGesture on GameComponent { } bool _acceptGesture(PointerEvent event, MouseButton button) { - bool isMouse = event.kind == PointerDeviceKind.mouse; + final isMouse = event.kind == PointerDeviceKind.mouse; if (_onlyMouse) { return event.buttons == button.id && isMouse; diff --git a/lib/input/gestures/pinch_gesture.dart b/lib/input/gestures/pinch_gesture.dart index ae120409f..b2803f480 100644 --- a/lib/input/gestures/pinch_gesture.dart +++ b/lib/input/gestures/pinch_gesture.dart @@ -27,7 +27,7 @@ mixin PinchGesture on GameComponent { screenToWorld: gameRef.screenToWorld, globalToViewportPosition: gameRef.globalToViewportPosition, ); - if (!_fingers.contains(event.pointer)) { + if (!_fingers.any((element) => element.id == gEvent.pointer)) { _fingers.add( FingerPoint( id: gEvent.pointer, @@ -74,7 +74,7 @@ mixin PinchGesture on GameComponent { bool get isVisible => true; void _updateFingers(GestureEvent event) { - for (var finger in _fingers) { + for (final finger in _fingers) { if (finger.id == event.pointer) { finger.position.setFrom(event.screenPosition); } @@ -125,11 +125,11 @@ class PinchEvent { }); factory PinchEvent.fromFingers(FingerPoint f1, FingerPoint f2) { - final Vector2 initialPosition = Vector2( + final initialPosition = Vector2( min(f1.initialPosition.x, f2.initialPosition.x), min(f1.initialPosition.y, f2.initialPosition.y), ); - final Vector2 position = Vector2( + final position = Vector2( min(f1.position.x, f2.position.x), min(f1.position.y, f2.position.y), ); diff --git a/lib/input/gestures/tap_gesture.dart b/lib/input/gestures/tap_gesture.dart index abc4a2af6..825affa5b 100644 --- a/lib/input/gestures/tap_gesture.dart +++ b/lib/input/gestures/tap_gesture.dart @@ -11,7 +11,7 @@ mixin TapGesture on GameComponent { screenToWorld: gameRef.screenToWorld, globalToViewportPosition: gameRef.globalToViewportPosition, ); - bool handler = false; + var handler = false; if (enableTab && hasGameRef) { onTapDownScreen(tapEvent); diff --git a/lib/input/input.dart b/lib/input/input.dart index 59a96b1d1..410a6394c 100644 --- a/lib/input/input.dart +++ b/lib/input/input.dart @@ -1,7 +1,7 @@ export 'package:bonfire/input/gestures/drag_gesture.dart'; export 'package:bonfire/input/gestures/gesture_event.dart'; +export 'package:bonfire/input/gestures/pinch_gesture.dart'; export 'package:bonfire/input/gestures/tap_gesture.dart'; -export 'package:bonfire/input/keyboard/keyboard_listener.dart'; export 'package:bonfire/input/keyboard/keyboard.dart'; +export 'package:bonfire/input/keyboard/keyboard_listener.dart'; export 'package:bonfire/input/mouse_listener.dart'; -export 'package:bonfire/input/gestures/pinch_gesture.dart'; diff --git a/lib/input/keyboard/keyboard.dart b/lib/input/keyboard/keyboard.dart index 3fe0e16e6..2fb1b2d00 100644 --- a/lib/input/keyboard/keyboard.dart +++ b/lib/input/keyboard/keyboard.dart @@ -23,7 +23,9 @@ class Keyboard extends PlayerController with KeyboardEventListener { @override bool onKeyboard(KeyEvent event, Set keysPressed) { /// If the keyboard is disabled, we do not process the event - if (!keyboardConfig.enable) return false; + if (!keyboardConfig.enable) { + return false; + } /// If the key is not accepted, we do not process the event if (keyboardConfig.acceptedKeys != null) { @@ -40,8 +42,6 @@ class Keyboard extends PlayerController with KeyboardEventListener { onJoystickChangeDirectional( JoystickDirectionalEvent( directional: JoystickMoveDirectional.IDLE, - intensity: 0.0, - radAngle: 0.0, ), ); } @@ -113,83 +113,89 @@ class Keyboard extends PlayerController with KeyboardEventListener { JoystickDirectionalEvent( directional: JoystickMoveDirectional.MOVE_UP, intensity: 1.0, - radAngle: 0.0, isKeyboard: true, ), ); } if (isDownPressed(key)) { - onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_DOWN, - intensity: 1.0, - radAngle: 0.0, - isKeyboard: true, - )); + onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_DOWN, + intensity: 1.0, + isKeyboard: true, + ), + ); } if (isLeftPressed(key)) { - onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_LEFT, - intensity: 1.0, - radAngle: 0.0, - isKeyboard: true, - )); + onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_LEFT, + intensity: 1.0, + isKeyboard: true, + ), + ); } if (isRightPressed(key)) { - onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_RIGHT, - intensity: 1.0, - radAngle: 0.0, - isKeyboard: true, - )); + onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_RIGHT, + intensity: 1.0, + isKeyboard: true, + ), + ); } } void _sendTwoDirection(LogicalKeyboardKey key1, LogicalKeyboardKey key2) { if (isRightPressed(key1) && isDownPressed(key2) || isDownPressed(key1) && isRightPressed(key2)) { - onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_DOWN_RIGHT, - intensity: 1.0, - radAngle: 0.0, - isKeyboard: true, - )); + onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_DOWN_RIGHT, + intensity: 1.0, + isKeyboard: true, + ), + ); } if (isLeftPressed(key1) && isDownPressed(key2) || isDownPressed(key1) && isLeftPressed(key2)) { - onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_DOWN_LEFT, - intensity: 1.0, - radAngle: 0.0, - isKeyboard: true, - )); + onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_DOWN_LEFT, + intensity: 1.0, + isKeyboard: true, + ), + ); } if (isLeftPressed(key1) && isUpPressed(key2) || isUpPressed(key1) && isLeftPressed(key2)) { - onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_UP_LEFT, - intensity: 1.0, - radAngle: 0.0, - isKeyboard: true, - )); + onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_UP_LEFT, + intensity: 1.0, + isKeyboard: true, + ), + ); } if (isRightPressed(key1) && isUpPressed(key2) || isUpPressed(key1) && isRightPressed(key2)) { - onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_UP_RIGHT, - intensity: 1.0, - radAngle: 0.0, - isKeyboard: true, - )); + onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_UP_RIGHT, + intensity: 1.0, + isKeyboard: true, + ), + ); } } bool _containDirectionalPressed(Set keysPressed) { - for (var element in keysPressed) { + for (final element in keysPressed) { if (_isDirectional(element)) { return true; } diff --git a/lib/input/mouse_listener.dart b/lib/input/mouse_listener.dart index fbeab41df..417d8b74a 100644 --- a/lib/input/mouse_listener.dart +++ b/lib/input/mouse_listener.dart @@ -24,7 +24,10 @@ mixin MouseEventListener on GameComponent { /// Listen when use scroll of the mouse across the screen void onMouseScrollScreen( - int pointer, Vector2 position, Vector2 scrollDelta) {} + int pointer, + Vector2 position, + Vector2 scrollDelta, + ) {} /// Listen when use scroll of the mouse in your component void onMouseScroll(int pointer, Vector2 position, Vector2 scrollDelta) {} @@ -42,8 +45,8 @@ mixin MouseEventListener on GameComponent { @override bool handlerPointerMove(PointerMoveEvent event) { if (event.kind == PointerDeviceKind.mouse) { - int pointer = event.pointer; - Vector2 position = event.localPosition.toVector2(); + final pointer = event.pointer; + final position = event.localPosition.toVector2(); onMouseMoveScreen(pointer, position, _getMouseButtonByInt(event.buttons)); } return super.handlerPointerMove(event); @@ -54,9 +57,9 @@ mixin MouseEventListener on GameComponent { if (!enableMouseGesture) { return super.handlerPointerHover(event); } - int pointer = event.pointer; - Vector2 position = event.localPosition.toVector2(); - Vector2 realPosition = position; + final pointer = event.pointer; + final position = event.localPosition.toVector2(); + var realPosition = position; if (!isHud) { realPosition = gameRef.screenToWorld(realPosition); } @@ -78,13 +81,13 @@ mixin MouseEventListener on GameComponent { if (!enableMouseGesture) { return super.handlerPointerSignal(event); } - int pointer = event.pointer; - Vector2 position = event.localPosition.toVector2(); - Vector2 realPosition = event.localPosition.toVector2(); + final pointer = event.pointer; + final position = event.localPosition.toVector2(); + var realPosition = event.localPosition.toVector2(); if (!isHud) { realPosition = gameRef.screenToWorld(realPosition); } - Vector2 scrollDelta = (event as PointerScrollEvent).scrollDelta.toVector2(); + final scrollDelta = (event as PointerScrollEvent).scrollDelta.toVector2(); onMouseScrollScreen(pointer, position, scrollDelta); if (containsPoint(realPosition)) { onMouseScroll(pointer, position, scrollDelta); @@ -125,7 +128,7 @@ mixin MouseEventListener on GameComponent { // Listen when mouse is clicked down in screen void onMouseScreenTapDown(int pointer, Vector2 position, MouseButton button) { - Vector2 realPosition = position; + var realPosition = position; if (!isHud) { realPosition = gameRef.screenToWorld(realPosition); } @@ -138,7 +141,7 @@ mixin MouseEventListener on GameComponent { // Listen when mouse is clicked up in screen void onMouseScreenTapUp(int pointer, Vector2 position) { - Vector2 realPosition = position; + var realPosition = position; if (!isHud) { realPosition = gameRef.screenToWorld(realPosition); } diff --git a/lib/input/player_controller.dart b/lib/input/player_controller.dart index e6ce4967c..b518fb52c 100644 --- a/lib/input/player_controller.dart +++ b/lib/input/player_controller.dart @@ -58,10 +58,10 @@ class JoystickActionEvent { final ActionEvent event; JoystickActionEvent({ + required this.event, this.id, this.intensity = 0.0, this.radAngle = 0.0, - required this.event, }); } @@ -83,14 +83,14 @@ abstract class PlayerController extends GameComponent @override void onJoystickChangeDirectional(JoystickDirectionalEvent event) { - for (var o in _observers) { + for (final o in _observers) { o.onJoystickChangeDirectional(event); } } @override void onJoystickAction(JoystickActionEvent event) { - for (var o in _observers) { + for (final o in _observers) { o.onJoystickAction(event); } } diff --git a/lib/joystick/joystick.dart b/lib/joystick/joystick.dart index 7406728b7..2ed1c68bb 100644 --- a/lib/joystick/joystick.dart +++ b/lib/joystick/joystick.dart @@ -21,10 +21,12 @@ class Joystick extends PlayerController { } } - void initialize(Vector2 size) async { - if (!hasGameRef) return; + void initialize(Vector2 size) { + if (!hasGameRef) { + return; + } directional?.initialize(this, gameRef.camera.viewport); - for (var action in actions) { + for (final action in actions) { action.initialize(this, gameRef.camera.viewport); } } @@ -49,7 +51,7 @@ class Joystick extends PlayerController { void render(Canvas canvas) { super.render(canvas); directional?.render(canvas); - for (JoystickAction action in actions) { + for (final action in actions) { action.render(canvas); } } @@ -57,7 +59,7 @@ class Joystick extends PlayerController { @override void update(double dt) { directional?.update(dt); - for (JoystickAction action in actions) { + for (final action in actions) { action.update(dt); } super.update(dt); @@ -65,7 +67,7 @@ class Joystick extends PlayerController { @override bool handlerPointerCancel(PointerCancelEvent event) { - for (JoystickAction action in actions) { + for (final action in actions) { action.actionUp(event.pointer); } directional?.directionalUp(event.pointer); @@ -75,7 +77,7 @@ class Joystick extends PlayerController { @override bool handlerPointerDown(PointerDownEvent event) { directional?.directionalDown(event.pointer, event.localPosition); - for (JoystickAction action in actions) { + for (final action in actions) { action.actionDown(event.pointer, event.localPosition); } return super.handlerPointerDown(event); @@ -83,7 +85,7 @@ class Joystick extends PlayerController { @override bool handlerPointerMove(PointerMoveEvent event) { - for (JoystickAction action in actions) { + for (final action in actions) { action.actionMove(event.pointer, event.localPosition); } directional?.directionalMove(event.pointer, event.localPosition); @@ -92,7 +94,7 @@ class Joystick extends PlayerController { @override bool handlerPointerUp(PointerUpEvent event) { - for (JoystickAction action in actions) { + for (final action in actions) { action.actionUp(event.pointer); } directional?.directionalUp(event.pointer); @@ -115,7 +117,7 @@ class Joystick extends PlayerController { Future onLoad() async { await super.onLoad(); await directional?.onLoad(); - for (var ac in actions) { + for (final ac in actions) { await ac.onLoad(); } } diff --git a/lib/joystick/joystick_action.dart b/lib/joystick/joystick_action.dart index bac16dca9..f8b3157e8 100644 --- a/lib/joystick/joystick_action.dart +++ b/lib/joystick/joystick_action.dart @@ -1,6 +1,7 @@ import 'dart:math'; import 'package:bonfire/bonfire.dart'; +import 'package:bonfire/util/extensions/color_extensions.dart'; import 'package:flame/camera.dart' as camera; import 'package:flutter/material.dart'; @@ -51,15 +52,18 @@ class JoystickAction { this.opacityBackground = 0.5, this.opacityKnob = 0.8, }) { - _loader?.add(AssetToLoad(sprite, (value) { - this.sprite = value; - })); - _loader?.add(AssetToLoad(spritePressed, (value) { - this.spritePressed = value; - })); - _loader?.add(AssetToLoad(spriteBackgroundDirection, (value) { - this.spriteBackgroundDirection = value; - })); + _loader?.add( + AssetToLoad(sprite, (value) => this.sprite = value), + ); + _loader?.add( + AssetToLoad(spritePressed, (value) => this.spritePressed = value), + ); + _loader?.add( + AssetToLoad( + spriteBackgroundDirection, + (value) => this.spriteBackgroundDirection = value, + ), + ); _sizeBackgroundDirection = sizeFactorBackgroundDirection * size; _tileSize = _sizeBackgroundDirection / 2; } @@ -72,11 +76,13 @@ class JoystickAction { PlayerControllerListener controller, camera.Viewport viewport, ) { - if (_screenSize == viewport.virtualSize) return; + if (_screenSize == viewport.virtualSize) { + return; + } _viewport = viewport; _screenSize = viewport.virtualSize.clone(); _controller = controller; - double radius = size / 2; + final radius = size / 2; final screenRect = Rect.fromLTRB( margin.left + radius, margin.top + radius, @@ -84,7 +90,7 @@ class JoystickAction { _screenSize.y - margin.bottom - radius, ); - Offset osBackground = alignment.withinRect(screenRect); + final osBackground = alignment.withinRect(screenRect); _rect = Rect.fromCircle( center: osBackground, radius: radius, @@ -102,7 +108,7 @@ class JoystickAction { if (_rectBackgroundDirection != null && _dragging && enableDirection) { if (spriteBackgroundDirection == null) { _paintBackground?.let((paintBackground) { - double radiusBackground = _rectBackgroundDirection!.width / 2; + final radiusBackground = _rectBackgroundDirection!.width / 2; c.drawCircle( Offset( _rectBackgroundDirection!.left + radiusBackground, @@ -127,7 +133,7 @@ class JoystickAction { rect, ); } else { - double radiusAction = rect.width / 2; + final radiusAction = rect.width / 2; c.drawCircle( Offset( rect.left + radiusAction, @@ -143,17 +149,19 @@ class JoystickAction { void update(double dt) { if (_dragPosition == null || _rectBackgroundDirection == null || - _rect == null) return; + _rect == null) { + return; + } if (_dragging) { - double radAngle = atan2( + final radAngle = atan2( _dragPosition!.dy - _rectBackgroundDirection!.center.dy, _dragPosition!.dx - _rectBackgroundDirection!.center.dx, ); // Distance between the center of joystick background & drag position - Vector2 centerPosition = _rectBackgroundDirection!.center.toVector2(); - Vector2 dragPosition = _dragPosition!.toVector2(); - double dist = centerPosition.distanceTo(dragPosition); + final centerPosition = _rectBackgroundDirection!.center.toVector2(); + final dragPosition = _dragPosition!.toVector2(); + var dist = centerPosition.distanceTo(dragPosition); // The maximum distance for the knob position the edge of // the background + half of its own size. The knob can wander in the @@ -161,18 +169,18 @@ class JoystickAction { dist = min(dist, _tileSize); // Calculation the knob position - double nextX = dist * cos(radAngle); - double nextY = dist * sin(radAngle); - Offset nextPoint = Offset(nextX, nextY); + final nextX = dist * cos(radAngle); + final nextY = dist * sin(radAngle); + final nextPoint = Offset(nextX, nextY); - Offset diff = Offset( + final diff = Offset( _rectBackgroundDirection!.center.dx + nextPoint.dx, _rectBackgroundDirection!.center.dy + nextPoint.dy, ) - _rect!.center; _rect = _rect!.shift(diff); - double intensity = dist / _tileSize; + final intensity = dist / _tileSize; _controller.onJoystickAction( JoystickActionEvent( @@ -183,7 +191,7 @@ class JoystickAction { ), ); } else { - Offset diff = _dragPosition! - _rect!.center; + final diff = _dragPosition! - _rect!.center; _rect = _rect!.shift(diff); } } @@ -251,19 +259,19 @@ class JoystickAction { if (spriteBackgroundDirection == null) { _paintBackground = Paint() - ..color = color.withOpacity(opacityBackground) + ..color = color.setOpacity(opacityBackground) ..style = PaintingStyle.fill; } if (sprite == null) { _paintAction = Paint() - ..color = color.withOpacity(opacityKnob) + ..color = color.setOpacity(opacityKnob) ..style = PaintingStyle.fill; } if (spritePressed == null) { _paintActionPressed = Paint() - ..color = color.withOpacity(opacityBackground) + ..color = color.setOpacity(opacityBackground) ..style = PaintingStyle.fill; } diff --git a/lib/joystick/joystick_directional.dart b/lib/joystick/joystick_directional.dart index 22bfe60ff..12a75f6c1 100644 --- a/lib/joystick/joystick_directional.dart +++ b/lib/joystick/joystick_directional.dart @@ -1,6 +1,7 @@ import 'dart:math'; import 'package:bonfire/bonfire.dart'; +import 'package:bonfire/util/extensions/color_extensions.dart'; import 'package:flame/camera.dart' as camera; import 'package:flutter/material.dart'; @@ -49,13 +50,17 @@ class JoystickDirectional { this.color = Colors.blueGrey, this.enableDiagonalInput = true, }) { - _loader?.add(AssetToLoad(spriteBackgroundDirectional, (value) { - _backgroundSprite = value; - })); + _loader?.add( + AssetToLoad(spriteBackgroundDirectional, (value) { + _backgroundSprite = value; + }), + ); - _loader?.add(AssetToLoad(spriteKnobDirectional, (value) { - _knobSprite = value; - })); + _loader?.add( + AssetToLoad(spriteKnobDirectional, (value) { + _knobSprite = value; + }), + ); _tileSize = size / 2; } @@ -68,7 +73,9 @@ class JoystickDirectional { PlayerControllerListener controller, camera.Viewport viewPort, ) { - if (_screenSize == viewPort.virtualSize) return; + if (_screenSize == viewPort.virtualSize) { + return; + } _viewPort = viewPort; _screenSize = viewPort.virtualSize.clone(); _controller = controller; @@ -81,14 +88,14 @@ class JoystickDirectional { _screenSize.y - margin.bottom - radius, ); - Offset osBackground = alignment.withinRect(screenRect); + final osBackground = alignment.withinRect(screenRect); _backgroundRect = Rect.fromCircle( center: osBackground, radius: radius, ); - Offset osKnob = Offset( + final osKnob = Offset( _backgroundRect!.center.dx, _backgroundRect!.center.dy, ); @@ -110,10 +117,12 @@ class JoystickDirectional { ); } else { _paintBackground?.let((paintBg) { - double radiusBackground = background.width / 2; + final radiusBackground = background.width / 2; canvas.drawCircle( - Offset(background.left + radiusBackground, - background.top + radiusBackground), + Offset( + background.left + radiusBackground, + background.top + radiusBackground, + ), radiusBackground, paintBg, ); @@ -126,7 +135,7 @@ class JoystickDirectional { _knobSprite?.renderRect(canvas, knobRect); } else { _paintKnob?.let((paintKnob) { - double radiusKnob = knobRect.width / 2; + final radiusKnob = knobRect.width / 2; canvas.drawCircle( Offset( knobRect.left + radiusKnob, @@ -146,17 +155,17 @@ class JoystickDirectional { } if (_dragging) { - double radAngle = atan2( + final radAngle = atan2( _dragPosition!.dy - _backgroundRect!.center.dy, _dragPosition!.dx - _backgroundRect!.center.dx, ); - double degrees = radAngle * 180 / pi; + final degrees = radAngle * 180 / pi; // Distance between the center of joystick background & drag position - Vector2 centerPosition = _backgroundRect!.center.toVector2(); - Vector2 dragPosition = _dragPosition!.toVector2(); - double dist = centerPosition.distanceTo(dragPosition); + final centerPosition = _backgroundRect!.center.toVector2(); + final dragPosition = _dragPosition!.toVector2(); + var dist = centerPosition.distanceTo(dragPosition); // The maximum distance for the knob position the edge of // the background + half of its own size. The knob can wander in the @@ -164,109 +173,129 @@ class JoystickDirectional { dist = min(dist, _tileSize); // Calculation the knob position - double nextX = dist * cos(radAngle); - double nextY = dist * sin(radAngle); - Offset nextPoint = Offset(nextX, nextY); + final nextX = dist * cos(radAngle); + final nextY = dist * sin(radAngle); + final nextPoint = Offset(nextX, nextY); - Offset diff = Offset( + final diff = Offset( _backgroundRect!.center.dx + nextPoint.dx, _backgroundRect!.center.dy + nextPoint.dy, ) - _knobRect!.center; _knobRect = _knobRect!.shift(diff); - double intensity = dist / _tileSize; + final intensity = dist / _tileSize; if (intensity == 0) { - _controller.onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.IDLE, - intensity: intensity, - radAngle: radAngle, - )); + _controller.onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.IDLE, + intensity: intensity, + radAngle: radAngle, + ), + ); return; } if (degrees > -22.5 && degrees <= 22.5) { - _controller.onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_RIGHT, - intensity: intensity, - radAngle: radAngle, - )); + _controller.onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_RIGHT, + intensity: intensity, + radAngle: radAngle, + ), + ); } if (enableDiagonalInput && degrees > 22.5 && degrees <= 67.5) { - _controller.onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_DOWN_RIGHT, - intensity: intensity, - radAngle: radAngle, - )); + _controller.onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_DOWN_RIGHT, + intensity: intensity, + radAngle: radAngle, + ), + ); } if (degrees > 67.5 && degrees <= 112.5) { - _controller.onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_DOWN, - intensity: intensity, - radAngle: radAngle, - )); + _controller.onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_DOWN, + intensity: intensity, + radAngle: radAngle, + ), + ); } if (enableDiagonalInput && degrees > 112.5 && degrees <= 157.5) { - _controller.onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_DOWN_LEFT, - intensity: intensity, - radAngle: radAngle, - )); + _controller.onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_DOWN_LEFT, + intensity: intensity, + radAngle: radAngle, + ), + ); } if ((degrees > 157.5 && degrees <= 180) || (degrees >= -180 && degrees <= -157.5)) { - _controller.onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_LEFT, - intensity: intensity, - radAngle: radAngle, - )); + _controller.onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_LEFT, + intensity: intensity, + radAngle: radAngle, + ), + ); } if (enableDiagonalInput && degrees > -157.5 && degrees <= -112.5) { - _controller.onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_UP_LEFT, - intensity: intensity, - radAngle: radAngle, - )); + _controller.onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_UP_LEFT, + intensity: intensity, + radAngle: radAngle, + ), + ); } if (degrees > -112.5 && degrees <= -67.5) { - _controller.onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_UP, - intensity: intensity, - radAngle: radAngle, - )); + _controller.onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_UP, + intensity: intensity, + radAngle: radAngle, + ), + ); } if (enableDiagonalInput && degrees > -67.5 && degrees <= -22.5) { - _controller.onJoystickChangeDirectional(JoystickDirectionalEvent( - directional: JoystickMoveDirectional.MOVE_UP_RIGHT, - intensity: intensity, - radAngle: radAngle, - )); + _controller.onJoystickChangeDirectional( + JoystickDirectionalEvent( + directional: JoystickMoveDirectional.MOVE_UP_RIGHT, + intensity: intensity, + radAngle: radAngle, + ), + ); } } else { if (_knobRect != null) { - Offset diff = _dragPosition! - _knobRect!.center; + final diff = _dragPosition! - _knobRect!.center; _knobRect = _knobRect!.shift(diff); } } } void directionalDown(int pointer, Offset localPosition) { - if (_backgroundRect == null) return; + if (_backgroundRect == null) { + return; + } final pos = getViewportPosition(localPosition); _updateDirectionalRect(pos); _backgroundRect?.let((backgroundRect) { - Rect directional = Rect.fromLTWH( + final directional = Rect.fromLTWH( backgroundRect.left - 50, backgroundRect.top - 50, backgroundRect.width + 100, @@ -297,15 +326,15 @@ class JoystickDirectional { _controller.onJoystickChangeDirectional( JoystickDirectionalEvent( directional: JoystickMoveDirectional.IDLE, - intensity: 0.0, - radAngle: 0.0, ), ); } } void _updateDirectionalRect(Offset position) { - if (isFixed) return; + if (isFixed) { + return; + } if (alignment.x == -1) { if (position.dx > _screenSize.x * 0.33) { return; @@ -323,7 +352,7 @@ class JoystickDirectional { radius: size / 2, ); - Offset osKnob = Offset( + final osKnob = Offset( _backgroundRect!.center.dx, _backgroundRect!.center.dy, ); @@ -337,12 +366,12 @@ class JoystickDirectional { await _loader?.load(); if (_backgroundSprite == null) { _paintBackground = Paint() - ..color = color.withOpacity(0.5) + ..color = color.setOpacity(0.5) ..style = PaintingStyle.fill; } _paintKnob ??= Paint() - ..color = color.withOpacity(0.8) + ..color = color.setOpacity(0.8) ..style = PaintingStyle.fill; _loader = null; diff --git a/lib/joystick/joystick_map_explorer.dart b/lib/joystick/joystick_map_explorer.dart index 4b7825f5e..ba4acda17 100644 --- a/lib/joystick/joystick_map_explorer.dart +++ b/lib/joystick/joystick_map_explorer.dart @@ -1,7 +1,6 @@ +import 'package:bonfire/bonfire.dart'; import 'package:bonfire/camera/bonfire_camera.dart'; -import '../bonfire.dart'; - class JoystickMapExplorer with PlayerControllerListener { final BonfireCamera camera; @@ -12,7 +11,7 @@ class JoystickMapExplorer with PlayerControllerListener { @override void onJoystickChangeDirectional(JoystickDirectionalEvent event) { - double speed = 4 * event.intensity; + final speed = 4 * event.intensity; switch (event.directional) { case JoystickMoveDirectional.MOVE_UP: diff --git a/lib/lighting/lighting.dart b/lib/lighting/lighting.dart index ead526b7b..ff67e18e0 100644 --- a/lib/lighting/lighting.dart +++ b/lib/lighting/lighting.dart @@ -19,7 +19,7 @@ mixin Lighting on GameComponent { double _lightingAngle() { if (_lightingConfig != null && _lightingConfig?.type is ArcLightingType) { - var type = _lightingConfig?.type as ArcLightingType; + final type = _lightingConfig!.type as ArcLightingType; if (type.isCenter) { return this.angle - (type.endRadAngle / 2); } else { diff --git a/lib/lighting/lighting_component.dart b/lib/lighting/lighting_component.dart index 572bfd89c..0671991d0 100644 --- a/lib/lighting/lighting_component.dart +++ b/lib/lighting/lighting_component.dart @@ -54,18 +54,22 @@ class LightingComponent extends GameComponent implements LightingInterface { @override void renderTree(Canvas canvas) { - if (!_containColor) return; + if (!_containColor) { + return; + } canvas.saveLayer(bounds, paint); canvas.drawColor(color!, BlendMode.dstATop); - for (var light in _visibleLight) { + for (final light in _visibleLight) { final config = light.lightingConfig; - if (config == null || !light.lightingEnabled) continue; + if (config == null || !light.lightingEnabled) { + continue; + } config.update(_dtUpdate); canvas.save(); canvas.scale(gameRef.camera.zoom); final tl = gameRef.camera.topleft; - canvas.translate(-(tl.x), -(tl.y)); + canvas.translate(-tl.x, -tl.y); if (config.type is CircleLightingType) { _drawCircle(canvas, light); @@ -117,9 +121,9 @@ class LightingComponent extends GameComponent implements LightingInterface { } void _drawArc(Canvas canvas, Lighting light) { - var config = light.lightingConfig!; - var type = config.type as ArcLightingType; - Offset offset = (light.absoluteCenter + config.align).toOffset(); + final config = light.lightingConfig!; + final type = config.type as ArcLightingType; + final offset = (light.absoluteCenter + config.align).toOffset(); canvas.save(); @@ -165,8 +169,8 @@ class LightingComponent extends GameComponent implements LightingInterface { } void _drawCircle(Canvas canvas, Lighting light) { - var config = light.lightingConfig!; - Offset offset = (light.absoluteCenter + config.align).toOffset(); + final config = light.lightingConfig!; + final offset = (light.absoluteCenter + config.align).toOffset(); canvas.drawCircle( offset, diff --git a/lib/map/base/tile.dart b/lib/map/base/tile.dart index 33fe38d39..c9ae421fa 100644 --- a/lib/map/base/tile.dart +++ b/lib/map/base/tile.dart @@ -38,9 +38,15 @@ class TileSprite { factory TileSprite.fromMap(Map map) { return TileSprite( - path: map['path'], - position: Vector2(map['column'], map['row']), - size: Vector2(map['width'], map['height']), + path: map['path'].toString(), + position: Vector2( + double.parse(map['column'].toString()), + double.parse(map['row'].toString()), + ), + size: Vector2( + double.parse(map['width'].toString()), + double.parse(map['height'].toString()), + ), ); } @@ -74,10 +80,10 @@ class TilelAnimation { factory TilelAnimation.fromMap(Map map) { return TilelAnimation( - stepTime: map['stepTime'], + stepTime: double.parse(map['stepTime'].toString()), frames: map['frames'] != null ? (map['frames'] as List).map((e) { - return TileSprite.fromMap(e); + return TileSprite.fromMap((e as Map).cast()); }).toList() : [], ); @@ -113,10 +119,10 @@ class Tile { Tile({ required this.x, required this.y, - this.offsetX = 0.0, - this.offsetY = 0.0, required this.width, required this.height, + this.offsetX = 0.0, + this.offsetY = 0.0, this.tileClass, this.properties, this.sprite, @@ -130,9 +136,9 @@ class Tile { }) { id = '$x/$y:${DateTime.now().microsecondsSinceEpoch}'; } - double get left => (x * width); + double get left => x * width; double get right => (x * width) + width; - double get top => (y * height); + double get top => y * height; double get bottom => (y * height) + height; TileComponent getTile() { @@ -168,8 +174,7 @@ class Tile { } } else { if (collisions?.isNotEmpty == true) { - ControlledUpdateAnimation animationControlled = - animation!.getSpriteControlledAnimation(); + final animationControlled = animation!.getSpriteControlledAnimation(); final tile = TileWithCollision.withAnimation( animation: animationControlled, position: Vector2(x, y), @@ -184,8 +189,7 @@ class Tile { return tile; } else { - ControlledUpdateAnimation animationControlled = - animation!.getSpriteControlledAnimation(); + final animationControlled = animation!.getSpriteControlledAnimation(); final tile = TileComponent.fromAnimation( animation: animationControlled, position: Vector2(x, y), diff --git a/lib/map/base/tile_component.dart b/lib/map/base/tile_component.dart index c69b47d8e..8431f8446 100644 --- a/lib/map/base/tile_component.dart +++ b/lib/map/base/tile_component.dart @@ -31,7 +31,10 @@ class TileComponent extends GameComponent with UseAssetsLoader { ); if (spritePath.isNotEmpty) { loader?.add( - AssetToLoad(Sprite.load(spritePath), (value) => _sprite = value), + AssetToLoad( + Sprite.load(spritePath), + (value) => _sprite = value, + ), ); } } @@ -101,7 +104,7 @@ class TileComponent extends GameComponent with UseAssetsLoader { @override Paint get paint { if (parent is HasPaint) { - return (parent as HasPaint).paint; + return (parent! as HasPaint).paint; } return super.paint; } diff --git a/lib/map/base/tile_layer_component.dart b/lib/map/base/tile_layer_component.dart index ac01b44c1..353a156bf 100644 --- a/lib/map/base/tile_layer_component.dart +++ b/lib/map/base/tile_layer_component.dart @@ -47,19 +47,25 @@ class TileLayerComponent extends PositionComponent with HasPaint, UseShader { if (_tiles.isNotEmpty) { _tileSize = _tiles.first.width; - double w = _tiles.first.right; - double h = _tiles.first.bottom; - - for (var tile in _tiles) { - if (tile.right > w) w = tile.right; - if (tile.bottom > h) h = tile.bottom; + var w = _tiles.first.right; + var h = _tiles.first.bottom; + + for (final tile in _tiles) { + if (tile.right > w) { + w = tile.right; + } + if (tile.bottom > h) { + h = tile.bottom; + } } size = Vector2(w, h); } } void initLayer(Vector2 gameSize, Vector2 screenSize) { - if (gameSize.isZero()) return; + if (gameSize.isZero()) { + return; + } _createQuadTree(gameSize, screenSize); } @@ -68,13 +74,15 @@ class TileLayerComponent extends PositionComponent with HasPaint, UseShader { Vector2 screenSize, { bool force = false, }) { - if (_lastScreenSize == screenSize && !force) return; + if (_lastScreenSize == screenSize && !force) { + return; + } _lastScreenSize = screenSize.clone(); - Vector2 treeSize = Vector2( + final treeSize = Vector2( mapSize.x / tileSize, mapSize.y / tileSize, ); - int maxItems = 100; + var maxItems = 100; final minScreen = min(screenSize.x, screenSize.y); maxItems = ((minScreen / tileSize) / 2).ceil(); _quadTree = tree.QuadTree( @@ -85,7 +93,7 @@ class TileLayerComponent extends PositionComponent with HasPaint, UseShader { maxItems: maxItems, ); - for (var tile in _tiles) { + for (final tile in _tiles) { _quadTree?.insert( tile, Point(tile.x, tile.y), @@ -100,7 +108,7 @@ class TileLayerComponent extends PositionComponent with HasPaint, UseShader { _quadTree?.clear(); _updateSizeAndPosition(); - for (var tile in _tiles) { + for (final tile in _tiles) { _quadTree?.insert( tile, Point(tile.x, tile.y), @@ -147,7 +155,7 @@ class TileLayerComponent extends PositionComponent with HasPaint, UseShader { } _lastRectCamera = rectCamera; - List visibleTiles = _quadTree!.query( + final visibleTiles = _quadTree!.query( rectCamera.getRectangleByTileSize(_tileSize), ); @@ -174,10 +182,10 @@ class TileLayerComponent extends PositionComponent with HasPaint, UseShader { Future _loadTile(Tile element) async { if (element.sprite != null) { - await MapAssetsManager.loadImage((element.sprite?.path ?? '')); + await MapAssetsManager.loadImage(element.sprite?.path ?? ''); } if (element.animation != null) { - for (var frame in (element.animation?.frames ?? [])) { + for (final frame in (element.animation?.frames ?? [])) { await MapAssetsManager.loadImage(frame.path); } } diff --git a/lib/map/base/tile_with_collision.dart b/lib/map/base/tile_with_collision.dart index 8952b9c5c..c4ceb179c 100644 --- a/lib/map/base/tile_with_collision.dart +++ b/lib/map/base/tile_with_collision.dart @@ -1,67 +1,41 @@ import 'package:bonfire/bonfire.dart'; import 'package:bonfire/util/collision_game_component.dart'; -import 'package:bonfire/util/controlled_update_animation.dart'; class TileWithCollision extends TileComponent { Iterable? collisions; TileWithCollision({ - required String spritePath, - required Vector2 position, - required Vector2 size, - String? tileClass, + required super.spritePath, + required super.position, + required super.size, + super.tileClass, this.collisions, - double offsetX = 0, - double offsetY = 0, - Map? properties, - }) : super( - spritePath: spritePath, - position: position, - size: size, - tileClass: tileClass, - offsetX: offsetX, - offsetY: offsetY, - properties: properties, - ); + super.offsetX, + super.offsetY, + super.properties, + }); TileWithCollision.fromSprite({ - required Sprite? sprite, - required Vector2 position, - required Vector2 size, - String? tileClass, + required super.sprite, + required super.position, + required super.size, + super.tileClass, this.collisions, - double offsetX = 0, - double offsetY = 0, - Color? color, - Map? properties, - }) : super.fromSprite( - sprite: sprite, - position: position, - size: size, - tileClass: tileClass, - offsetX: offsetX, - offsetY: offsetY, - properties: properties, - color: color, - ); + super.offsetX, + super.offsetY, + super.color, + super.properties, + }) : super.fromSprite(); TileWithCollision.withAnimation({ - required ControlledUpdateAnimation animation, - required Vector2 position, - required Vector2 size, - String? tileClass, + required super.animation, + required super.position, + required super.size, + super.tileClass, this.collisions, - double offsetX = 0, - double offsetY = 0, - Map? properties, - }) : super.fromAnimation( - animation: animation, - position: position, - size: size, - offsetX: offsetX, - offsetY: offsetY, - tileClass: tileClass, - properties: properties, - ); + super.offsetX, + super.offsetY, + super.properties, + }) : super.fromAnimation(); @override Future onLoad() { diff --git a/lib/map/empty_map.dart b/lib/map/empty_map.dart index dd27c8b99..643f86712 100644 --- a/lib/map/empty_map.dart +++ b/lib/map/empty_map.dart @@ -9,9 +9,9 @@ class EmptyWorldMap extends WorldMap { id: 0, tiles: [ if (size != null) - Tile(x: size.x, y: size.y, width: 1, height: 1) + Tile(x: size.x, y: size.y, width: 1, height: 1), ], - ) + ), ], tileSizeToUpdate: tileSizeToUpdate, ); diff --git a/lib/map/matrix_map/map_terrain.dart b/lib/map/matrix_map/map_terrain.dart index ebadc99d6..08da7858d 100644 --- a/lib/map/matrix_map/map_terrain.dart +++ b/lib/map/matrix_map/map_terrain.dart @@ -46,7 +46,7 @@ class TerrainSpriteSheet { required this.invertedBottomRight, }); - static TerrainSpriteSheet create({ + factory TerrainSpriteSheet.create({ required String path, required Vector2 tileSize, Vector2? position, @@ -151,16 +151,16 @@ class MapTerrain { this.collisionsBuilder, this.collisionOnlyCloseCorners = false, }) { - int last = 0; - for (var element in spritesProportion) { + var last = 0; + for (final element in spritesProportion) { final value = (element * 100).toInt(); - _rangeProportion.add(_RandomRange(last, (last + value))); + _rangeProportion.add(_RandomRange(last, last + value)); last += value; } } int inRange(int value) { - int index = _rangeProportion.indexWhere( + final index = _rangeProportion.indexWhere( (element) => element.inRange(value), ); return index == -1 ? 0 : index; @@ -176,8 +176,8 @@ class MapTerrain { TileSprite? getSingleSprite() { if (sprites.length > 1 && sprites.length == spritesProportion.length) { - int randomValue = _random.nextInt(maxRandomValue); - int index = inRange(randomValue); + final randomValue = _random.nextInt(maxRandomValue); + final index = inRange(randomValue); return sprites[index]; } else { @@ -191,17 +191,13 @@ class MapTerrainCorners extends MapTerrain { final TerrainSpriteSheet spriteSheet; MapTerrainCorners({ - required double value, + required super.value, required this.to, required this.spriteSheet, - String? type, - Map? properties, - List? Function()? collisionsBuilder, + super.type, + super.properties, + super.collisionsBuilder, }) : super( - value: value, sprites: [], - type: type, - properties: properties, - collisionsBuilder: collisionsBuilder, ); } diff --git a/lib/map/matrix_map/matrix_map_generator.dart b/lib/map/matrix_map/matrix_map_generator.dart index 93c2ced44..af2f323c0 100644 --- a/lib/map/matrix_map/matrix_map_generator.dart +++ b/lib/map/matrix_map/matrix_map_generator.dart @@ -71,9 +71,9 @@ class MatrixMapGenerator { required List layers, required TileModelBuilder builder, }) { - List tileLayers = []; - int index = 0; - for (var layer in layers) { + final tileLayers = []; + var index = 0; + for (final layer in layers) { if (layer.axisInverted) { tileLayers.add( Layer( @@ -107,7 +107,7 @@ class MatrixMapGenerator { List> matrix, TileModelBuilder builder, ) { - List tiles = []; + final tiles = []; final h = matrix.first.length; final w = matrix.length; for (var x = 0; x < w; x++) { @@ -137,7 +137,7 @@ class MatrixMapGenerator { List> matrix, TileModelBuilder builder, ) { - List tiles = []; + final tiles = []; final w = matrix.first.length; final h = matrix.length; for (var y = 0; y < h; y++) { diff --git a/lib/map/matrix_map/terrain_builder.dart b/lib/map/matrix_map/terrain_builder.dart index 4ad62ea43..aa431ef0f 100644 --- a/lib/map/matrix_map/terrain_builder.dart +++ b/lib/map/matrix_map/terrain_builder.dart @@ -23,7 +23,7 @@ class TerrainBuilder { TerrainBuilder({required this.tileSize, required this.terrainList}); Tile build(ItemMatrixProperties prop) { - Iterable findList = terrainList.where( + final findList = terrainList.where( (element) => element.value == prop.value, ); @@ -33,7 +33,7 @@ class TerrainBuilder { try { if (prop.isCenterTile) { - MapTerrain terrain = findList.where((element) { + final terrain = findList.where((element) { return element is! MapTerrainCorners; }).first; return _buildTile(terrain, prop); @@ -50,8 +50,7 @@ class TerrainBuilder { ItemMatrixProperties prop, ) { TileSprite? sprite; - Iterable corners = - terrains.whereType(); + final corners = terrains.whereType(); MapTerrain? terrain; @@ -66,7 +65,7 @@ class TerrainBuilder { } if (sprite == null) { - MapTerrainCorners? left = firstWhere( + final MapTerrainCorners? left = firstWhere( corners, (element) => element.to == prop.valueLeft, ); @@ -78,7 +77,7 @@ class TerrainBuilder { } if (sprite == null) { - MapTerrainCorners? right = firstWhere( + final MapTerrainCorners? right = firstWhere( corners, (element) => element.to == prop.valueRight, ); @@ -90,7 +89,7 @@ class TerrainBuilder { } if (sprite == null) { - MapTerrainCorners? top = firstWhere( + final MapTerrainCorners? top = firstWhere( corners, (element) => element.to == prop.valueTop, ); @@ -101,7 +100,7 @@ class TerrainBuilder { } if (sprite == null) { - MapTerrainCorners? bottom = firstWhere( + final MapTerrainCorners? bottom = firstWhere( corners, (element) => element.to == prop.valueBottom, ); @@ -112,7 +111,7 @@ class TerrainBuilder { } if (sprite == null) { - MapTerrain? center = firstWhere( + final MapTerrain? center = firstWhere( terrains, (element) => element is! MapTerrainCorners, ); @@ -165,7 +164,7 @@ class TerrainBuilder { if (prop.valueBottom != prop.value && prop.valueBottom == prop.valueBottomLeft && prop.valueBottom == prop.valueLeft) { - MapTerrainCorners? bottomLeft = firstWhere( + final MapTerrainCorners? bottomLeft = firstWhere( corners, (element) => element.to == prop.valueBottom, ); @@ -178,7 +177,7 @@ class TerrainBuilder { if (prop.valueBottom != prop.value && prop.valueBottom == prop.valueBottomRight && prop.valueBottom == prop.valueRight) { - MapTerrainCorners? bottomRight = firstWhere( + final MapTerrainCorners? bottomRight = firstWhere( corners, (element) => element.to == prop.valueBottom, ); @@ -191,7 +190,7 @@ class TerrainBuilder { if (prop.valueBottomLeft != prop.value && prop.valueLeft == prop.value && prop.valueLeft == prop.valueBottom) { - MapTerrainCorners? bottomLeft = firstWhere( + final MapTerrainCorners? bottomLeft = firstWhere( corners, (element) => element.to == prop.valueBottomLeft, ); @@ -204,7 +203,7 @@ class TerrainBuilder { if (prop.valueBottomRight != prop.value && prop.valueRight == prop.value && prop.valueRight == prop.valueBottom) { - MapTerrainCorners? bottomRight = firstWhere( + final MapTerrainCorners? bottomRight = firstWhere( corners, (element) => element.to == prop.valueBottomRight, ); @@ -226,7 +225,7 @@ class TerrainBuilder { if (prop.valueTop != prop.value && prop.valueTop == prop.valueTopLeft && prop.valueTop == prop.valueLeft) { - MapTerrainCorners? topLeft = firstWhere( + final MapTerrainCorners? topLeft = firstWhere( corners, (element) => element.to == prop.valueTop, ); @@ -239,7 +238,7 @@ class TerrainBuilder { if (prop.valueTop != prop.value && prop.valueTop == prop.valueTopRight && prop.valueTop == prop.valueRight) { - MapTerrainCorners? topRight = firstWhere( + final MapTerrainCorners? topRight = firstWhere( corners, (element) => element.to == prop.valueTop, ); @@ -252,7 +251,7 @@ class TerrainBuilder { if (prop.valueTopLeft != prop.value && prop.valueLeft == prop.value && prop.valueLeft == prop.valueTop) { - MapTerrainCorners? topLeftInverted = firstWhere( + final MapTerrainCorners? topLeftInverted = firstWhere( corners, (element) => element.to == prop.valueTopLeft, ); @@ -265,7 +264,7 @@ class TerrainBuilder { if (prop.valueTopRight != prop.value && prop.valueRight == prop.value && prop.valueRight == prop.valueTop) { - MapTerrainCorners? topRightInverted = firstWhere( + final MapTerrainCorners? topRightInverted = firstWhere( corners, (element) => element.to == prop.valueTopRight, ); diff --git a/lib/map/spritefusion/builder/spritefusion_world_builder.dart b/lib/map/spritefusion/builder/spritefusion_world_builder.dart index 0e6aa6c79..bdc08ff80 100644 --- a/lib/map/spritefusion/builder/spritefusion_world_builder.dart +++ b/lib/map/spritefusion/builder/spritefusion_world_builder.dart @@ -47,10 +47,10 @@ class SpritefusionWorldBuilder { } Future _load(SpritefusionMap map) async { - int index = 0; + var index = 0; final spritesheet = await MapAssetsManager.loadImage(map.imgPath); final maxRow = spritesheet.width / map.tileSize; - for (var layer in map.layers.reversed) { + for (final layer in map.layers.reversed) { final objectBuilder = objectsBuilder?[layer.name]; if (objectBuilder != null) { _addObjects(layer, objectBuilder, map.tileSize); @@ -61,9 +61,13 @@ class SpritefusionWorldBuilder { } } - void _addTile(SpritefusionMapLayer layer, SpritefusionMap map, double maxRow, - int index) { - List tiles = _loadTiles( + void _addTile( + SpritefusionMapLayer layer, + SpritefusionMap map, + double maxRow, + int index, + ) { + final tiles = _loadTiles( layer.tiles, map.tileSize, map.imgPath, @@ -89,8 +93,8 @@ class SpritefusionWorldBuilder { final size = Vector2.all(tileSize); return tiles.map( (tile) { - int row = tile.idInt ~/ maxRow; - int col = (tile.idInt % maxRow).toInt(); + final row = tile.idInt ~/ maxRow; + final col = (tile.idInt % maxRow).toInt(); return Tile( x: tile.x.toDouble(), y: tile.y.toDouble(), @@ -107,9 +111,12 @@ class SpritefusionWorldBuilder { ).toList(); } - void _addObjects(SpritefusionMapLayer layer, - SpritefusionObjectBuilder objectBuilder, double tileSize) { - for (var tile in layer.tiles) { + void _addObjects( + SpritefusionMapLayer layer, + SpritefusionObjectBuilder objectBuilder, + double tileSize, + ) { + for (final tile in layer.tiles) { final position = Vector2( tile.x.toDouble(), tile.y.toDouble(), diff --git a/lib/map/spritefusion/model/spritefucion_map.dart b/lib/map/spritefusion/model/spritefucion_map.dart index 8ba1f4202..0e8451b0c 100644 --- a/lib/map/spritefusion/model/spritefucion_map.dart +++ b/lib/map/spritefusion/model/spritefucion_map.dart @@ -31,7 +31,7 @@ class SpritefusionMap { tileSize: double.parse(map['tileSize'].toString()), mapWidth: double.parse(map['mapWidth'].toString()), mapHeight: double.parse(map['mapHeight'].toString()), - imgPath: map['imgPath'] ?? '', + imgPath: map['imgPath']?.toString() ?? '', layers: List.from( (map['layers'] as List).map( (x) => SpritefusionMapLayer.fromMap(x as Map), @@ -52,8 +52,11 @@ class SpritefusionMapLayer { final bool collider; final List tiles; - SpritefusionMapLayer( - {required this.name, required this.tiles, this.collider = false}); + SpritefusionMapLayer({ + required this.name, + required this.tiles, + this.collider = false, + }); Map toMap() { return { @@ -66,7 +69,7 @@ class SpritefusionMapLayer { factory SpritefusionMapLayer.fromMap(Map map) { return SpritefusionMapLayer( name: map['name'] as String, - collider: map['collider'] ?? false, + collider: map['collider'] as bool? ?? false, tiles: List.from( (map['tiles'] as List).map( (x) => SpritefusionMapLayerTile.fromMap(x as Map), @@ -114,5 +117,6 @@ class SpritefusionMapLayerTile { factory SpritefusionMapLayerTile.fromJson(String source) => SpritefusionMapLayerTile.fromMap( - json.decode(source) as Map); + json.decode(source) as Map, + ); } diff --git a/lib/map/spritefusion/reader/spritefusion_asset_reader.dart b/lib/map/spritefusion/reader/spritefusion_asset_reader.dart index f259ce1d6..6f257e194 100644 --- a/lib/map/spritefusion/reader/spritefusion_asset_reader.dart +++ b/lib/map/spritefusion/reader/spritefusion_asset_reader.dart @@ -13,7 +13,7 @@ class SpritefusionAssetReader extends WorldMapReader { SpritefusionAssetReader({ required this.asset, }) { - var assetKey = asset.startsWith(_assetPrefixKey) + final assetKey = asset.startsWith(_assetPrefixKey) ? asset.substring(_assetPrefixKey.length) : asset; basePath = assetKey.replaceAll(assetKey.split('/').last, ''); @@ -22,7 +22,7 @@ class SpritefusionAssetReader extends WorldMapReader { @override Future readMap() async { - String data = await rootBundle.loadString(_path); + final data = await rootBundle.loadString(_path); return SpritefusionMap.fromJson(data) ..imgPath = '${basePath}spritesheet.png'; } diff --git a/lib/map/spritefusion/reader/spritefusion_network_reader.dart b/lib/map/spritefusion/reader/spritefusion_network_reader.dart index c72d83377..7ee3c64ae 100644 --- a/lib/map/spritefusion/reader/spritefusion_network_reader.dart +++ b/lib/map/spritefusion/reader/spritefusion_network_reader.dart @@ -23,7 +23,7 @@ class SpritefusionNetworkReader extends WorldMapReader { this.headers, }) : cache = cacheProvider ?? TiledMemoryCacheProvider() { _imageLoader = ServerImageLoader(cache: cache); - String url = uri.toString(); + final url = uri.toString(); basePath = url.replaceAll(url.split('/').last, ''); } @@ -36,16 +36,16 @@ class SpritefusionNetworkReader extends WorldMapReader { Future _fetchMap() async { final uriKey = uri.toString(); - bool containCache = await cache.containsKey(uriKey); + final containCache = await cache.containsKey(uriKey); if (containCache) { final map = await cache.get(uriKey); return SpritefusionMap.fromMap(map); } else { final mapResponse = await http.get(uri, headers: headers); - final map = jsonDecode(mapResponse.body); + final map = (jsonDecode(mapResponse.body) as Map).cast(); map['imgPath'] = '${basePath}spritesheet.png'; - cache.put(uriKey, map); - return SpritefusionMap.fromJson(map); + cache.put(uriKey, map.cast()); + return SpritefusionMap.fromMap(map); } } } diff --git a/lib/map/tiled/builder/tiled_world_builder.dart b/lib/map/tiled/builder/tiled_world_builder.dart index bcc427c04..fcfcecf9f 100644 --- a/lib/map/tiled/builder/tiled_world_builder.dart +++ b/lib/map/tiled/builder/tiled_world_builder.dart @@ -6,6 +6,8 @@ import 'dart:ui'; import 'package:bonfire/background/background_image_game.dart'; import 'package:bonfire/bonfire.dart' hide TileComponent; import 'package:bonfire/map/base/layer.dart'; +import 'package:bonfire/map/tiled/model/tiled_data_object_collision.dart'; +import 'package:bonfire/map/tiled/model/tiled_item_tile_set.dart'; import 'package:bonfire/map/tiled/model/tiled_world_data.dart'; import 'package:bonfire/map/util/map_layer_mapper.dart'; import 'package:bonfire/util/collision_game_component.dart'; @@ -20,13 +22,7 @@ import 'package:tiledjsonreader/map/layer/objects.dart'; import 'package:tiledjsonreader/map/layer/tile_layer.dart' as tiled; import 'package:tiledjsonreader/map/tile_set_detail.dart'; import 'package:tiledjsonreader/map/tiled_map.dart'; -import 'package:tiledjsonreader/tile_set/frame_animation.dart'; import 'package:tiledjsonreader/tile_set/polygon.dart'; -import 'package:tiledjsonreader/tile_set/tile_set_item.dart'; -import 'package:tiledjsonreader/tile_set/tile_set_object.dart'; - -import '../model/tiled_data_object_collision.dart'; -import '../model/tiled_item_tile_set.dart'; typedef ObjectBuilder = GameComponent Function( TiledObjectProperties properties, @@ -100,16 +96,20 @@ class TiledWorldBuilder { } Future _load(TiledMap tiledMap) async { - for (var layer in tiledMap.layers ?? const []) { + for (final layer in tiledMap.layers ?? const []) { await _loadLayer(layer); } } Future _loadLayer(MapLayer layer) async { - if (layer.visible != true) return; + if (layer.visible != true) { + return; + } if (layer is tiled.TileLayer) { - _layers.add(MapLayerMapper.toLayer(layer, countTileLayer)); + _layers.add( + MapLayerMapper.toLayer(layer, countTileLayer), + ); await _addTileLayer(layer); countTileLayer++; } @@ -124,7 +124,7 @@ class TiledWorldBuilder { } if (layer is GroupLayer) { - for (var layer in layer.layers ?? const []) { + for (final layer in layer.layers ?? const []) { await _loadLayer(layer); } } @@ -135,25 +135,29 @@ class TiledWorldBuilder { } Future _addTileLayer(tiled.TileLayer tileLayer) async { - if (tileLayer.visible != true) return; - int count = 0; - double offsetX = _getDoubleByProportion(tileLayer.offsetX); - double offsetY = _getDoubleByProportion(tileLayer.offsetY); - double opacity = tileLayer.opacity ?? 1.0; - bool layerIsAbove = tileLayer.properties - ?.where((element) => - element.name == 'type' && element.value == ABOVE_TYPE) + if (tileLayer.visible != true) { + return; + } + var count = 0; + final offsetX = _getDoubleByProportion(tileLayer.offsetX); + final offsetY = _getDoubleByProportion(tileLayer.offsetY); + final opacity = tileLayer.opacity ?? 1.0; + final layerIsAbove = tileLayer.properties + ?.where( + (element) => + element.name == 'type' && element.value == ABOVE_TYPE, + ) .isNotEmpty ?? false; - for (var tile in tileLayer.data ?? const []) { + for (final tile in tileLayer.data ?? const []) { if (tile != 0) { - var data = _getDataTile(tile); + final data = _getDataTile(tile); if (data != null) { - bool tileIsAbove = ((data.type?.contains(ABOVE_TYPE) ?? false) || + final tileIsAbove = (data.type?.contains(ABOVE_TYPE) ?? false) || (data.tileClass?.contains(ABOVE_TYPE) ?? false) || - layerIsAbove); - bool isDynamic = data.type?.contains(DYNAMIC_ABOVE_TYPE) ?? false; + layerIsAbove; + final isDynamic = data.type?.contains(DYNAMIC_ABOVE_TYPE) ?? false; if (tileIsAbove || isDynamic) { _addGameDecorationAbove( data, @@ -212,8 +216,8 @@ class TiledWorldBuilder { comp = GameDecorationWithCollision.withAnimation( animation: data.animation!.getFutureSpriteAnimation(), position: Vector2( - _getX(count, (tileLayer.width?.toInt()) ?? 1) * _tileWidth, - _getY(count, (tileLayer.width?.toInt()) ?? 1) * _tileHeight, + _getX(count, tileLayer.width?.toInt() ?? 1) * _tileWidth, + _getY(count, tileLayer.width?.toInt() ?? 1) * _tileHeight, ), size: Vector2(_tileWidth, _tileHeight), collisions: data.collisions, @@ -228,8 +232,8 @@ class TiledWorldBuilder { comp = GameDecorationWithCollision.withSprite( sprite: data.sprite!.getFutureSprite(), position: Vector2( - _getX(count, (tileLayer.width?.toInt()) ?? 1) * _tileWidth, - _getY(count, (tileLayer.width?.toInt()) ?? 1) * _tileHeight, + _getX(count, tileLayer.width?.toInt() ?? 1) * _tileWidth, + _getY(count, tileLayer.width?.toInt() ?? 1) * _tileHeight, ), size: Vector2(_tileWidth, _tileHeight), collisions: data.collisions, @@ -262,15 +266,15 @@ class TiledWorldBuilder { TiledItemTileSet? _getDataTile(int gid) { final gidInfo = tiled.TileLayer.getGidInfo(gid); - int index = gidInfo.index; + final index = gidInfo.index; TileSetDetail? tileSetContain; - String pathTileset = ''; - String imagePath = ''; - int firsTgId = 0; - int tilesetFirsTgId = 0; - int widthCount = 1; - Vector2 spriteSize = Vector2.all(0); + var pathTileset = ''; + var imagePath = ''; + var firsTgId = 0; + var tilesetFirsTgId = 0; + var widthCount = 1; + var spriteSize = Vector2.all(0); try { tileSetContain = _tiledMap?.tileSets?.lastWhere((tileSet) { @@ -298,7 +302,7 @@ class TiledWorldBuilder { // to cases that the tileSet contain individual image. if (tileSetContain?.image == null && tileSetContain?.tiles?.isNotEmpty == true) { - int tilePosition = index - firsTgId; + final tilePosition = index - firsTgId; final tile = tileSetContain!.tiles![tilePosition]; imagePath = tile.image ?? ''; widthCount = 1; @@ -313,14 +317,14 @@ class TiledWorldBuilder { if (tileSetContain != null) { final spritePosition = Vector2( - _getX((index - firsTgId), widthCount), - _getY((index - firsTgId), widthCount), + _getX(index - firsTgId, widthCount), + _getY(index - firsTgId, widthCount), ); final pathSprite = '$_basePath$pathTileset$imagePath'; TileSprite sprite; - String tileKey = '$pathSprite/${spritePosition.x}/${spritePosition.y}'; + final tileKey = '$pathSprite/${spritePosition.x}/${spritePosition.y}'; if (_tileModelSpriteCache.containsKey(tileKey)) { sprite = _tileModelSpriteCache[tileKey]!; } else { @@ -334,13 +338,13 @@ class TiledWorldBuilder { final animation = _getAnimation( tileSetContain, pathTileset, - (index - tilesetFirsTgId), + index - tilesetFirsTgId, widthCount, ); final object = _getCollision( tileSetContain, - (index - tilesetFirsTgId), + index - tilesetFirsTgId, ); return TiledItemTileSet( @@ -359,17 +363,19 @@ class TiledWorldBuilder { } void _addObjects(ObjectLayer layer) { - if (layer.visible != true) return; - bool isCollisionLayer = layer.layerClass?.toLowerCase() == 'collision'; - double offsetX = _getDoubleByProportion(layer.offsetX); - double offsetY = _getDoubleByProportion(layer.offsetY); - for (var element in layer.objects ?? const []) { - double x = _getDoubleByProportion(element.x) + offsetX; - double y = _getDoubleByProportion(element.y) + offsetY; - double width = _getDoubleByProportion(element.width); - double height = _getDoubleByProportion(element.height); - double rotation = (element.rotation ?? 0) * pi / 180; - bool isObjectCollision = + if (layer.visible != true) { + return; + } + final isCollisionLayer = layer.layerClass?.toLowerCase() == 'collision'; + final offsetX = _getDoubleByProportion(layer.offsetX); + final offsetY = _getDoubleByProportion(layer.offsetY); + for (final element in layer.objects ?? const []) { + final x = _getDoubleByProportion(element.x) + offsetX; + final y = _getDoubleByProportion(element.y) + offsetY; + final width = _getDoubleByProportion(element.width); + final height = _getDoubleByProportion(element.height); + final rotation = (element.rotation ?? 0) * pi / 180; + final isObjectCollision = element.typeOrClass?.toLowerCase() == 'collision' || isCollisionLayer; final collision = _getCollisionObject( x, @@ -382,7 +388,7 @@ class TiledWorldBuilder { ); if (element.text != null) { - double fontSize = element.text!.pixelSize.toDouble(); + var fontSize = element.text!.pixelSize.toDouble(); fontSize = (_tileWidth * fontSize) / _tileWidthOrigin; _components.add( TextGameComponent( @@ -442,28 +448,28 @@ class TiledWorldBuilder { TileSetDetail tileSetContain, int index, ) { - Iterable tileSetItemList = tileSetContain.tiles?.where( + final tileSetItemList = tileSetContain.tiles?.where( (element) => element.id == index, ) ?? []; if (tileSetItemList.isNotEmpty) { - List tileSetObjectList = + final tileSetObjectList = tileSetItemList.first.objectGroup?.objects ?? []; - Map properties = MapLayerMapper.extractOtherProperties( + final properties = MapLayerMapper.extractOtherProperties( tileSetItemList.first.properties, ); - List collisions = []; + final collisions = []; if (tileSetObjectList.isNotEmpty) { - for (var object in tileSetObjectList) { - double width = _getDoubleByProportion(object.width); - double height = _getDoubleByProportion(object.height); + for (final object in tileSetObjectList) { + final width = _getDoubleByProportion(object.width); + final height = _getDoubleByProportion(object.height); - double x = _getDoubleByProportion(object.x); - double y = _getDoubleByProportion(object.y); + final x = _getDoubleByProportion(object.x); + final y = _getDoubleByProportion(object.y); collisions.add( _getCollisionObject( @@ -500,21 +506,21 @@ class TiledWorldBuilder { return null; } - TileSetItem tileSetItemList = filter.first; + final tileSetItemList = filter.first; - List animationFrames = tileSetItemList.animation ?? []; + final animationFrames = tileSetItemList.animation ?? []; - List frames = []; - if ((animationFrames.isNotEmpty)) { - double stepTime = (animationFrames[0].duration ?? 100) / 1000; + final frames = []; + if (animationFrames.isNotEmpty) { + final stepTime = (animationFrames[0].duration ?? 100) / 1000; - for (var frame in animationFrames) { - double y = _getY((frame.tileid ?? 0), widthCount); - double x = _getX((frame.tileid ?? 0), widthCount); + for (final frame in animationFrames) { + final y = _getY(frame.tileid ?? 0, widthCount); + final x = _getX(frame.tileid ?? 0, widthCount); final spritePath = '$_basePath$pathTileset${tileSetContain.image}'; - TileSprite sprite = TileSprite( + final sprite = TileSprite( path: spritePath, size: Vector2( tileSetContain.tileWidth ?? 0, @@ -535,7 +541,9 @@ class TiledWorldBuilder { } void _addImageLayer(ImageLayer layer) { - if (!(layer.visible ?? false)) return; + if (!(layer.visible ?? false)) { + return; + } _components.add( BackgroundImageGame( id: layer.id, @@ -591,10 +599,10 @@ class TiledWorldBuilder { List polygon, bool isObjectCollision, ) { - double minorX = _getDoubleByProportion(polygon.first.x); - double minorY = _getDoubleByProportion(polygon.first.y); - List points = polygon.map((e) { - Vector2 vector = Vector2( + var minorX = _getDoubleByProportion(polygon.first.x); + var minorY = _getDoubleByProportion(polygon.first.y); + var points = polygon.map((e) { + final vector = Vector2( _getDoubleByProportion(e.x), _getDoubleByProportion(e.y), ); @@ -621,8 +629,8 @@ class TiledWorldBuilder { }).toList(); } - double alignX = x - points.first.x; - double alignY = y - points.first.y; + var alignX = x - points.first.x; + var alignY = y - points.first.y; if (isObjectCollision) { alignX = minorX; diff --git a/lib/map/tiled/reader/tiled_asset_reader.dart b/lib/map/tiled/reader/tiled_asset_reader.dart index 5d99a3d21..f9e5f2133 100644 --- a/lib/map/tiled/reader/tiled_asset_reader.dart +++ b/lib/map/tiled/reader/tiled_asset_reader.dart @@ -13,7 +13,7 @@ class TiledAssetReader extends WorldMapReader { TiledAssetReader({ required this.asset, }) { - var assetKey = asset.startsWith(_ASSET_KEY_PREFIX) + final assetKey = asset.startsWith(_ASSET_KEY_PREFIX) ? asset.substring(_ASSET_KEY_PREFIX.length) : asset; basePath = assetKey.replaceAll(assetKey.split('/').last, ''); diff --git a/lib/map/tiled/reader/tiled_network_reader.dart b/lib/map/tiled/reader/tiled_network_reader.dart index 4d243b149..2c5973a10 100644 --- a/lib/map/tiled/reader/tiled_network_reader.dart +++ b/lib/map/tiled/reader/tiled_network_reader.dart @@ -27,14 +27,14 @@ class TiledNetworkReader extends WorldMapReader { this.headers, }) : cache = cacheProvider ?? TiledMemoryCacheProvider() { _imageLoader = ServerImageLoader(cache: cache); - String url = uri.toString(); + final url = uri.toString(); basePath = url.replaceAll(url.split('/').last, ''); } @override Future readMap() async { try { - TiledMap tiledMap = await _fetchMap(); + final tiledMap = await _fetchMap(); await Future.forEach( tiledMap.layers ?? [], @@ -60,7 +60,7 @@ class TiledNetworkReader extends WorldMapReader { Future preload() => readMap(); Future _loadTileset(TileSetDetail tileSet) async { - String sourceBasePath = ''; + var sourceBasePath = ''; if (tileSet.source != null) { if (!_isSuppotedTilesetFileType(tileSet.source!)) { throw Exception('Invalid TileSet source: only supports json|tsj files'); @@ -82,16 +82,16 @@ class TiledNetworkReader extends WorldMapReader { } bool _isSuppotedTilesetFileType(String source) { - return (source.contains('.json') || source.contains('.tsj')); + return source.contains('.json') || source.contains('.tsj'); } bool _isSuppotedMapFileType(String source) { - return (source.contains('.json') || source.contains('.tmj')); + return source.contains('.json') || source.contains('.tmj'); } Future _fetchMap() async { final uriKey = uri.toString(); - bool containCache = await cache.containsKey(uriKey); + final containCache = await cache.containsKey(uriKey); if (containCache) { final map = await cache.get(uriKey); return TiledMap.fromJson(map); @@ -100,7 +100,7 @@ class TiledNetworkReader extends WorldMapReader { throw Exception('Invalid TileMap source: only supports json|tmj files'); } final mapResponse = await http.get(uri, headers: headers); - final map = jsonDecode(mapResponse.body); + final map = (jsonDecode(mapResponse.body) as Map).cast(); cache.put(uriKey, map); return TiledMap.fromJson(map); } @@ -110,7 +110,7 @@ class TiledNetworkReader extends WorldMapReader { final uri = Uri.parse('$basePath$source'); final uriKey = uri.toString(); - bool containCache = await cache.containsKey(uriKey); + final containCache = await cache.containsKey(uriKey); if (containCache) { return cache.get(uriKey); @@ -119,14 +119,14 @@ class TiledNetworkReader extends WorldMapReader { Uri.parse('$basePath$source'), headers: headers, ); - final map = jsonDecode(tileSetResponse.body); + final map = jsonDecode(tileSetResponse.body) as Map; cache.put(uriKey, map); return map; } } Future _fetchTilesetImage(String sourceBasePath, String image) async { - String url = '$basePath$sourceBasePath$image'; + var url = '$basePath$sourceBasePath$image'; if (image.contains('http')) { url = image; } @@ -136,7 +136,7 @@ class TiledNetworkReader extends WorldMapReader { Future _fetchLayerImage(MapLayer layer) async { if (layer is ImageLayer) { - String url = '$basePath${layer.image}'; + var url = '$basePath${layer.image}'; if (layer.image.contains('http')) { url = layer.image; } diff --git a/lib/map/util/map_assets_manager.dart b/lib/map/util/map_assets_manager.dart index 9b2933bf7..0f374434b 100644 --- a/lib/map/util/map_assets_manager.dart +++ b/lib/map/util/map_assets_manager.dart @@ -10,12 +10,12 @@ class MapAssetsManager { Vector2 position, Vector2 size, ) { - String pathCache = '$image/${position.x}/${position.y}'; + final pathCache = '$image/${position.x}/${position.y}'; if (spriteCache.containsKey(pathCache)) { return spriteCache[pathCache]!; } - Image? spriteSheetImg = getImageCache(image); + final spriteSheetImg = getImageCache(image); return spriteCache[pathCache] = spriteSheetImg!.getSprite( position: Vector2(position.x * size.x, position.y * size.y), @@ -31,20 +31,20 @@ class MapAssetsManager { Vector2? position, Vector2? size, }) async { - String pathCache = '$image/${position?.x ?? 0}/${position?.y ?? 0}'; + final pathCache = '$image/${position?.x ?? 0}/${position?.y ?? 0}'; if (spriteCache.containsKey(pathCache)) { return Future.value(spriteCache[pathCache]); } - Image spriteSheetImg = await loadImage( + final spriteSheetImg = await loadImage( image, ); return spriteCache[pathCache] = spriteSheetImg.getSprite( position: Vector2( - ((position?.x ?? 0.0) * (size?.x ?? 0.0)), - ((position?.y ?? 0.0) * (size?.y ?? 0.0)), + (position?.x ?? 0.0) * (size?.x ?? 0.0), + (position?.y ?? 0.0) * (size?.y ?? 0.0), ), size: Vector2( (size?.x ?? 0.0) == 0.0 ? spriteSheetImg.width.toDouble() : size!.x, @@ -57,10 +57,10 @@ class MapAssetsManager { List frames, double stepTime, ) async { - List spriteList = []; + final spriteList = []; - for (var frame in frames) { - Sprite sprite = await MapAssetsManager.getFutureSprite( + for (final frame in frames) { + final sprite = await MapAssetsManager.getFutureSprite( frame.path, position: frame.position, size: frame.size, @@ -78,11 +78,11 @@ class MapAssetsManager { List frames, double stepTime, ) { - String key = ''; - List spriteList = []; + var key = ''; + final spriteList = []; - for (var frame in frames) { - Sprite sprite = MapAssetsManager.getSprite( + for (final frame in frames) { + final sprite = MapAssetsManager.getSprite( frame.path, frame.position, frame.size, diff --git a/lib/map/util/map_layer_mapper.dart b/lib/map/util/map_layer_mapper.dart index 79f064d8a..83265dff2 100644 --- a/lib/map/util/map_layer_mapper.dart +++ b/lib/map/util/map_layer_mapper.dart @@ -4,7 +4,7 @@ import 'package:tiledjsonreader/map/layer/map_layer.dart'; import 'package:tiledjsonreader/map/layer/objects.dart'; abstract class MapLayerMapper { - static toLayer(MapLayer layer, int priority) { + static Layer toLayer(MapLayer layer, int priority) { return Layer( id: layer.id, layerClass: layer.layerClass, @@ -26,10 +26,11 @@ abstract class MapLayerMapper { } static Map extractOtherProperties( - List? properties) { + List? properties, + ) { final map = {}; - for (var element in properties ?? const []) { + for (final element in properties ?? const []) { if (element.value != null && element.name != null) { map[element.name!] = element.value; } diff --git a/lib/map/util/server_image_loader.dart b/lib/map/util/server_image_loader.dart index f5ad477cd..5c4c63c74 100644 --- a/lib/map/util/server_image_loader.dart +++ b/lib/map/util/server_image_loader.dart @@ -14,13 +14,13 @@ class ServerImageLoader { }); Future load(String url) async { if (!Flame.images.containsKey(url)) { - bool containCache = await cache.containsKey(url); + final containCache = await cache.containsKey(url); if (containCache) { - String base64 = (await cache.get(url))[_keyImgBase64]; + final base64 = (await cache.get(url))[_keyImgBase64].toString(); return Flame.images.fromBase64(url, base64); } else { final response = await http.get(Uri.parse(url), headers: headers); - String img64 = base64Encode(response.bodyBytes); + final img64 = base64Encode(response.bodyBytes); cache.put(url, {_keyImgBase64: img64}); return Flame.images.fromBase64(url, img64); } diff --git a/lib/map/world_map.dart b/lib/map/world_map.dart index 451987eab..af1ef0962 100644 --- a/lib/map/world_map.dart +++ b/lib/map/world_map.dart @@ -18,18 +18,17 @@ class WorldMap extends GameMap { tree.QuadTree? quadTree; - factory WorldMap.empty({Vector2? size}) { - return EmptyWorldMap(size: size); - } - WorldMap( - List layers, { + super.layers, { double tileSizeToUpdate = 0, }) : super( - layers, sizeToUpdate: tileSizeToUpdate, ); + factory WorldMap.empty({Vector2? size}) { + return EmptyWorldMap(size: size); + } + @override void update(double dt) { super.update(dt); @@ -39,9 +38,9 @@ class WorldMap extends GameMap { } } - void _searchTilesToRender() async { + Future _searchTilesToRender() async { final rectCamera = gameRef.camera.cameraRectWithSpacing; - for (var layer in layersComponent) { + for (final layer in layersComponent) { await layer.onMoveCamera(rectCamera); } _buildingTiles = false; @@ -79,7 +78,7 @@ class WorldMap extends GameMap { @override void refreshMap() { - for (var element in layersComponent) { + for (final element in layersComponent) { element.refresh(); } } @@ -90,7 +89,7 @@ class WorldMap extends GameMap { lastCameraWindow = Vector2.zero(); lastMinorZoom = gameRef.camera.zoom; _calculatePositionAndSize(); - for (var layer in layersComponent) { + for (final layer in layersComponent) { layer.initLayer(size, sizeScreen); } } @@ -106,15 +105,23 @@ class WorldMap extends GameMap { double x = 0; double y = 0; - double w = layersComponent.first.size.x; - double h = layersComponent.first.size.y; - - for (var layer in layersComponent) { - if (layer.left < x) x = layer.left; - if (layer.top < y) y = layer.top; - - if (layer.right > w) w = layer.right; - if (layer.bottom > h) h = layer.bottom; + var w = layersComponent.first.size.x; + var h = layersComponent.first.size.y; + + for (final layer in layersComponent) { + if (layer.left < x) { + x = layer.left; + } + if (layer.top < y) { + y = layer.top; + } + + if (layer.right > w) { + w = layer.right; + } + if (layer.bottom > h) { + h = layer.bottom; + } } _mapSize = Vector2(w - x, h - y); size = Vector2(w, h); diff --git a/lib/mixins/attackable.dart b/lib/mixins/attackable.dart index 1fd4d2ea5..7ff16127c 100644 --- a/lib/mixins/attackable.dart +++ b/lib/mixins/attackable.dart @@ -33,7 +33,7 @@ mixin Attackable on GameComponent { /// Increase life void addLife(double life) { - double newLife = _life + life; + var newLife = _life + life; if (newLife > maxLife) { newLife = maxLife; @@ -54,7 +54,7 @@ mixin Attackable on GameComponent { /// reduce life void removeLife(double life) { - double newLife = _life - life; + var newLife = _life - life; if (newLife < 0) { newLife = 0; } @@ -101,9 +101,12 @@ mixin Attackable on GameComponent { removeLife(damage); } - /// This method is used to check if this component can receive damage from any attacker. + /// This method is used to check if this component can + /// receive damage from any attacker. bool checkCanReceiveDamage(AttackOriginEnum attacker) { - if (isDead || isRemoving) return false; + if (isDead || isRemoving) { + return false; + } switch (receivesAttackFrom) { case AcceptableAttackOriginEnum.ALL: return true; diff --git a/lib/mixins/elastic_collision.dart b/lib/mixins/elastic_collision.dart index 002d81615..f6d14424a 100644 --- a/lib/mixins/elastic_collision.dart +++ b/lib/mixins/elastic_collision.dart @@ -23,26 +23,26 @@ mixin ElasticCollision on BlockMovementCollision { CollisionData data, ) { if (_bouncingObjectEnabled) { - Vector2 otherVelocity = + final otherVelocity = (other is Movement) ? other.velocity : Vector2.zero(); - Vector2 relativeVelocity = otherVelocity - velocity; + final relativeVelocity = otherVelocity - velocity; if (relativeVelocity.dot(data.normal) > 0) { return super.getVelocityReflection(other, data); } - double bRestitution = + final bRestitution = (other is ElasticCollision) ? other._restitution : _restitution; - double e = min(_restitution, bRestitution); + final double e = min(_restitution, bRestitution); - double j = -(1 + e) * relativeVelocity.dot(data.normal); + var j = -(1 + e) * relativeVelocity.dot(data.normal); - double mass = (this is HandleForces) ? (this as HandleForces).mass : 1; - double massB = (other is HandleForces) ? (other).mass : 1; + final mass = (this is HandleForces) ? (this as HandleForces).mass : 1; + final massB = (other is HandleForces) ? other.mass : 1; j /= mass + massB; - Vector2 impulse = data.normal * j; + final impulse = data.normal * j; return impulse; } return super.getVelocityReflection(other, data); diff --git a/lib/mixins/flip_render.dart b/lib/mixins/flip_render.dart index a9a5bd23e..95aeb8df6 100644 --- a/lib/mixins/flip_render.dart +++ b/lib/mixins/flip_render.dart @@ -18,7 +18,7 @@ mixin FlipRender on GameComponent { bool get _needFlip => flipRenderVertically || flipRenderHorizonally; void _doFlip(Canvas canvas) { - Vector2 center = (size / 2); + final center = size / 2; canvas.save(); canvas.translate(center.x, center.y); canvas.scale( diff --git a/lib/mixins/interval_checker.dart b/lib/mixins/interval_checker.dart index db0523f66..736401823 100644 --- a/lib/mixins/interval_checker.dart +++ b/lib/mixins/interval_checker.dart @@ -12,7 +12,8 @@ import 'package:bonfire/bonfire.dart'; /// Rafaelbarbosatec /// on 17/05/22 mixin InternalChecker on Component { - /// Map available to store times that can be used to control the frequency of any action. + /// Map available to store times that can be used to control + /// the frequency of any action. Map? _timers; /// Returns true if for each time the defined millisecond interval passes. diff --git a/lib/mixins/jumper.dart b/lib/mixins/jumper.dart index c2c903b39..e513156c7 100644 --- a/lib/mixins/jumper.dart +++ b/lib/mixins/jumper.dart @@ -1,3 +1,5 @@ +// ignore_for_file: use_setters_to_change_properties + import 'package:bonfire/bonfire.dart'; import 'package:bonfire/util/collision_game_component.dart'; @@ -57,7 +59,9 @@ mixin Jumper on Movement, BlockMovementCollision { @override void onCollisionStart( - Set intersectionPoints, PositionComponent other) { + Set intersectionPoints, + PositionComponent other, + ) { if (other is CollisionMapComponent || other is TileWithCollision) { ++_tileCollisionCount; resetInterval(_tileCollisionCountKey); @@ -68,15 +72,21 @@ mixin Jumper on Movement, BlockMovementCollision { @override void onCollisionEnd(PositionComponent other) { if (other is CollisionMapComponent || other is TileWithCollision) { - if (--_tileCollisionCount == 0) resetInterval(_tileCollisionCountKey); + if (--_tileCollisionCount == 0) { + resetInterval(_tileCollisionCountKey); + } } super.onCollisionEnd(other); } @override void update(double dt) { - if (checkInterval(_tileCollisionCountKey, 100, dt, - firstCheckIsTrue: false) && + if (checkInterval( + _tileCollisionCountKey, + 100, + dt, + firstCheckIsTrue: false, + ) && !isJumping && _tileCollisionCount == 0 && displacement.y.abs() > 0.2) { diff --git a/lib/mixins/move_per_cell.dart b/lib/mixins/move_per_cell.dart index 3c706583d..179f6357c 100644 --- a/lib/mixins/move_per_cell.dart +++ b/lib/mixins/move_per_cell.dart @@ -29,7 +29,9 @@ mixin MovePerCell on Movement { @override void moveLeft({double? speed}) { if (_perCellEnabled) { - if (_perCellMoving) return; + if (_perCellMoving) { + return; + } _perCellMoving = true; add( MoveEffect.by( @@ -49,7 +51,9 @@ mixin MovePerCell on Movement { @override void moveRight({double? speed}) { if (_perCellEnabled) { - if (_perCellMoving) return; + if (_perCellMoving) { + return; + } _perCellMoving = true; add( MoveEffect.by( @@ -69,7 +73,9 @@ mixin MovePerCell on Movement { @override void moveDown({double? speed}) { if (_perCellEnabled) { - if (_perCellMoving) return; + if (_perCellMoving) { + return; + } _perCellMoving = true; add( MoveEffect.by( @@ -89,7 +95,9 @@ mixin MovePerCell on Movement { @override void moveUp({double? speed}) { if (_perCellEnabled) { - if (_perCellMoving) return; + if (_perCellMoving) { + return; + } _perCellMoving = true; add( MoveEffect.by( diff --git a/lib/mixins/movement.dart b/lib/mixins/movement.dart index 79cce457d..48e07e472 100644 --- a/lib/mixins/movement.dart +++ b/lib/mixins/movement.dart @@ -57,6 +57,7 @@ mixin Movement on GameComponent { } } + // ignore: use_setters_to_change_properties void correctPositionFromCollision(Vector2 position) { super.position = position; } @@ -185,7 +186,9 @@ mixin Movement on GameComponent { } void stopMove({bool forceIdle = false, bool isX = true, bool isY = true}) { - if (isIdle && !forceIdle) return; + if (isIdle && !forceIdle) { + return; + } setZeroVelocity(isX: isX, isY: isY); idle(); } @@ -292,8 +295,8 @@ mixin Movement on GameComponent { return; } - var normal = velocity.normalized()..absolute(); - double baseDiagonal = 0.2; + final normal = velocity.normalized()..absolute(); + const baseDiagonal = 0.2; if (velocity.x > 0 && velocity.y > 0) { if (normal.x > baseDiagonal && normal.y > baseDiagonal) { @@ -361,15 +364,15 @@ mixin Movement on GameComponent { double? speed, bool useCenter = true, }) { - double diagonalSpeed = (speed ?? this.speed) * diaginalReduction; - double dtSpeed = (speed ?? this.speed) * dtUpdate * 1.1; - double dtDiagonalSpeed = diagonalSpeed * dtUpdate * 1.1; + final diagonalSpeed = (speed ?? this.speed) * diaginalReduction; + final dtSpeed = (speed ?? this.speed) * dtUpdate * 1.1; + final dtDiagonalSpeed = diagonalSpeed * dtUpdate * 1.1; final rect = rectCollision; final compCenter = rect.centerVector2; final compPosition = rect.positionVector2; - double diffX = position.x - (useCenter ? compCenter : compPosition).x; - double diffY = position.y - (useCenter ? compCenter : compPosition).y; + final diffX = position.x - (useCenter ? compCenter : compPosition).x; + final diffY = position.y - (useCenter ? compCenter : compPosition).y; if (diffX.abs() < dtSpeed && diffY.abs() < dtSpeed) { return false; @@ -444,7 +447,7 @@ mixin Movement on GameComponent { double? displacement, Iterable? ignoreHitboxes, }) { - double maxDistance = displacement ?? (speed * (dtUpdate * 2)); + final maxDistance = displacement ?? (speed * (dtUpdate * 2)); switch (direction) { case Direction.right: @@ -529,26 +532,26 @@ mixin Movement on GameComponent { double maxDistance, { Iterable? ignoreHitboxes, }) { - double distance = maxDistance; + var distance = maxDistance; final centerComp = rectCollision.center.toVector2(); - Vector2 origin1 = centerComp; - Vector2 origin3 = centerComp; + var origin1 = centerComp; + var origin3 = centerComp; final size = rectCollision.sizeVector2; final vetorDirection = direction.toVector2(); switch (direction) { case Direction.right: case Direction.left: - double halfY = (size.y / 2); - double halfX = (size.y / 2); + final halfY = size.y / 2; + final halfX = size.y / 2; origin1 = origin1.translated(0, -halfY); origin3 = origin3.translated(0, halfY); distance += halfX; break; case Direction.up: case Direction.down: - double halfX = (size.x / 2); - double halfY = (size.y / 2); + final halfX = size.x / 2; + final halfY = size.y / 2; origin1 = origin1.translated(-halfX, 0); origin3 = origin3.translated(halfX, 0); distance += halfY; @@ -558,20 +561,20 @@ mixin Movement on GameComponent { case Direction.downLeft: case Direction.downRight: } - bool check1 = raycast( + final check1 = raycast( vetorDirection, maxDistance: distance, origin: origin1, ignoreHitboxes: ignoreHitboxes, ) != null; - bool check2 = raycast( + final check2 = raycast( vetorDirection, maxDistance: distance, ignoreHitboxes: ignoreHitboxes, ) != null; - bool check3 = raycast( + final check3 = raycast( vetorDirection, maxDistance: distance, origin: origin3, diff --git a/lib/mixins/movement_by_joystick.dart b/lib/mixins/movement_by_joystick.dart index fb893db54..4604f2a30 100644 --- a/lib/mixins/movement_by_joystick.dart +++ b/lib/mixins/movement_by_joystick.dart @@ -3,7 +3,8 @@ import 'package:bonfire/bonfire.dart'; enum MovementByJoystickType { direction, angle } class MovementByJoystickProps { - /// MovementByJoystickType.direction if you only want the 8 directions movement. + /// MovementByJoystickType.direction if you only want the + /// 8 directions movement. /// Set MovementByJoystickType.angle to have full 360 movement MovementByJoystickType moveType; bool intensityEnabled; diff --git a/lib/mixins/path_finding.dart b/lib/mixins/path_finding.dart index bb4273559..9b9516c7c 100644 --- a/lib/mixins/path_finding.dart +++ b/lib/mixins/path_finding.dart @@ -5,11 +5,14 @@ import 'dart:ui'; import 'package:a_star_algorithm/a_star_algorithm.dart'; import 'package:bonfire/bonfire.dart'; +import 'package:bonfire/util/extensions/color_extensions.dart'; +import 'package:bonfire/util/extensions/int_int_extensions.dart'; import 'package:bonfire/util/line_path_component.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; -/// Mixin responsible for find path using `a_star_algorithm` and moving the component through the path +/// Mixin responsible for find path using `a_star_algorithm` and +/// moving the component through the path mixin PathFinding on Movement { static const REDUCTION_TO_AVOID_ROUNDING_PROBLEMS = 4; @@ -23,14 +26,14 @@ mixin PathFinding on Movement { double _factorInflateFindArea = 2; VoidCallback? _onFinish; - final List> _barriers = []; + final List<(int, int)> _barriers = []; final List _ignoreCollisions = []; LinePathComponent? _linePathComponent; - Color _pathLineColor = const Color(0xFF40C4FF).withOpacity(0.5); + Color _pathLineColor = const Color(0xFF40C4FF).setOpacity(0.5); double _pathLineStrokeWidth = 4; final Paint _paintShowBarriers = Paint() - ..color = const Color(0xFF2196F3).withOpacity(0.5); + ..color = const Color(0xFF2196F3).setOpacity(0.5); void setupPathFinding({ bool? linePathEnabled, @@ -46,7 +49,8 @@ mixin PathFinding on Movement { bool showBarriersCalculated = false, bool useOnlyVisibleBarriers = true, - /// If `false` the algorithm use map tile size with base of the grid. if true this use collision size of the component. + /// If `false` the algorithm use map tile size with base of the grid. + /// if true this use collision size of the component. bool gridSizeIsCollisionSize = false, bool withDiagonal = true, double factorInflateFindArea = 2, @@ -56,12 +60,12 @@ mixin PathFinding on Movement { _useOnlyVisibleBarriers = useOnlyVisibleBarriers; _factorInflateFindArea = factorInflateFindArea; _paintShowBarriers.color = - barriersCalculatedColor ?? const Color(0xFF2196F3).withOpacity(0.5); + barriersCalculatedColor ?? const Color(0xFF2196F3).setOpacity(0.5); _showBarriers = showBarriersCalculated; _pathLineColor = pathLineColor ?? _pathLineColor; _pathLineStrokeWidth = pathLineStrokeWidth; - _pathLineColor = pathLineColor ?? const Color(0xFF40C4FF).withOpacity(0.5); + _pathLineColor = pathLineColor ?? const Color(0xFF40C4FF).setOpacity(0.5); _gridSizeIsCollisionSize = gridSizeIsCollisionSize; } @@ -154,38 +158,38 @@ mixin PathFinding on Movement { final positionPlayer = player.rectCollision.centerVector2; - Point playerPosition = _getCenterPositionByTile(positionPlayer); + final playerPosition = _getCenterPositionByTile(positionPlayer); - Point targetPosition = _getCenterPositionByTile(finalPosition); + final targetPosition = _getCenterPositionByTile(finalPosition); - double inflate = _tileSize * _factorInflateFindArea; + final inflate = _tileSize * _factorInflateFindArea; - int maxY = max( + final int maxY = max( playerPosition.y, targetPosition.y, ); - int maxX = max( + final int maxX = max( playerPosition.x, targetPosition.x, ); - int rows = maxY.toInt() + inflate.toInt(); + final rows = maxY + inflate.toInt(); - int columns = maxX.toInt() + inflate.toInt(); + final columns = maxX + inflate.toInt(); _barriers.clear(); - Rect area = Rect.fromPoints( + var area = Rect.fromPoints( positionPlayer.toOffset(), finalPosition.toOffset(), ); - double left = area.left; - double right = area.right; - double top = area.top; - double bottom = area.bottom; - double size = max(area.width, area.height); + var left = area.left; + var right = area.right; + var top = area.top; + var bottom = area.bottom; + final double size = max(area.width, area.height); if (positionPlayer.x < finalPosition.x) { left -= size; } else if (positionPlayer.x > finalPosition.x) { @@ -202,14 +206,14 @@ mixin PathFinding on Movement { for (final e in gameRef.collisions(onlyVisible: _useOnlyVisibleBarriers)) { if (!_ignoreCollisions.contains(e)) { - var rect = e.toAbsoluteRect(); + final rect = e.toAbsoluteRect(); if (area.overlaps(rect)) { _addCollisionOffsetsPositionByTile(rect); } } } - Iterable> result = []; + Iterable<(int, int)> result = []; if (_barriers.contains(targetPosition)) { stopMove(); @@ -227,7 +231,7 @@ mixin PathFinding on Movement { ).findThePath(); if (result.isNotEmpty || _isNeighbor(playerPosition, targetPosition)) { - result = AStar.resumePath(result); + result = AStar.simplifyPath(result); return _mapToWorldPositions(result); } } catch (e, stacktrace) { @@ -239,7 +243,7 @@ mixin PathFinding on Movement { /// Get size of the grid used on algorithm to calculate path double get _tileSize { - double tileSize = gameRef.map.tileSize; + final tileSize = gameRef.map.tileSize; if (_gridSizeIsCollisionSize) { final rect = rectCollision; return max(rect.height, rect.width) + @@ -250,58 +254,61 @@ mixin PathFinding on Movement { bool get isMovingAlongThePath => _currentPath.isNotEmpty; - Point _getCenterPositionByTile(Vector2 center) { - return Point( + (int, int) _getCenterPositionByTile(Vector2 center) { + return ( (center.x / _tileSize).floor(), (center.y / _tileSize).floor(), ); } - /// creating an imaginary grid would calculate how many tile this object is occupying. + /// creating an imaginary grid would calculate how many tile + /// this object is occupying. void _addCollisionOffsetsPositionByTile(Rect rect) { final leftTop = Offset( - ((rect.left / _tileSize).floor() * _tileSize), - ((rect.top / _tileSize).floor() * _tileSize), + (rect.left / _tileSize).floor() * _tileSize, + (rect.top / _tileSize).floor() * _tileSize, ); - List grid = []; - int countColumns = (rect.width / _tileSize).ceil() + 1; - int countRows = (rect.height / _tileSize).ceil() + 1; + final grid = []; + final countColumns = (rect.width / _tileSize).ceil() + 1; + final countRows = (rect.height / _tileSize).ceil() + 1; List.generate(countRows, (r) { List.generate(countColumns, (c) { - grid.add(Rect.fromLTWH( - leftTop.dx + - (c * _tileSize) + - REDUCTION_TO_AVOID_ROUNDING_PROBLEMS / 2, - leftTop.dy + - (r * _tileSize) + - REDUCTION_TO_AVOID_ROUNDING_PROBLEMS / 2, - _tileSize - REDUCTION_TO_AVOID_ROUNDING_PROBLEMS, - _tileSize - REDUCTION_TO_AVOID_ROUNDING_PROBLEMS, - )); + grid.add( + Rect.fromLTWH( + leftTop.dx + + (c * _tileSize) + + REDUCTION_TO_AVOID_ROUNDING_PROBLEMS / 2, + leftTop.dy + + (r * _tileSize) + + REDUCTION_TO_AVOID_ROUNDING_PROBLEMS / 2, + _tileSize - REDUCTION_TO_AVOID_ROUNDING_PROBLEMS, + _tileSize - REDUCTION_TO_AVOID_ROUNDING_PROBLEMS, + ), + ); }); }); - List listRect = grid.where((element) { + final listRect = grid.where((element) { return rect.overlaps(element); }).toList(); final result = listRect.map((e) { - return Point( + return ( (e.center.dx / _tileSize).floor(), (e.center.dy / _tileSize).floor(), ); }).toList(); - for (var element in result) { + for (final element in result) { if (!_barriers.contains(element)) { _barriers.add(element); } } } - bool _isNeighbor(Point playerPosition, Point targetPosition) { + bool _isNeighbor((int, int) playerPosition, (int, int) targetPosition) { if ((playerPosition.x - targetPosition.x).abs() == 1) { return true; } @@ -321,7 +328,7 @@ mixin PathFinding on Movement { void _drawBarrries(Canvas canvas) { if (_showBarriers) { - for (var element in _barriers) { + for (final element in _barriers) { canvas.drawRect( Rect.fromLTWH( element.x * _tileSize, @@ -358,7 +365,7 @@ mixin PathFinding on Movement { } } - List _mapToWorldPositions(Iterable> result) { + List _mapToWorldPositions(Iterable<(int, int)> result) { return result.map((e) { return Vector2(e.x * _tileSize, e.y * _tileSize) .translated(_tileSize / 2, _tileSize / 2); diff --git a/lib/mixins/pointer_detector.dart b/lib/mixins/pointer_detector.dart index 3d715eada..737857dc3 100644 --- a/lib/mixins/pointer_detector.dart +++ b/lib/mixins/pointer_detector.dart @@ -13,7 +13,7 @@ mixin PointerDetector { mixin PointerDetectorHandler on Component { // If return 'true' this event is not relay to others components. bool handlerPointerDown(PointerDownEvent event) { - for (var child in children) { + for (final child in children) { if (child is GameComponent) { if (child.handlerPointerDown(event)) { return true; @@ -25,7 +25,7 @@ mixin PointerDetectorHandler on Component { // If return 'true' this event is not relay to others components. bool handlerPointerMove(PointerMoveEvent event) { - for (var child in children) { + for (final child in children) { if (child is GameComponent) { if (child.handlerPointerMove(event)) { return true; @@ -37,7 +37,7 @@ mixin PointerDetectorHandler on Component { // If return 'true' this event is not relay to others components. bool handlerPointerUp(PointerUpEvent event) { - for (var child in children) { + for (final child in children) { if (child is GameComponent) { if (child.handlerPointerUp(event)) { return true; @@ -49,7 +49,7 @@ mixin PointerDetectorHandler on Component { // If return 'true' this event is not relay to others components. bool handlerPointerCancel(PointerCancelEvent event) { - for (var child in children) { + for (final child in children) { if (child is GameComponent) { if (child.handlerPointerCancel(event)) { return true; diff --git a/lib/mixins/pushable.dart b/lib/mixins/pushable.dart index d51e7c99b..96f7d0578 100644 --- a/lib/mixins/pushable.dart +++ b/lib/mixins/pushable.dart @@ -56,10 +56,10 @@ mixin Pushable on Movement { } case PushableFromEnum.ALL: } - GameComponent component = other; + final component = other; if (component is Movement && onPush(component)) { - Vector2 displacement = (rectCollision.centerVector2 - - component.rectCollision.centerVector2); + final displacement = rectCollision.centerVector2 - + component.rectCollision.centerVector2; if (_pushPerCellEnabled) { _movePercell(component, displacement); } else { @@ -111,7 +111,7 @@ mixin Pushable on Movement { if (_percellMoving) { return; } - Vector2 cellSize = _cellSize ?? size; + final cellSize = _cellSize ?? size; _percellMoving = true; if (displacement.x.abs() > displacement.y.abs()) { if (displacement.x < 0) { diff --git a/lib/mixins/random_movement.dart b/lib/mixins/random_movement.dart index bd0657bb9..df4cdf23a 100644 --- a/lib/mixins/random_movement.dart +++ b/lib/mixins/random_movement.dart @@ -32,7 +32,8 @@ class RandomMovementDirections { ); } -/// Mixin responsible for adding random movement like enemy walking through the scene +/// Mixin responsible for adding random movement like enemy +/// walking through the scene mixin RandomMovement on Movement { // ignore: constant_identifier_names static const _KEY_INTERVAL_KEEP_STOPPED = 'INTERVAL_RANDOM_MOVEMENT'; @@ -105,7 +106,7 @@ mixin RandomMovement on Movement { void correctPositionFromCollision(Vector2 position) { super.correctPositionFromCollision(position); if (this is Jumper) { - if ((this is BlockMovementCollision)) { + if (this is BlockMovementCollision) { final isV = (this as BlockMovementCollision) .lastCollisionData ?.direction @@ -157,12 +158,12 @@ mixin RandomMovement on Movement { bool checkDirectionWithRayCast, RandomMovementDirections directions, ) { - int index = 0; + var index = 0; while (index < 100) { final distance = _getDistance(minDistance, maxDistance); final direction = _getDirection(directions); final targetPosition = _getTargetPosition(direction, distance); - bool isRaycastOk = true; + var isRaycastOk = true; if (checkDirectionWithRayCast) { isRaycastOk = canMove( @@ -201,8 +202,9 @@ class _RandomPositionTarget { final Direction direction; final double distance; - _RandomPositionTarget( - {required this.position, - required this.direction, - required this.distance}); + _RandomPositionTarget({ + required this.position, + required this.direction, + required this.distance, + }); } diff --git a/lib/mixins/sensor.dart b/lib/mixins/sensor.dart index c517628ff..0f37a82b5 100644 --- a/lib/mixins/sensor.dart +++ b/lib/mixins/sensor.dart @@ -1,11 +1,12 @@ import 'dart:async'; import 'package:bonfire/bonfire.dart'; +import 'package:bonfire/util/extensions/color_extensions.dart'; /// Mixin responsible for adding trigger to detect other objects above /// T is a type that Sensor will be find contact. mixin Sensor on GameComponent { - static Color color = const Color(0xFFF44336).withOpacity(0.5); + static Color color = const Color(0xFFF44336).setOpacity(0.5); static const _sensorIntervalKey = 'SensorContact'; int _intervalCallback = 100; bool sensorEnabled = true; @@ -13,14 +14,14 @@ mixin Sensor on GameComponent { void onContact(T component) {} void onContactExit(T component) {} - void setSensorInterval(int intervalCallback) { + set sensorInterval(int intervalCallback) { _intervalCallback = intervalCallback; } @override Future onLoad() async { await super.onLoad(); - bool containsShape = children.query().isNotEmpty; + final containsShape = children.query().isNotEmpty; if (!containsShape) { add(RectangleHitbox(size: size, isSolid: true)); } diff --git a/lib/mixins/shader/shader_setter.dart b/lib/mixins/shader/shader_setter.dart index 582bb7780..5bf005f19 100644 --- a/lib/mixins/shader/shader_setter.dart +++ b/lib/mixins/shader/shader_setter.dart @@ -43,7 +43,7 @@ class ShaderSetter { void apply(FragmentShader shader) { _indexFloat = startFloatIndex; _indexImage = startImageIndex; - for (var item in values) { + for (final item in values) { if (item is SetterDouble) { _setFloat(shader, item.value); } @@ -58,10 +58,10 @@ class ShaderSetter { if (item is SetterColor) { final color = item.value; - _setFloat(shader, color.red / 255 * color.opacity); - _setFloat(shader, color.green / 255 * color.opacity); - _setFloat(shader, color.blue / 255 * color.opacity); - _setFloat(shader, color.opacity); + _setFloat(shader, color.r * color.a); + _setFloat(shader, color.g * color.a); + _setFloat(shader, color.b * color.a); + _setFloat(shader, color.a); } } } diff --git a/lib/mixins/shader/shader_util.dart b/lib/mixins/shader/shader_util.dart index f8d1a1320..59987e614 100644 --- a/lib/mixins/shader/shader_util.dart +++ b/lib/mixins/shader/shader_util.dart @@ -14,9 +14,9 @@ abstract class ShaderUtils { ui.Image? snapshot, }) { { - ui.Image? innerSnapshot = snapshot; - ui.PictureRecorder recorder = ui.PictureRecorder(); - ui.Canvas canvasRecorder = ui.Canvas(recorder); + var innerSnapshot = snapshot; + final recorder = ui.PictureRecorder(); + final canvasRecorder = ui.Canvas(recorder); canvasRecorder.scale(shaderCanvasScale); record(canvasRecorder); diff --git a/lib/mixins/shader/use_shader.dart b/lib/mixins/shader/use_shader.dart index e9494b7dc..bc4074016 100644 --- a/lib/mixins/shader/use_shader.dart +++ b/lib/mixins/shader/use_shader.dart @@ -1,8 +1,7 @@ import 'dart:ui' as ui; import 'package:bonfire/bonfire.dart'; - -import 'shader_util.dart'; +import 'package:bonfire/mixins/shader/shader_util.dart'; export 'shader_setter.dart'; @@ -45,7 +44,7 @@ mixin UseShader on PositionComponent { decoratorCanvas, (recorderCanvas) { render(recorderCanvas); - for (var c in children) { + for (final c in children) { c.renderTree(recorderCanvas); } }, diff --git a/lib/mixins/tile_recognizer.dart b/lib/mixins/tile_recognizer.dart index 4c37b9cb8..5f9b0ba7a 100644 --- a/lib/mixins/tile_recognizer.dart +++ b/lib/mixins/tile_recognizer.dart @@ -26,7 +26,9 @@ mixin TileRecognizer on GameComponent { /// Method that checks what types map tile is currently List tileTypeListBelow() { - if (!hasGameRef) return []; + if (!hasGameRef) { + return []; + } final map = gameRef.map; if (map.getRenderedTiles().isNotEmpty) { return tileListBelow().map((e) => e.tileClass!).toList(); @@ -46,7 +48,9 @@ mixin TileRecognizer on GameComponent { /// Method that checks what properties list map tile is currently List>? tilePropertiesListBelow() { - if (!hasGameRef) return null; + if (!hasGameRef) { + return null; + } final map = gameRef.map; if (map.layers.isNotEmpty) { return tileListBelow() @@ -58,12 +62,13 @@ mixin TileRecognizer on GameComponent { /// Method that checks what map tiles is below Iterable tileListBelow() { - if (!hasGameRef) return []; + if (!hasGameRef) { + return []; + } final map = gameRef.map; if (map.layers.isNotEmpty) { return map.getRenderedTiles().where((element) { - return (element.overlaps(rectCollision) && - (element.properties != null)); + return element.overlaps(rectCollision) && (element.properties != null); }); } return []; diff --git a/lib/mixins/update_camera_by_pinch_gesture.dart b/lib/mixins/update_camera_by_pinch_gesture.dart index 0340f6a9f..13dc652c9 100644 --- a/lib/mixins/update_camera_by_pinch_gesture.dart +++ b/lib/mixins/update_camera_by_pinch_gesture.dart @@ -1,6 +1,7 @@ import 'package:bonfire/bonfire.dart'; -// Mixin usend in component that use PinchGesture to update zoom and cameraposition in pich gestures. +// Mixin usend in component that use PinchGesture to update zoom and +//cameraposition in pich gestures. mixin UpdateCameraByPinchGesture on PinchGesture { double _initialZoom = 1.0; Vector2 _initialPosition = Vector2.zero(); @@ -20,8 +21,7 @@ mixin UpdateCameraByPinchGesture on PinchGesture { final scale = event.factorDistance; gameRef.camera.zoom = _initialZoom * scale; final diff = event.diffCenter; - gameRef.camera.position = - (_initialPosition - diff / (gameRef.camera.zoom)); + gameRef.camera.position = _initialPosition - diff / (gameRef.camera.zoom); } super.onPinchUpdate(event); diff --git a/lib/mixins/vision.dart b/lib/mixins/vision.dart index eb129ed55..ced038e95 100644 --- a/lib/mixins/vision.dart +++ b/lib/mixins/vision.dart @@ -3,13 +3,14 @@ import 'dart:math'; import 'package:bonfire/bonfire.dart'; import 'package:bonfire/geometry/polygon.dart'; import 'package:bonfire/geometry/rectangle.dart'; +import 'package:bonfire/util/extensions/color_extensions.dart'; import 'package:flutter/material.dart'; /// Mixin used to adds basic Vision to the component mixin Vision on GameComponent { // ignore: constant_identifier_names static const VISION_360 = 6.28319; - final Paint _paint = Paint()..color = Colors.red.withOpacity(0.5); + final Paint _paint = Paint()..color = Colors.red.setOpacity(0.5); bool _drawVision = false; bool _checkWithRaycast = true; final Map _polygonCache = {}; @@ -22,14 +23,15 @@ mixin Vision on GameComponent { bool checkWithRaycast = true, int countPolygonPoints = 20, }) { - assert(countPolygonPoints % 2 == 0, 'countPolygonPoints must be even'); + assert(countPolygonPoints.isEven, 'countPolygonPoints must be even'); _drawVision = drawVision; _checkWithRaycast = checkWithRaycast; _countPolygonPoints = countPolygonPoints; - _paint.color = color ?? Colors.red.withOpacity(0.5); + _paint.color = color ?? Colors.red.setOpacity(0.5); } - /// This method we notify when detect the component when enter in [radiusVision] configuration + /// This method we notify when detect the component when enter + /// in [radiusVision] configuration /// Method that bo used in [update] method. /// [visionAngle] in radians /// [angle] in radians. @@ -46,7 +48,7 @@ mixin Vision on GameComponent { return _currentShape = null; } - PolygonShape shape = _getShapeVision(radiusVision, visionAngle, angle); + final shape = _getShapeVision(radiusVision, visionAngle, angle); if (_canSee(shape, component, radiusVision)) { observed(component); @@ -71,12 +73,12 @@ mixin Vision on GameComponent { position: rect.positionVector2, ); - bool inShape = shape.isCollision(otherShape); + final inShape = shape.isCollision(otherShape); if (inShape) { if (_checkWithRaycast) { - Vector2 myCenter = rectCollision.center.toVector2(); - Vector2 compCenter = component.rectCollision.center.toVector2(); - Vector2 direction = (compCenter - myCenter).normalized(); + final myCenter = rectCollision.center.toVector2(); + final compCenter = component.rectCollision.center.toVector2(); + final direction = (compCenter - myCenter).normalized(); final result = raycast( direction, @@ -84,7 +86,7 @@ mixin Vision on GameComponent { origin: myCenter, ignoreHitboxes: _getCanNotSeenHitbox(), ); - var vParent = result?.hitbox?.parent; + final vParent = result?.hitbox?.parent; return vParent == component || vParent == null; } return true; @@ -93,27 +95,28 @@ mixin Vision on GameComponent { return false; } - /// This method we notify when detect components by type when enter in [radiusVision] configuration + /// This method we notify when detect components by type when enter + /// in [radiusVision] configuration /// Method that bo used in [update] method. /// [visionAngle] in radians /// [angle] in radians. PolygonShape? seeComponentType({ - required Function(List) observed, + required void Function(List) observed, VoidCallback? notObserved, double radiusVision = 32, double? visionAngle, double angle = 3.14159, }) { - var compVisible = gameRef.visibles(); + final compVisible = gameRef.visibles(); if (compVisible.isEmpty) { notObserved?.call(); return _currentShape = null; } - PolygonShape shape = _getShapeVision(radiusVision, visionAngle, angle); + final shape = _getShapeVision(radiusVision, visionAngle, angle); - List compObserved = compVisible.where((comp) { + final compObserved = compVisible.where((comp) { return _canSee(shape, comp, radiusVision); }).toList(); @@ -131,34 +134,38 @@ mixin Vision on GameComponent { double angle, Vector2 position, ) { - double angleV = angleVision ?? VISION_360; - double nextX = radiusVision * cos(angle); - double nextY = radiusVision * sin(angle); - Offset point = Offset(nextX, nextY); - List pointsP = []; + final angleV = angleVision ?? VISION_360; + final nextX = radiusVision * cos(angle); + final nextY = radiusVision * sin(angle); + final point = Offset(nextX, nextY); + final pointsP = []; List.generate(_countPolygonPoints ~/ 2, (index) { if (index == 0) { - pointsP.add(point - .rotate(angleV / _countPolygonPoints, Offset.zero) - .toVector2()); + pointsP.add( + point.rotate(angleV / _countPolygonPoints, Offset.zero).toVector2(), + ); } else { - pointsP.add(pointsP.last - .toOffset() - .rotate(angleV / _countPolygonPoints, Offset.zero) - .toVector2()); + pointsP.add( + pointsP.last + .toOffset() + .rotate(angleV / _countPolygonPoints, Offset.zero) + .toVector2(), + ); } }); - List pointsN = []; + final pointsN = []; List.generate(_countPolygonPoints ~/ 2, (index) { if (index == 0) { - pointsN.add(point - .rotate(angleV / -_countPolygonPoints, Offset.zero) - .toVector2()); + pointsN.add( + point.rotate(angleV / -_countPolygonPoints, Offset.zero).toVector2(), + ); } else { - pointsN.add(pointsN.last - .toOffset() - .rotate(angleV / -_countPolygonPoints, Offset.zero) - .toVector2()); + pointsN.add( + pointsN.last + .toOffset() + .rotate(angleV / -_countPolygonPoints, Offset.zero) + .toVector2(), + ); } }); @@ -199,9 +206,9 @@ mixin Vision on GameComponent { double? visionAngle, double angle, ) { - String key = '$radiusVision/$visionAngle/$angle'; + final key = '$radiusVision/$visionAngle/$angle'; PolygonShape shape; - var center = rectCollision.centerVector2; + final center = rectCollision.centerVector2; if (_polygonCache.containsKey(key)) { shape = _polygonCache[key]!; shape.position = center; @@ -213,7 +220,7 @@ mixin Vision on GameComponent { } List _getCanNotSeenHitbox() { - var sensorHitBox = []; + final sensorHitBox = []; gameRef.query(onlyVisible: true).forEach((e) { sensorHitBox.addAll(e.children.query()); }); diff --git a/lib/npc/ally/rotation_ally.dart b/lib/npc/ally/rotation_ally.dart index 76452091a..3a2b49cdb 100644 --- a/lib/npc/ally/rotation_ally.dart +++ b/lib/npc/ally/rotation_ally.dart @@ -18,29 +18,26 @@ class RotationAlly extends Ally with UseSpriteAnimation, UseAssetsLoader { SpriteAnimation? animRun; RotationAlly({ - required Vector2 position, - required Vector2 size, + required super.position, + required super.size, required Future animIdle, required Future animRun, double currentRadAngle = -1.55, - double speed = 100, - double life = 100, - AcceptableAttackOriginEnum receivesAttackFrom = - AcceptableAttackOriginEnum.ENEMY, - }) : super( - position: position, - size: size, - life: life, - speed: speed, - receivesAttackFrom: receivesAttackFrom, - ) { + super.speed, + super.life = 100, + super.receivesAttackFrom, + }) { angle = currentRadAngle; - loader?.add(AssetToLoad(animIdle, (value) { - this.animIdle = value; - })); - loader?.add(AssetToLoad(animRun, (value) { - this.animRun = value; - })); + loader?.add( + AssetToLoad(animIdle, (value) { + this.animIdle = value; + }), + ); + loader?.add( + AssetToLoad(animRun, (value) { + this.animRun = value; + }), + ); } @override diff --git a/lib/npc/ally/simple_ally.dart b/lib/npc/ally/simple_ally.dart index 50b3ceeb0..a1fb501e2 100644 --- a/lib/npc/ally/simple_ally.dart +++ b/lib/npc/ally/simple_ally.dart @@ -1,9 +1,7 @@ -import 'package:bonfire/mixins/attackable.dart'; import 'package:bonfire/mixins/direction_animation.dart'; import 'package:bonfire/npc/ally/ally.dart'; import 'package:bonfire/util/direction.dart'; import 'package:bonfire/util/direction_animations/simple_direction_animation.dart'; -import 'package:flame/components.dart'; /// /// Created by @@ -20,21 +18,14 @@ import 'package:flame/components.dart'; /// Enemy with animation in all direction class SimpleAlly extends Ally with DirectionAnimation { SimpleAlly({ - required Vector2 position, - required Vector2 size, + required super.position, + required super.size, SimpleDirectionAnimation? animation, - double life = 100, - double speed = 100, + super.life = 100, + super.speed, Direction initDirection = Direction.right, - AcceptableAttackOriginEnum receivesAttackFrom = - AcceptableAttackOriginEnum.ENEMY, - }) : super( - position: position, - size: size, - life: life, - speed: speed, - receivesAttackFrom: receivesAttackFrom, - ) { + super.receivesAttackFrom, + }) { this.animation = animation; lastDirection = initDirection; lastDirectionHorizontal = diff --git a/lib/npc/enemy/enemy.dart b/lib/npc/enemy/enemy.dart index dd0676b18..da4585ebb 100644 --- a/lib/npc/enemy/enemy.dart +++ b/lib/npc/enemy/enemy.dart @@ -1,6 +1,5 @@ import 'package:bonfire/mixins/attackable.dart'; import 'package:bonfire/npc/npc.dart'; -import 'package:flame/components.dart'; export 'platform_enemy.dart'; export 'rotation_enemy.dart'; @@ -9,13 +8,13 @@ export 'simple_enemy.dart'; /// It is used to represent your enemies. class Enemy extends Npc with Attackable { Enemy({ - required Vector2 position, - required Vector2 size, + required super.position, + required super.size, double life = 10, - double? speed, + super.speed, AcceptableAttackOriginEnum receivesAttackFrom = AcceptableAttackOriginEnum.PLAYER_AND_ALLY, - }) : super(position: position, size: size, speed: speed) { + }) { this.receivesAttackFrom = receivesAttackFrom; initialLife(life); } diff --git a/lib/npc/enemy/platform_enemy.dart b/lib/npc/enemy/platform_enemy.dart index 481ec606e..fd36f2687 100644 --- a/lib/npc/enemy/platform_enemy.dart +++ b/lib/npc/enemy/platform_enemy.dart @@ -6,14 +6,11 @@ class PlatformEnemy extends SimpleEnemy required super.position, required super.size, PlatformAnimations? animation, - Direction initDirection = Direction.right, - double? speed, - double life = 100, + super.initDirection, + super.speed, + super.life, int countJumps = 1, }) : super( - initDirection: initDirection, - speed: speed, - life: life, animation: animation?.toSimpleDirectionAnimation(), ) { setupJumper(maxJump: countJumps); diff --git a/lib/npc/enemy/rotation_enemy.dart b/lib/npc/enemy/rotation_enemy.dart index 0385d78bf..df3c57f63 100644 --- a/lib/npc/enemy/rotation_enemy.dart +++ b/lib/npc/enemy/rotation_enemy.dart @@ -6,29 +6,26 @@ class RotationEnemy extends Enemy with UseSpriteAnimation, UseAssetsLoader { SpriteAnimation? animRun; RotationEnemy({ - required Vector2 position, - required Vector2 size, + required super.position, + required super.size, required Future animIdle, required Future animRun, double currentRadAngle = -1.55, - double? speed, - double life = 100, - AcceptableAttackOriginEnum receivesAttackFrom = - AcceptableAttackOriginEnum.PLAYER_AND_ALLY, - }) : super( - position: position, - size: size, - life: life, - speed: speed, - receivesAttackFrom: receivesAttackFrom, - ) { + super.speed, + super.life = 100, + super.receivesAttackFrom, + }) { angle = currentRadAngle; - loader?.add(AssetToLoad(animIdle, (value) { - this.animIdle = value; - })); - loader?.add(AssetToLoad(animRun, (value) { - this.animRun = value; - })); + loader?.add( + AssetToLoad(animIdle, (value) { + this.animIdle = value; + }), + ); + loader?.add( + AssetToLoad(animRun, (value) { + this.animRun = value; + }), + ); } @override diff --git a/lib/npc/enemy/simple_enemy.dart b/lib/npc/enemy/simple_enemy.dart index 3295d29e2..76e096e34 100644 --- a/lib/npc/enemy/simple_enemy.dart +++ b/lib/npc/enemy/simple_enemy.dart @@ -1,29 +1,19 @@ -import 'package:bonfire/mixins/attackable.dart'; import 'package:bonfire/mixins/direction_animation.dart'; +import 'package:bonfire/npc/enemy/enemy.dart'; import 'package:bonfire/util/direction.dart'; import 'package:bonfire/util/direction_animations/simple_direction_animation.dart'; -import 'package:flame/components.dart'; - -import 'enemy.dart'; /// Enemy with animation in all direction class SimpleEnemy extends Enemy with DirectionAnimation { SimpleEnemy({ - required Vector2 position, - required Vector2 size, + required super.position, + required super.size, SimpleDirectionAnimation? animation, - double life = 100, - double? speed, + super.life = 100, + super.speed, Direction initDirection = Direction.right, - AcceptableAttackOriginEnum receivesAttackFrom = - AcceptableAttackOriginEnum.PLAYER_AND_ALLY, - }) : super( - position: position, - size: size, - life: life, - speed: speed, - receivesAttackFrom: receivesAttackFrom, - ) { + super.receivesAttackFrom, + }) { this.animation = animation; lastDirection = initDirection; lastDirectionHorizontal = diff --git a/lib/npc/rotation_npc.dart b/lib/npc/rotation_npc.dart index 3365b7731..e5c8fa892 100644 --- a/lib/npc/rotation_npc.dart +++ b/lib/npc/rotation_npc.dart @@ -18,24 +18,24 @@ class RotationNpc extends Npc with UseSpriteAnimation, UseAssetsLoader { SpriteAnimation? animRun; RotationNpc({ - required Vector2 position, - required Vector2 size, + required super.position, + required super.size, required Future animIdle, required Future animRun, double currentRadAngle = -1.55, - double? speed, - }) : super( - position: position, - size: size, - speed: speed, - ) { + super.speed, + }) { angle = currentRadAngle; - loader?.add(AssetToLoad(animIdle, (value) { - this.animIdle = value; - })); - loader?.add(AssetToLoad(animRun, (value) { - this.animRun = value; - })); + loader?.add( + AssetToLoad(animIdle, (value) { + this.animIdle = value; + }), + ); + loader?.add( + AssetToLoad(animRun, (value) { + this.animRun = value; + }), + ); } @override diff --git a/lib/npc/simple_npc.dart b/lib/npc/simple_npc.dart index 14ff97c34..e51403cd7 100644 --- a/lib/npc/simple_npc.dart +++ b/lib/npc/simple_npc.dart @@ -1,8 +1,7 @@ +import 'package:bonfire/mixins/direction_animation.dart'; import 'package:bonfire/npc/npc.dart'; import 'package:bonfire/util/direction.dart'; import 'package:bonfire/util/direction_animations/simple_direction_animation.dart'; -import 'package:bonfire/mixins/direction_animation.dart'; -import 'package:flame/components.dart'; /// /// Created by @@ -19,16 +18,12 @@ import 'package:flame/components.dart'; /// Enemy with animation in all direction class SimpleNpc extends Npc with DirectionAnimation { SimpleNpc({ - required Vector2 position, - required Vector2 size, + required super.position, + required super.size, SimpleDirectionAnimation? animation, - double? speed, + super.speed, Direction initDirection = Direction.right, - }) : super( - position: position, - size: size, - speed: speed, - ) { + }) { this.animation = animation; lastDirection = initDirection; lastDirectionHorizontal = diff --git a/lib/objects/animated_game_object.dart b/lib/objects/animated_game_object.dart index f3e12f374..dbdb8ab30 100644 --- a/lib/objects/animated_game_object.dart +++ b/lib/objects/animated_game_object.dart @@ -23,18 +23,20 @@ class AnimatedGameObject extends GameObject with UseSpriteAnimation { super.objectPriority, super.renderAboveComponents, }) : super(sprite: null) { - loader?.add(AssetToLoad( - animation, - (value) { - setAnimation( - value, - size: size, - onFinish: _onFinish, - onStart: onStart, - loop: loop, - ); - }, - )); + loader?.add( + AssetToLoad( + animation, + (value) { + setAnimation( + value, + size: size, + onFinish: _onFinish, + onStart: onStart, + loop: loop, + ); + }, + ), + ); } void _onFinish() { diff --git a/lib/objects/flying_attack_game_object.dart b/lib/objects/flying_attack_game_object.dart index 6e02cb38c..9679b96de 100644 --- a/lib/objects/flying_attack_game_object.dart +++ b/lib/objects/flying_attack_game_object.dart @@ -129,7 +129,9 @@ class FlyingAttackGameObject extends AnimatedGameObject } void _destroyObject(GameComponent component) { - if (isRemoving || isRemoved) return; + if (isRemoving || isRemoved) { + return; + } removeAll(children); removeFromParent(); if (animationDestroy != null) { @@ -155,15 +157,15 @@ class FlyingAttackGameObject extends AnimatedGameObject void _destroyByDirection(Direction direction) { Vector2 positionDestroy; - double biggerSide = max(width, height); + final double biggerSide = max(width, height); double addCenterX = 0; double addCenterY = 0; const double divisionFactor = 2; if (destroySize != null) { - addCenterX = ((size.x - destroySize!.x) / divisionFactor); - addCenterY = ((size.y - destroySize!.y) / divisionFactor); + addCenterX = (size.x - destroySize!.x) / divisionFactor; + addCenterY = (size.y - destroySize!.y) / divisionFactor; } switch (direction) { case Direction.left: @@ -217,10 +219,10 @@ class FlyingAttackGameObject extends AnimatedGameObject } if (hasGameRef) { - Vector2 innerSize = destroySize ?? size; + final innerSize = destroySize ?? size; gameRef.add( AnimatedGameObject( - animation: animationDestroy!, + animation: animationDestroy, position: positionDestroy, size: innerSize, lightingConfig: lightingConfig, @@ -240,12 +242,12 @@ class FlyingAttackGameObject extends AnimatedGameObject } void _destroyByAngle() { - double nextX = (width / 2) * _cosAngle; - double nextY = (height / 2) * _senAngle; + final nextX = (width / 2) * _cosAngle; + final nextY = (height / 2) * _senAngle; - Vector2 innerSize = destroySize ?? size; + final innerSize = destroySize ?? size; final rect = rectCollision; - Offset diffBase = Offset( + final diffBase = Offset( rect.center.dx + nextX, rect.center.dy + nextY, ) - @@ -256,7 +258,7 @@ class FlyingAttackGameObject extends AnimatedGameObject if (hasGameRef) { gameRef.add( AnimatedGameObject( - animation: animationDestroy!, + animation: animationDestroy, position: Rect.fromCenter( center: positionDestroy.toOffset(), width: innerSize.x, diff --git a/lib/objects/game_object.dart b/lib/objects/game_object.dart index 4bfa3922c..1f9737725 100644 --- a/lib/objects/game_object.dart +++ b/lib/objects/game_object.dart @@ -11,7 +11,6 @@ class GameObject extends GameComponent required Vector2 position, required Vector2 size, required FutureOr? sprite, - Vector2? positionFromTarget, LightingConfig? lightingConfig, this.objectPriority, double angle = 0, @@ -23,7 +22,7 @@ class GameObject extends GameComponent this.position = position; this.size = size; this.angle = angle; - loader?.add(AssetToLoad(sprite, (value) => this.sprite = value)); + loader?.add(AssetToLoad(sprite, (value) => this.sprite = value)); setupLighting(lightingConfig); } diff --git a/lib/parallax/camera_parallax.dart b/lib/parallax/camera_parallax.dart index 1cf30c422..b09742bf0 100644 --- a/lib/parallax/camera_parallax.dart +++ b/lib/parallax/camera_parallax.dart @@ -52,11 +52,12 @@ class CameraParallax extends Parallax { final _delta = Vector2.zero(); void moveParallax(Vector2 velocity, double dt) { - for (var layer in layers) { + for (final layer in layers) { layer.update( _delta ..setFrom( - Vector2(baseVelocity.x * velocity.x, baseVelocity.y * velocity.y)) + Vector2(baseVelocity.x * velocity.x, baseVelocity.y * velocity.y), + ) ..multiply(layer.velocityMultiplier) ..scale(dt), dt, @@ -69,7 +70,7 @@ extension IterableExtension on Iterable { /// Maps each element and its index to a new value. Iterable mapIndexed(R Function(int index, T element) convert) sync* { var index = 0; - for (var element in this) { + for (final element in this) { yield convert(index++, element); } } diff --git a/lib/parallax/camera_parallax_componet.dart b/lib/parallax/camera_parallax_componet.dart index c2608f1c0..d07ddcbe1 100644 --- a/lib/parallax/camera_parallax_componet.dart +++ b/lib/parallax/camera_parallax_componet.dart @@ -60,9 +60,9 @@ class CameraParallaxComponent extends ParallaxComponent with BonfireHasGameRef { void update(double dt) { final campP = gameRef.camera.position; if (campP != _camPosition) { - Vector2 velocity = campP - _camPosition; + final velocity = campP - _camPosition; _camPosition = campP.clone(); - (parallax as CameraParallax).moveParallax(velocity, dt); + (parallax! as CameraParallax).moveParallax(velocity, dt); } } } diff --git a/lib/player/platform_player.dart b/lib/player/platform_player.dart index e294f99a0..1853fac52 100644 --- a/lib/player/platform_player.dart +++ b/lib/player/platform_player.dart @@ -6,14 +6,11 @@ class PlatformPlayer extends SimplePlayer required super.position, required super.size, PlatformAnimations? animation, - Direction initDirection = Direction.right, - double? speed, - double life = 100, + super.initDirection, + super.speed, + super.life, int countJumps = 1, }) : super( - initDirection: initDirection, - speed: speed, - life: life, animation: animation?.toSimpleDirectionAnimation(), ) { setupJumper(maxJump: countJumps); @@ -21,7 +18,7 @@ class PlatformPlayer extends SimplePlayer @override void onJoystickChangeDirectional(JoystickDirectionalEvent event) { - JoystickMoveDirectional newDirectional = JoystickMoveDirectional.IDLE; + var newDirectional = JoystickMoveDirectional.IDLE; if (event.directional.isRight) { newDirectional = JoystickMoveDirectional.MOVE_RIGHT; diff --git a/lib/player/rotation_player.dart b/lib/player/rotation_player.dart index 006cf14d7..0b603420a 100644 --- a/lib/player/rotation_player.dart +++ b/lib/player/rotation_player.dart @@ -7,25 +7,30 @@ class RotationPlayer extends Player with UseSpriteAnimation, UseAssetsLoader { bool _isRunning = false; RotationPlayer({ - required Vector2 position, - required Vector2 size, + required super.position, + required super.size, required Future animIdle, required Future animRun, - double? speed, + super.speed, double currentRadAngle = -1.55, - double life = 100, - }) : super( - position: position, - size: size, - life: life, - speed: speed, - ) { + super.life, + }) { setupMovementByJoystick( moveType: MovementByJoystickType.angle, ); movementByJoystickRadAngle = currentRadAngle; - loader?.add(AssetToLoad(animIdle, (value) => this.animIdle = value)); - loader?.add(AssetToLoad(animRun, (value) => this.animRun = value)); + loader?.add( + AssetToLoad( + animIdle, + (value) => this.animIdle = value, + ), + ); + loader?.add( + AssetToLoad( + animRun, + (value) => this.animRun = value, + ), + ); } @override diff --git a/lib/player/simple_player.dart b/lib/player/simple_player.dart index 59ed67506..b93f822e5 100644 --- a/lib/player/simple_player.dart +++ b/lib/player/simple_player.dart @@ -3,18 +3,13 @@ import 'package:bonfire/mixins/direction_animation.dart'; class SimplePlayer extends Player with DirectionAnimation { SimplePlayer({ - required Vector2 position, - required Vector2 size, + required super.position, + required super.size, SimpleDirectionAnimation? animation, Direction initDirection = Direction.right, - double? speed, - double life = 100, - }) : super( - position: position, - size: size, - life: life, - speed: speed, - ) { + super.speed, + super.life, + }) { this.animation = animation; lastDirection = initDirection; if (initDirection == Direction.left || initDirection == Direction.right) { diff --git a/lib/scene_builder/actions/camera_scene_action.dart b/lib/scene_builder/actions/camera_scene_action.dart index cca50d363..d319f8c31 100644 --- a/lib/scene_builder/actions/camera_scene_action.dart +++ b/lib/scene_builder/actions/camera_scene_action.dart @@ -26,13 +26,13 @@ class CameraSceneAction extends SceneAction { bool _done = false; CameraSceneAction({ + required this.duration, dynamic id, this.position, this.target, this.zoom, this.angle, this.curve = widget.Curves.decelerate, - required this.duration, }) : super(id); CameraSceneAction.position( this.position, { diff --git a/lib/scene_builder/actions/move_to_position_scene_action.dart b/lib/scene_builder/actions/move_to_position_scene_action.dart index 39b98365e..08304bd04 100644 --- a/lib/scene_builder/actions/move_to_position_scene_action.dart +++ b/lib/scene_builder/actions/move_to_position_scene_action.dart @@ -22,28 +22,28 @@ class MoveToPositionSceneAction extends SceneAction { Vector2 _diffPosition = Vector2.zero(); MoveToPositionSceneAction({ - dynamic id, required this.component, required this.newPosition, + dynamic id, }) : super(id); @override bool runAction(double dt, BonfireGameInterface game) { - var diffPosition = newPosition - component.position; + final diffPosition = newPosition - component.position; - var dtSpeed = component.speed * dt; + final dtSpeed = component.speed * dt; if (diffPosition.x.abs() < dtSpeed && diffPosition.y.abs() < dtSpeed) { component.stopMove(); return true; } - var d = _diffPosition - diffPosition; + final d = _diffPosition - diffPosition; if (d.isZero()) { component.stopMove(); return true; } _diffPosition = diffPosition; - var radAngle = atan2(diffPosition.y, diffPosition.x); + final radAngle = atan2(diffPosition.y, diffPosition.x); component.moveFromAngle(radAngle); return false; } diff --git a/lib/scene_builder/scene_builder.dart b/lib/scene_builder/scene_builder.dart index 4c7275e3d..443527dfe 100644 --- a/lib/scene_builder/scene_builder.dart +++ b/lib/scene_builder/scene_builder.dart @@ -1,19 +1,8 @@ -/// -/// Created by -/// -/// ─▄▀─▄▀ -/// ──▀──▀ -/// █▀▀▀▀▀█▄ -/// █░░░░░█─█ -/// ▀▄▄▄▄▄▀▀ -/// -/// Rafaelbarbosatec -/// on 04/03/22 +export 'actions/await_scene_action.dart'; export 'actions/callback_scene_action.dart'; export 'actions/camera_scene_action.dart'; export 'actions/delay_scene_action.dart'; export 'actions/move_to_position_scene_action.dart'; export 'actions/move_while_scene_action.dart'; -export 'actions/await_scene_action.dart'; export 'scene_action.dart'; export 'scene_manager_component.dart'; diff --git a/lib/util/barlife_component.dart b/lib/util/barlife_component.dart index a41436379..1c165ab31 100644 --- a/lib/util/barlife_component.dart +++ b/lib/util/barlife_component.dart @@ -72,8 +72,8 @@ class BarLifeComponent extends GameComponent { @override void render(Canvas canvas) { - double yPosition = (y - height); - double xPosition = (target.size.x - width) / 2; + var yPosition = y - height; + var xPosition = (target.size.x - width) / 2; switch (drawPosition) { case BarLifeDrawPosition.top: break; @@ -90,10 +90,10 @@ class BarLifeComponent extends GameComponent { break; } - double currentBarLife = (_life * width) / _maxLife; + final currentBarLife = (_life * width) / _maxLife; if (borderWidth > 0) { - final RRect borderRect = borderRadius.toRRect( + final borderRect = borderRadius.toRRect( Rect.fromLTWH( xPosition, yPosition, @@ -108,24 +108,28 @@ class BarLifeComponent extends GameComponent { ); } - final RRect bgRect = borderRadius.toRRect(Rect.fromLTWH( - xPosition, - yPosition, - width, - height, - )); + final bgRect = borderRadius.toRRect( + Rect.fromLTWH( + xPosition, + yPosition, + width, + height, + ), + ); canvas.drawRRect( bgRect, _barLifeBgPaint, ); - final RRect lifeRect = borderRadius.toRRect(Rect.fromLTWH( - xPosition, - yPosition, - currentBarLife, - height, - )); + final lifeRect = borderRadius.toRRect( + Rect.fromLTWH( + xPosition, + yPosition, + currentBarLife, + height, + ), + ); canvas.drawRRect( lifeRect, @@ -143,8 +147,8 @@ class BarLifeComponent extends GameComponent { ); if (showLifeText) { - double xText = _textOffset.x + xPosition + (width - _textSize.x) / 2; - double yText = _textOffset.y + yPosition + (height - _textSize.y) / 2; + final xText = _textOffset.x + xPosition + (width - _textSize.x) / 2; + final yText = _textOffset.y + yPosition + (height - _textSize.y) / 2; _textConfig.render( canvas, _getLifeText(), @@ -161,7 +165,7 @@ class BarLifeComponent extends GameComponent { List colors, ) { final parts = maxWidth / colors.length; - int index = (currentBarLife / parts).ceil() - 1; + final index = (currentBarLife / parts).ceil() - 1; if (index < 0) { return colors[0]; } diff --git a/lib/util/bonfire_util.dart b/lib/util/bonfire_util.dart index cc4dbf3dc..29eb5d0b0 100644 --- a/lib/util/bonfire_util.dart +++ b/lib/util/bonfire_util.dart @@ -4,13 +4,13 @@ import 'package:bonfire/bonfire.dart'; class BonfireUtil { // ignore: constant_identifier_names - static const PI_180 = (180 / pi); + static const PI_180 = 180 / pi; static Direction getDirectionFromAngle( double angle, { double directionSpace = 2.5, }) { - double degrees = angle * PI_180; + final degrees = angle * PI_180; if (degrees > -directionSpace && degrees <= directionSpace) { return Direction.right; } @@ -68,8 +68,6 @@ class BonfireUtil { return 135 / PI_180; case Direction.downRight: return 45 / PI_180; - default: - return 0; } } @@ -85,11 +83,11 @@ class BonfireUtil { final s = sin(angle); final c = cos(angle); - double x1 = point.dx - center.dx; - double y1 = point.dy - center.dy; + final x1 = point.dx - center.dx; + final y1 = point.dy - center.dy; - double x2 = x1 * c - y1 * s; - double y2 = x1 * s + y1 * c; + final x2 = x1 * c - y1 * s; + final y2 = x1 * s + y1 * c; return Offset(x2 + center.dx, y2 + center.dy); } @@ -99,8 +97,8 @@ class BonfireUtil { double speed, double angle, ) { - double nextX = speed * cos(angle); - double nextY = speed * sin(angle); + final nextX = speed * cos(angle); + final nextY = speed * sin(angle); return Vector2(point.x + nextX, point.y + nextY); } diff --git a/lib/util/collision_game_component.dart b/lib/util/collision_game_component.dart index f286235b3..e92145a02 100644 --- a/lib/util/collision_game_component.dart +++ b/lib/util/collision_game_component.dart @@ -17,10 +17,10 @@ class CollisionMapComponent extends GameComponent { List? collisions; CollisionMapComponent({ - this.name = '', - Map? properties, required Vector2 position, required Vector2 size, + this.name = '', + Map? properties, this.collisions, }) { this.properties = properties; diff --git a/lib/util/component_spawner.dart b/lib/util/component_spawner.dart index 284580d07..ec22ef69b 100644 --- a/lib/util/component_spawner.dart +++ b/lib/util/component_spawner.dart @@ -44,8 +44,8 @@ class ComponentSpawner extends GameComponent { } void _spawn() { - Vector2 point = Vector2.zero(); - int count = 0; + var point = Vector2.zero(); + var count = 0; do { point = Vector2( size.x * _random.nextDouble(), diff --git a/lib/util/controlled_update_animation.dart b/lib/util/controlled_update_animation.dart index 83dd16326..1b82c5838 100644 --- a/lib/util/controlled_update_animation.dart +++ b/lib/util/controlled_update_animation.dart @@ -10,15 +10,17 @@ class ControlledUpdateAnimation { ControlledUpdateAnimation(Future animation, Vector2 size) { _loader = AssetsLoader(); - _loader?.add(AssetToLoad( - animation, - (value) { - this.animation = SpriteAnimationRender( - animation: value, - size: size, - ); - }, - )); + _loader?.add( + AssetToLoad( + animation, + (value) { + this.animation = SpriteAnimationRender( + animation: value, + size: size, + ); + }, + ), + ); } ControlledUpdateAnimation.fromSpriteAnimation(SpriteAnimation animation) { diff --git a/lib/util/damage_hitbox.dart b/lib/util/damage_hitbox.dart index f1ed2e4de..e6721751b 100644 --- a/lib/util/damage_hitbox.dart +++ b/lib/util/damage_hitbox.dart @@ -13,11 +13,11 @@ class DamageHitbox extends GameComponent { final Paint _paint = Paint()..color = Sensor.color; DamageHitbox({ - this.id, required Vector2 position, required this.damage, required this.origin, required Vector2 size, + this.id, double angle = 0, this.onDamage, Anchor anchor = Anchor.center, diff --git a/lib/util/direction_animations/render_transform_warpper.dart b/lib/util/direction_animations/render_transform_warpper.dart index 7dbfc9206..b67eb6580 100644 --- a/lib/util/direction_animations/render_transform_warpper.dart +++ b/lib/util/direction_animations/render_transform_warpper.dart @@ -9,14 +9,14 @@ class RenderTransformWrapper { RenderTransformWrapper({required this.transforms, required this.render}); void execRender(Canvas canvas, Paint paint) { - int index = 0; + var index = 0; for (final transform in transforms) { if (transform.transform(canvas)) { index++; } } render(canvas, paint); - for (int i = 0; i < index; i++) { + for (var i = 0; i < index; i++) { canvas.restore(); } } @@ -38,7 +38,7 @@ class CenterAdjustRenderTransform extends RenderTransformer { return false; } canvas.save(); - Vector2 diff = data.center - data.newCenter; + final diff = data.center - data.newCenter; canvas.translate(diff.x, diff.y); return true; } diff --git a/lib/util/direction_animations/simple_direction_animation.dart b/lib/util/direction_animations/simple_direction_animation.dart index 91de16d4a..a10cfb485 100644 --- a/lib/util/direction_animations/simple_direction_animation.dart +++ b/lib/util/direction_animations/simple_direction_animation.dart @@ -123,33 +123,97 @@ class SimpleDirectionAnimation { this.eightDirection = false, this.centerAnchor, }) { - _loader?.add(AssetToLoad(idleLeft, (value) => _idleLeftAnim = value)); - _loader?.add(AssetToLoad(idleRight, (value) => _idleRightAnim = value)); - _loader?.add(AssetToLoad(idleDown, (value) => _idleDownAnim = value)); - _loader?.add(AssetToLoad(idleUp, (value) => _idleUpAnim = value)); - _loader?.add(AssetToLoad(idleUpLeft, (value) => _idleUpLeftAnim = value)); - _loader?.add(AssetToLoad(idleUpRight, (value) => _idleUpRightAnim = value)); _loader?.add( - AssetToLoad(idleDownLeft, (value) => _idleDownLeftAnim = value), + AssetToLoad( + idleLeft, + (value) => _idleLeftAnim = value, + ), ); _loader?.add( - AssetToLoad(idleDownRight, (value) => _idleDownRightAnim = value), + AssetToLoad( + idleRight, + (value) => _idleRightAnim = value, + ), ); - _loader?.add(AssetToLoad(runUp, (value) => _runUpAnim = value)); - _loader?.add(AssetToLoad(runRight, (value) => _runRightAnim = value)); - _loader?.add(AssetToLoad(runDown, (value) => _runDownAnim = value)); - _loader?.add(AssetToLoad(runLeft, (value) => _runLeftAnim = value)); - _loader?.add(AssetToLoad(runUpLeft, (value) => _runUpLeftAnim = value)); - _loader?.add(AssetToLoad(runUpRight, (value) => _runUpRightAnim = value)); - _loader?.add(AssetToLoad(runDownLeft, (value) => _runDownLeftAnim = value)); _loader?.add( - AssetToLoad(runDownRight, (value) => _runDownRightAnim = value), + AssetToLoad( + idleDown, + (value) => _idleDownAnim = value, + ), + ); + _loader?.add( + AssetToLoad(idleUp, (value) => _idleUpAnim = value), + ); + _loader?.add( + AssetToLoad( + idleUpLeft, + (value) => _idleUpLeftAnim = value, + ), + ); + _loader?.add( + AssetToLoad( + idleUpRight, + (value) => _idleUpRightAnim = value, + ), + ); + _loader?.add( + AssetToLoad( + idleDownLeft, + (value) => _idleDownLeftAnim = value, + ), + ); + _loader?.add( + AssetToLoad( + idleDownRight, + (value) => _idleDownRightAnim = value, + ), + ); + _loader?.add( + AssetToLoad(runUp, (value) => _runUpAnim = value), + ); + _loader?.add( + AssetToLoad( + runRight, + (value) => _runRightAnim = value, + ), + ); + _loader?.add( + AssetToLoad(runDown, (value) => _runDownAnim = value), + ); + _loader?.add( + AssetToLoad(runLeft, (value) => _runLeftAnim = value), + ); + _loader?.add( + AssetToLoad( + runUpLeft, + (value) => _runUpLeftAnim = value, + ), + ); + _loader?.add( + AssetToLoad( + runUpRight, + (value) => _runUpRightAnim = value, + ), + ); + _loader?.add( + AssetToLoad( + runDownLeft, + (value) => _runDownLeftAnim = value, + ), + ); + _loader?.add( + AssetToLoad( + runDownRight, + (value) => _runDownRightAnim = value, + ), ); others?.forEach((key, anim) { - _loader?.add(AssetToLoad(anim, (value) { - return this.others[key] = value; - })); + _loader?.add( + AssetToLoad(anim, (value) { + return this.others[key] = value!; + }), + ); }); _renderWrapper = RenderTransformWrapper( @@ -159,7 +223,7 @@ class SimpleDirectionAnimation { ), CenterAdjustRenderTransform( _adjustRenderTransform, - ) + ), ], render: _myRender, ); @@ -170,7 +234,7 @@ class SimpleDirectionAnimation { ), CenterAdjustRenderTransform( _adjustRenderTransform, - ) + ), ], render: _myFastAnimationRender, ); @@ -179,7 +243,7 @@ class SimpleDirectionAnimation { CenterAdjustRenderData? _adjustRenderTransform() { if (centerAnchor != null) { return CenterAdjustRenderData( - center: (size / 2), + center: size / 2, newCenter: centerAnchor!, ); } @@ -189,7 +253,7 @@ class SimpleDirectionAnimation { FlipRenderTransformData? _flipRenderTransform() { if (_needDoFlip) { return FlipRenderTransformData( - center: (size / 2), + center: size / 2, horizontal: isFlipHorizontally, vertical: isFlipVertically, ); @@ -200,7 +264,7 @@ class SimpleDirectionAnimation { FlipRenderTransformData? _flipFastAnimationRenderTransform() { if (_fastAnimation != null && _needDoFlipFastAnimation) { return FlipRenderTransformData( - center: (size / 2), + center: size / 2, horizontal: isFlipHorizontallyFastAnimation, vertical: isFlipVerticallyFastAnimation, ); @@ -210,7 +274,9 @@ class SimpleDirectionAnimation { /// Method used to play specific default animation void play(SimpleAnimationEnum animation) { - if (_currentType == animation) return; + if (_currentType == animation) { + return; + } isFlipHorizontally = false; isFlipVertically = false; @@ -228,7 +294,9 @@ class SimpleDirectionAnimation { _current.animation = _idleRightAnim; break; case SimpleAnimationEnum.idleUp: - if (_idleUpAnim != null) _current.animation = _idleUpAnim; + if (_idleUpAnim != null) { + _current.animation = _idleUpAnim; + } break; case SimpleAnimationEnum.idleDown: if (_idleDownAnim != null) { @@ -385,8 +453,8 @@ class SimpleDirectionAnimation { if (!runToTheEndFastAnimation) { _fastAnimation = null; } - isFlipHorizontally = flipX ?? (isFlipHorizontally); - isFlipVertically = flipY ?? (isFlipVertically); + isFlipHorizontally = flipX ?? isFlipHorizontally; + isFlipVertically = flipY ?? isFlipVertically; _current.animation = others[key]; _currentKeyCustom = key; _currentType = SimpleAnimationEnum.custom; @@ -653,7 +721,7 @@ class SimpleDirectionAnimation { if (_strockePaint != null) { _fastAnimation?.render( canvas, - overridePaint: _strockePaint!, + overridePaint: _strockePaint, size: _strokeSize, position: _strokePosition + (spriteAnimationOffset ?? Vector2.zero()), ); diff --git a/lib/util/extensions/ally/ally_extensions.dart b/lib/util/extensions/ally/ally_extensions.dart index 050be188a..8a6614673 100644 --- a/lib/util/extensions/ally/ally_extensions.dart +++ b/lib/util/extensions/ally/ally_extensions.dart @@ -27,11 +27,11 @@ extension AllyExtensions on Ally { VoidCallback? execute, Vector2? centerOffset, }) { - if (!checkInterval('attackMelee', interval, dtUpdate)) return; + if (!checkInterval('attackMelee', interval, dtUpdate) || isDead) { + return; + } - if (isDead) return; - - Direction direct = direction ?? lastDirection; + final direct = direction ?? lastDirection; simpleAttackMeleeByDirection( damage: damage, @@ -65,11 +65,11 @@ extension AllyExtensions on Ally { VoidCallback? execute, LightingConfig? lightingConfig, }) { - if (!checkInterval('attackRange', interval, dtUpdate)) return; - - if (isDead) return; + if (!checkInterval('attackRange', interval, dtUpdate) || isDead) { + return; + } - Direction direct = direction ?? lastDirection; + final direct = direction ?? lastDirection; simpleAttackRangeByDirection( animationRight: animationRight, @@ -87,7 +87,7 @@ extension AllyExtensions on Ally { attackFrom: AttackOriginEnum.PLAYER_OR_ALLY, ); - if (execute != null) execute(); + execute?.call(); } /// Checks whether the Enemy is within range. If so, move to it. @@ -104,18 +104,20 @@ extension AllyExtensions on Ally { double? minDistanceFromPlayer, bool runOnlyVisibleInScreen = true, }) { - if (isDead) return; + if (isDead) { + return; + } seeComponentType( radiusVision: radiusVision, angle: angle ?? lastDirection.toRadians(), visionAngle: visionAngle, observed: (enemy) { - var e = enemy.first; + final e = enemy.first; observed?.call(e); - bool inDistance = keepDistance( + final inDistance = keepDistance( e, - (minDistanceFromPlayer ?? (radiusVision - 5)), + minDistanceFromPlayer ?? (radiusVision - 5), ); if (inDistance) { final playerDirection = getComponentDirectionFromMe(e); @@ -132,7 +134,7 @@ extension AllyExtensions on Ally { } }, notObserved: () { - bool stop = notObserved?.call() ?? true; + final stop = notObserved?.call() ?? true; if (stop) { stopMove(); } diff --git a/lib/util/extensions/ally/rotation_ally_extensions.dart b/lib/util/extensions/ally/rotation_ally_extensions.dart index 051bb58b9..19a0f2e3a 100644 --- a/lib/util/extensions/ally/rotation_ally_extensions.dart +++ b/lib/util/extensions/ally/rotation_ally_extensions.dart @@ -1,9 +1,8 @@ import 'dart:ui'; import 'package:bonfire/npc/ally/ally.dart'; - -import '../../../player/player.dart'; -import '../extensions.dart'; +import 'package:bonfire/player/player.dart'; +import 'package:bonfire/util/extensions/extensions.dart'; /// /// Created by @@ -26,16 +25,17 @@ extension RotationEnemyExtensions on RotationAlly { double margin = 10, bool runOnlyVisibleInScreen = true, }) { - if (isDead) return; - if (runOnlyVisibleInScreen && !isVisible) return; + if ((runOnlyVisibleInScreen && !isVisible) || isDead) { + return; + } seePlayer( radiusVision: radiusVision, observed: (player) { - double radAngle = getAngleFromPlayer(); + final radAngle = getAngleFromPlayer(); - Rect playerRect = player.rectCollision; - Rect rectPlayerCollision = Rect.fromLTWH( + final playerRect = player.rectCollision; + final rectPlayerCollision = Rect.fromLTWH( playerRect.left - margin, playerRect.top - margin, playerRect.width + (margin * 2), @@ -51,7 +51,7 @@ extension RotationEnemyExtensions on RotationAlly { moveFromAngle(radAngle); }, notObserved: () { - bool stop = notObserved?.call() ?? true; + final stop = notObserved?.call() ?? true; if (stop) { stopMove(); } diff --git a/lib/util/extensions/color_extensions.dart b/lib/util/extensions/color_extensions.dart new file mode 100644 index 000000000..6b0114226 --- /dev/null +++ b/lib/util/extensions/color_extensions.dart @@ -0,0 +1,8 @@ +import 'dart:ui'; + +extension ColorExtensions on Color { + Color setOpacity(double opacity) { + assert(opacity >= 0.0 && opacity <= 1.0); + return withValues(alpha: (255.0 * opacity).roundToDouble()); + } +} diff --git a/lib/util/extensions/enemy/enemy_extensions.dart b/lib/util/extensions/enemy/enemy_extensions.dart index 5a25559f9..09b5c4a83 100644 --- a/lib/util/extensions/enemy/enemy_extensions.dart +++ b/lib/util/extensions/enemy/enemy_extensions.dart @@ -16,11 +16,11 @@ extension EnemyExtensions on Enemy { VoidCallback? execute, Vector2? centerOffset, }) { - if (!checkInterval('attackMelee', interval, dtUpdate)) return; - - if (isDead) return; + if (!checkInterval('attackMelee', interval, dtUpdate) || isDead) { + return; + } - Direction direct = direction ?? + final direct = direction ?? (gameRef.player != null ? getComponentDirectionFromMe(gameRef.player!) : lastDirection); @@ -57,11 +57,11 @@ extension EnemyExtensions on Enemy { VoidCallback? execute, LightingConfig? lightingConfig, }) { - if (!checkInterval('attackRange', interval, dtUpdate)) return; - - if (isDead) return; + if (!checkInterval('attackRange', interval, dtUpdate) || isDead) { + return; + } - Direction direct = direction ?? + final direct = direction ?? (gameRef.player != null ? getComponentDirectionFromMe(gameRef.player!) : lastDirection); @@ -103,7 +103,9 @@ extension EnemyExtensions on Enemy { assert(minDistanceFromPlayer < radiusVision); } - if (isDead) return; + if (isDead) { + return; + } seePlayer( radiusVision: radiusVision, @@ -111,9 +113,9 @@ extension EnemyExtensions on Enemy { angle: angle, observed: (player) { observed?.call(player); - double minD = (minDistanceFromPlayer ?? (radiusVision - 5)); + final minD = minDistanceFromPlayer ?? (radiusVision - 5); if (useDiagonal) { - bool inDistance = keepDistance( + final inDistance = keepDistance( player, minD, ); @@ -152,7 +154,7 @@ extension EnemyExtensions on Enemy { } }, notObserved: () { - bool stop = notObserved?.call() ?? true; + final stop = notObserved?.call() ?? true; if (stop) { stopMove(forceIdle: true); } diff --git a/lib/util/extensions/enemy/rotation_enemy_extensions.dart b/lib/util/extensions/enemy/rotation_enemy_extensions.dart index 554ced009..ecfd3e884 100644 --- a/lib/util/extensions/enemy/rotation_enemy_extensions.dart +++ b/lib/util/extensions/enemy/rotation_enemy_extensions.dart @@ -17,16 +17,17 @@ extension RotationEnemyExtensions on RotationEnemy { double margin = 10, bool runOnlyVisibleInScreen = true, }) { - if (isDead) return; - if (runOnlyVisibleInScreen && !isVisible) return; + if ((runOnlyVisibleInScreen && !isVisible) || isDead) { + return; + } seePlayer( radiusVision: radiusVision, observed: (player) { - double radAngle = getAngleFromPlayer(); + final radAngle = getAngleFromPlayer(); - Rect playerRect = player.rectCollision; - Rect rectPlayerCollision = playerRect.inflate(margin); + final playerRect = player.rectCollision; + final rectPlayerCollision = playerRect.inflate(margin); if (rectCollision.overlaps(rectPlayerCollision)) { closePlayer(player); @@ -38,7 +39,7 @@ extension RotationEnemyExtensions on RotationEnemy { moveFromAngle(radAngle); }, notObserved: () { - bool stop = notObserved?.call() ?? true; + final stop = notObserved?.call() ?? true; if (stop) { stopMove(); } @@ -55,28 +56,29 @@ extension RotationEnemyExtensions on RotationEnemy { double? minDistanceCellsFromPlayer, bool runOnlyVisibleInScreen = true, }) { - if (isDead) return; - if (runOnlyVisibleInScreen && !isVisible) return; + if ((runOnlyVisibleInScreen && !isVisible) || isDead) { + return; + } seePlayer( radiusVision: radiusVision, observed: (player) { positioned(player); - Rect playerRect = player.rectCollision; - double distance = (minDistanceCellsFromPlayer ?? radiusVision); + final playerRect = player.rectCollision; + final distance = minDistanceCellsFromPlayer ?? radiusVision; - Vector2 myPosition = Vector2( + final myPosition = Vector2( center.x, center.y, ); - Vector2 playerPosition = Vector2( + final playerPosition = Vector2( playerRect.center.dx, playerRect.center.dy, ); - double dist = myPosition.distanceTo(playerPosition); + final dist = myPosition.distanceTo(playerPosition); if (dist >= distance) { stopMove(); @@ -88,7 +90,7 @@ extension RotationEnemyExtensions on RotationEnemy { ); }, notObserved: () { - bool stop = notObserved?.call() ?? true; + final stop = notObserved?.call() ?? true; if (stop) { stopMove(); } @@ -109,9 +111,9 @@ extension RotationEnemyExtensions on RotationEnemy { double marginFromCenter = 16, Vector2? centerOffset, }) { - if (!checkInterval('attackMelee', interval, dtUpdate)) return; - - if (isDead) return; + if (!checkInterval('attackMelee', interval, dtUpdate) || isDead) { + return; + } simpleAttackMeleeByAngle( id: id, @@ -148,9 +150,9 @@ extension RotationEnemyExtensions on RotationEnemy { Vector2? centerOffset, double marginFromOrigin = 16, }) { - if (!checkInterval('attackRange', interval, dtUpdate)) return; - - if (isDead) return; + if (!checkInterval('attackRange', interval, dtUpdate) || isDead) { + return; + } simpleAttackRangeByAngle( animation: animation, diff --git a/lib/util/extensions/extensions.dart b/lib/util/extensions/extensions.dart index 8e9c1a932..c994580ab 100644 --- a/lib/util/extensions/extensions.dart +++ b/lib/util/extensions/extensions.dart @@ -47,10 +47,10 @@ extension RectExt on Rect { } bool overlapComponent(PositionComponent c) { - double left = c.position.x; - double top = c.position.y; - double right = c.position.x + c.size.x; - double bottom = c.position.y + c.size.y; + final left = c.position.x; + final top = c.position.y; + final right = c.position.x + c.size.x; + final bottom = c.position.y + c.size.y; if (this.right <= left || right <= this.left) { return false; } @@ -63,7 +63,11 @@ extension RectExt on Rect { /// Returns a new rectangle with edges moved outwards by the given delta. Rect inflatexy(double deltaX, double deltaY) { return Rect.fromLTRB( - left - deltaX, top - deltaY, right + deltaX, bottom + deltaY); + left - deltaX, + top - deltaY, + right + deltaX, + bottom + deltaY, + ); } /// Returns a new rectangle with edges moved inwards by the given delta. @@ -74,7 +78,7 @@ extension RectExt on Rect { extension SpriteFutureExt on Future { Future toAnimation({double stepTime = 1}) async { - var sprite = await this; + final sprite = await this; return SpriteAnimation.spriteList([sprite], stepTime: stepTime); } } @@ -146,7 +150,9 @@ extension FutureSpriteAnimationExt on FutureOr { key: key, future: this as Future, builder: (context, data) { - if (!data.hasData) return const widget.SizedBox.shrink(); + if (!data.hasData) { + return const widget.SizedBox.shrink(); + } return widget.Container( constraints: widget.BoxConstraints( minWidth: data.data!.frames.first.sprite.src.width, @@ -190,7 +196,9 @@ extension FutureSpriteExt on FutureOr { key: key, future: this as Future, builder: (context, data) { - if (!data.hasData) return const widget.SizedBox.shrink(); + if (!data.hasData) { + return const widget.SizedBox.shrink(); + } return widget.Container( constraints: widget.BoxConstraints( minWidth: data.data!.src.width, @@ -224,8 +232,8 @@ extension FutureSpriteExt on FutureOr { extension ComponentExt on GameComponent { bool get isHud { if (hasGameRef) { - bool thisIs = gameRef.camera.viewport.contains(this); - bool parentIs = false; + final thisIs = gameRef.camera.viewport.contains(this); + var parentIs = false; if (parent != null) { parentIs = gameRef.camera.viewport.contains(parent!); } @@ -271,13 +279,13 @@ extension PositionComponentExt on PositionComponent { double offsetY = 0, bool calculatePosition = false, }) { - double bleedingPixel = max(size.x, size.y) * factor; + var bleedingPixel = max(size.x, size.y) * factor; bleedingPixel = bleedingPixel > 2 ? 2 : bleedingPixel; bleedingPixel = bleedingPixel < 0.6 ? 0.6 : bleedingPixel; - bool xIsEven = position.x % 2 == 0; - bool yIsEven = position.y % 2 == 0; - Vector2 baseP = position; + final xIsEven = position.x % 2 == 0; + final yIsEven = position.y % 2 == 0; + var baseP = position; if (calculatePosition) { baseP = Vector2(position.x * size.x, position.y * size.y); } @@ -295,7 +303,7 @@ extension PositionComponentExt on PositionComponent { extension ShapeHitbocExt on ShapeHitbox { ShapeHitbox clone() { if (e is RectangleHitbox) { - RectangleHitbox rect = e as RectangleHitbox; + final rect = e as RectangleHitbox; return RectangleHitbox( anchor: rect.anchor, angle: rect.angle, @@ -307,7 +315,7 @@ extension ShapeHitbocExt on ShapeHitbox { } if (e is CircleHitbox) { - CircleHitbox circle = e as CircleHitbox; + final circle = e as CircleHitbox; return CircleHitbox( anchor: circle.anchor, angle: circle.angle, @@ -318,7 +326,7 @@ extension ShapeHitbocExt on ShapeHitbox { } if (e is PolygonHitbox) { - PolygonHitbox poly = e as PolygonHitbox; + final poly = e as PolygonHitbox; return PolygonHitbox( poly.vertices, anchor: poly.anchor, diff --git a/lib/util/extensions/game_component_extensions.dart b/lib/util/extensions/game_component_extensions.dart index 4c0a9cc61..2ccd648a2 100644 --- a/lib/util/extensions/game_component_extensions.dart +++ b/lib/util/extensions/game_component_extensions.dart @@ -15,7 +15,9 @@ extension GameComponentExtensions on GameComponent { DirectionTextDamage direction = DirectionTextDamage.RANDOM, bool onlyUp = false, }) { - if (!hasGameRef) return; + if (!hasGameRef) { + return; + } gameRef.add( TextDamageComponent( damage.toInt().toString(), @@ -56,12 +58,12 @@ extension GameComponentExtensions on GameComponent { double marginFromOrigin = 16, Vector2? centerOffset, }) { - var initPosition = rectCollision; + final initPosition = rectCollision; - Vector2 startPosition = + var startPosition = initPosition.center.toVector2() + (centerOffset ?? Vector2.zero()); - double displacement = + final displacement = max(initPosition.width, initPosition.height) / 2 + marginFromOrigin; startPosition = BonfireUtil.movePointByAngle( @@ -129,12 +131,12 @@ extension GameComponentExtensions on GameComponent { ///Execute simple attack melee using animation void simpleAttackMeleeByDirection({ - Future? animationRight, - dynamic id, required double damage, required Direction direction, required Vector2 size, required AttackOriginEnum attackFrom, + Future? animationRight, + dynamic id, bool withPush = true, double? sizePush, double? marginFromCenter, @@ -158,34 +160,34 @@ extension GameComponentExtensions on GameComponent { ///Execute simple attack melee using animation void simpleAttackMeleeByAngle({ - dynamic id, - - /// use animation facing right. - Future? animation, required double damage, /// Use radians angle required double angle, required AttackOriginEnum attackFrom, required Vector2 size, + dynamic id, + + /// use animation facing right. + Future? animation, bool withPush = true, double marginFromCenter = 0, Vector2? centerOffset, void Function(Attackable attackable)? onDamage, }) { - var initPosition = rectCollision; + final initPosition = rectCollision; - Vector2 startPosition = + final startPosition = initPosition.center.toVector2() + (centerOffset ?? Vector2.zero()); - double displacement = max( + final displacement = max( initPosition.width, initPosition.height, ) / 2 + marginFromCenter; - Vector2 diffBase = BonfireUtil.diffMovePointByAngle( + final diffBase = BonfireUtil.diffMovePointByAngle( startPosition, displacement, angle, @@ -241,18 +243,24 @@ extension GameComponentExtensions on GameComponent { double get right => absolutePositionOfAnchor(Anchor.bottomRight).x; bool overlaps(Rect other) { - if (right <= other.left || other.right <= left) return false; - if (bottom <= other.top || other.bottom <= top) return false; + if (right <= other.left || other.right <= left) { + return false; + } + if (bottom <= other.top || other.bottom <= top) { + return false; + } return true; } Direction? directionThePlayerIsIn() { - Player? player = gameRef.player; - if (player == null) return null; + final player = gameRef.player; + if (player == null) { + return null; + } var diffX = center.x - player.center.x; - var diffPositiveX = diffX < 0 ? diffX *= -1 : diffX; + final diffPositiveX = diffX < 0 ? diffX *= -1 : diffX; var diffY = center.y - player.center.y; - var diffPositiveY = diffY < 0 ? diffY *= -1 : diffY; + final diffPositiveY = diffY < 0 ? diffY *= -1 : diffY; if (diffPositiveX > diffPositiveY) { if (player.center.x > center.x) { @@ -417,12 +425,16 @@ extension GameComponentExtensions on GameComponent { } Offset globalToViewportPosition(Offset position) { - if (!hasGameRef) return position; + if (!hasGameRef) { + return position; + } return gameRef.globalToViewportPosition(position.toVector2()).toOffset(); } Offset viewportPositionToGlobal(Offset position) { - if (!hasGameRef) return position; + if (!hasGameRef) { + return position; + } return gameRef.viewportPositionToGlobal(position.toVector2()).toOffset(); } } diff --git a/lib/util/extensions/image_extensions.dart b/lib/util/extensions/image_extensions.dart index 729d9e09d..a822eb9b4 100644 --- a/lib/util/extensions/image_extensions.dart +++ b/lib/util/extensions/image_extensions.dart @@ -37,9 +37,9 @@ extension BonfireImageExtension on Image { /// Do merge image. Overlaying the images /// @deprecated Use [ImageComposition] Future overlap(Image other) { - PictureRecorder recorder = PictureRecorder(); + final recorder = PictureRecorder(); final paint = Paint(); - Canvas canvas = Canvas(recorder); + final canvas = Canvas(recorder); final totalWidth = max(width, other.width); final totalHeight = max(height, other.height); canvas.drawImage(this, Offset.zero, paint); @@ -49,13 +49,13 @@ extension BonfireImageExtension on Image { /// Do merge image list. Overlaying the images Future overlapList(List others) { - PictureRecorder recorder = PictureRecorder(); + final recorder = PictureRecorder(); final paint = Paint(); - Canvas canvas = Canvas(recorder); - int totalWidth = width; - int totalHeight = height; + final canvas = Canvas(recorder); + var totalWidth = width; + var totalHeight = height; canvas.drawImage(this, Offset.zero, paint); - for (var i in others) { + for (final i in others) { totalWidth = max(totalWidth, i.width); totalHeight = max(totalHeight, i.height); canvas.drawImage(i, Offset.zero, paint); @@ -65,15 +65,15 @@ extension BonfireImageExtension on Image { // flip the frames horizontally Future flipAnimation({required Vector2 size, required int count}) { - PictureRecorder recorder = PictureRecorder(); + final recorder = PictureRecorder(); final paint = Paint(); - Canvas canvas = Canvas(recorder); + final canvas = Canvas(recorder); canvas.translate(width / 2, height / 2); canvas.scale(-1, 1); canvas.translate(-width / 2, -height / 2); - int indexAux = 0; - for (int i = count - 1; i >= 0; i--) { + var indexAux = 0; + for (var i = count - 1; i >= 0; i--) { final dstPosition = Vector2(size.x * i, 0); final srcPosition = Vector2(size.x * indexAux, 0); canvas.drawImageRect( diff --git a/lib/util/extensions/int_int_extensions.dart b/lib/util/extensions/int_int_extensions.dart new file mode 100644 index 000000000..408401ba2 --- /dev/null +++ b/lib/util/extensions/int_int_extensions.dart @@ -0,0 +1,17 @@ +extension IntIntExtensions on (int, int) { + int get x => $1; + int get y => $2; + + bool isNeighbour((int, int) other, {bool withDiagonal = true}) { + if (this == other) { + return false; + } + + if (withDiagonal) { + return (x - other.x).abs() <= 1 && (y - other.y).abs() <= 1; + } + + return (x - other.x).abs() <= 1 && y == other.y || + x == other.x && (y - other.y).abs() <= 1; + } +} diff --git a/lib/util/extensions/movement_extensions.dart b/lib/util/extensions/movement_extensions.dart index 37f72ed48..ff52fce91 100644 --- a/lib/util/extensions/movement_extensions.dart +++ b/lib/util/extensions/movement_extensions.dart @@ -11,11 +11,11 @@ extension MovementExtensions on Movement { /// return true if moved. bool moveTowardsTarget({ required T target, - Function? close, + void Function()? close, double margin = 4, MovementAxis movementAxis = MovementAxis.all, }) { - Rect rectPlayerCollision = target.rectCollision.inflate(margin); + final rectPlayerCollision = target.rectCollision.inflate(margin); if (rectCollision.overlaps(rectPlayerCollision)) { close?.call(); @@ -23,8 +23,8 @@ extension MovementExtensions on Movement { return false; } - double radAngle = getAngleFromTarget(target); - Direction directionToMove = BonfireUtil.getDirectionFromAngle( + final radAngle = getAngleFromTarget(target); + var directionToMove = BonfireUtil.getDirectionFromAngle( radAngle, ); final newDirectionToMove = _checkRestrictAxis( @@ -94,13 +94,15 @@ extension MovementExtensions on Movement { } bool keepDistance(GameComponent target, double minDistance) { - if (!isVisible) return true; - double distance = rectCollision.centerVector2.distanceTo( + if (!isVisible) { + return true; + } + final distance = rectCollision.centerVector2.distanceTo( target.rectCollision.centerVector2, ); if (distance < minDistance) { - var angle = getAngleFromTarget(target); + final angle = getAngleFromTarget(target); moveFromAngle(angle + pi); return false; } @@ -116,19 +118,21 @@ extension MovementExtensions on Movement { double? minDistanceFromPlayer, bool runOnlyVisibleInScreen = true, }) { - if (runOnlyVisibleInScreen && !isVisible) return false; - double distance = (minDistanceFromPlayer ?? radiusVision); + if (runOnlyVisibleInScreen && !isVisible) { + return false; + } + final distance = minDistanceFromPlayer ?? radiusVision; - Rect rectTarget = target.rectCollision; - double centerXTarget = rectTarget.center.dx; - double centerYTarget = rectTarget.center.dy; + final rectTarget = target.rectCollision; + final centerXTarget = rectTarget.center.dx; + final centerYTarget = rectTarget.center.dy; double translateX = 0; double translateY = 0; - double speed = this.speed * dtUpdate; + final speed = this.speed * dtUpdate; - Rect rectToMove = rectCollision; + final rectToMove = rectCollision; translateX = rectToMove.center.dx > centerXTarget ? (-1 * speed) : speed; translateX = _adjustTranslate( @@ -144,10 +148,10 @@ extension MovementExtensions on Movement { centerYTarget, ); - double translateXPositive = + final translateXPositive = (rectToMove.center.dx - rectTarget.center.dx).abs(); - double translateYPositive = + final translateYPositive = (rectToMove.center.dy - rectTarget.center.dy).abs(); if (translateXPositive >= distance && @@ -179,7 +183,7 @@ extension MovementExtensions on Movement { double centerEnemy, double centerPlayer, ) { - double diff = centerPlayer - centerEnemy; + final diff = centerPlayer - centerEnemy; double newTrasnlate = 0; if (translate.abs() > diff.abs()) { newTrasnlate = diff; diff --git a/lib/util/extensions/npc/npc_extensions.dart b/lib/util/extensions/npc/npc_extensions.dart index f36a54e76..a1ffa9894 100644 --- a/lib/util/extensions/npc/npc_extensions.dart +++ b/lib/util/extensions/npc/npc_extensions.dart @@ -27,7 +27,7 @@ extension NpcExtensions on Npc { double? visionAngle, double? angle, }) { - Player? player = gameRef.player; + final player = gameRef.player; if (player == null || player.isDead) { notObserved?.call(); return null; @@ -58,7 +58,9 @@ extension NpcExtensions on Npc { bool runOnlyVisibleInScreen = true, MovementAxis movementAxis = MovementAxis.all, }) { - if (runOnlyVisibleInScreen && !isVisible) return null; + if (runOnlyVisibleInScreen && !isVisible) { + return null; + } return seePlayer( radiusVision: radiusVision, @@ -66,7 +68,7 @@ extension NpcExtensions on Npc { angle: angle, observed: (player) { observed?.call(); - bool move = moveTowardsTarget( + final move = moveTowardsTarget( target: player, close: () => closePlayer?.call(player), margin: margin, @@ -77,7 +79,7 @@ extension NpcExtensions on Npc { } }, notObserved: () { - bool stop = notObserved?.call() ?? true; + final stop = notObserved?.call() ?? true; if (stop) { stopMove(); } @@ -101,7 +103,9 @@ extension NpcExtensions on Npc { bool runOnlyVisibleInScreen = true, MovementAxis movementAxis = MovementAxis.all, }) { - if (runOnlyVisibleInScreen && !isVisible) return; + if (runOnlyVisibleInScreen && !isVisible) { + return; + } seeComponentType( radiusVision: radiusVision, @@ -109,7 +113,7 @@ extension NpcExtensions on Npc { angle: angle ?? lastDirection.toRadians(), observed: (enemy) { observed?.call(); - bool move = moveTowardsTarget( + final move = moveTowardsTarget( target: enemy.first, close: () { closeEnemy(enemy.first); @@ -122,7 +126,7 @@ extension NpcExtensions on Npc { } }, notObserved: () { - bool stop = notObserved?.call() ?? true; + final stop = notObserved?.call() ?? true; if (stop) { stopMove(); } @@ -146,7 +150,9 @@ extension NpcExtensions on Npc { bool runOnlyVisibleInScreen = true, MovementAxis movementAxis = MovementAxis.all, }) { - if (runOnlyVisibleInScreen && !isVisible) return; + if (runOnlyVisibleInScreen && !isVisible) { + return; + } seeComponentType( radiusVision: radiusVision, @@ -154,7 +160,7 @@ extension NpcExtensions on Npc { angle: angle ?? lastDirection.toRadians(), observed: (ally) { observed?.call(); - bool move = moveTowardsTarget( + final move = moveTowardsTarget( target: ally.first, close: () { closeAlly(ally.first); @@ -167,7 +173,7 @@ extension NpcExtensions on Npc { } }, notObserved: () { - bool stop = notObserved?.call() ?? true; + final stop = notObserved?.call() ?? true; if (stop) { stopMove(); } @@ -183,16 +189,20 @@ extension NpcExtensions on Npc { /// Get angle between enemy and player /// player as a base double getAngleFromPlayer() { - Player? player = gameRef.player; - if (player == null) return 0.0; + final player = gameRef.player; + if (player == null) { + return 0.0; + } return getAngleFromTarget(player); } /// Get angle between enemy and player /// enemy position as a base double getInverseAngleFromPlayer() { - Player? player = gameRef.player; - if (player == null) return 0.0; + final player = gameRef.player; + if (player == null) { + return 0.0; + } return BonfireUtil.angleBetweenPoints( playerRect.center.toVector2(), rectCollision.centerVector2, diff --git a/lib/util/extensions/player/player_extensions.dart b/lib/util/extensions/player/player_extensions.dart index e4858b79f..80b8a8e21 100644 --- a/lib/util/extensions/player/player_extensions.dart +++ b/lib/util/extensions/player/player_extensions.dart @@ -16,7 +16,9 @@ extension PlayerExtensions on Player { double? visionAngle, double? angle, }) { - if (isDead) return null; + if (isDead) { + return null; + } return seeComponentType( observed: observed, notObserved: notObserved, @@ -27,9 +29,9 @@ extension PlayerExtensions on Player { } void simpleAttackMelee({ - Future? animationRight, required double damage, required Vector2 size, + Future? animationRight, dynamic id, Direction? direction, bool withPush = true, @@ -54,8 +56,8 @@ extension PlayerExtensions on Player { void simpleAttackRange({ required Future animationRight, - Future? animationDestroy, required Vector2 size, + Future? animationDestroy, Vector2? destroySize, dynamic id, double speed = 150, @@ -67,7 +69,7 @@ extension PlayerExtensions on Player { ShapeHitbox? collision, LightingConfig? lightingConfig, }) { - Direction attackDirection = direction ?? _getLastDirection(diagonalEnabled); + final attackDirection = direction ?? _getLastDirection(diagonalEnabled); simpleAttackRangeByDirection( direction: attackDirection, animationRight: animationRight, diff --git a/lib/util/extensions/player/rotation_player_extensions.dart b/lib/util/extensions/player/rotation_player_extensions.dart index 978ad154d..ea811f06c 100644 --- a/lib/util/extensions/player/rotation_player_extensions.dart +++ b/lib/util/extensions/player/rotation_player_extensions.dart @@ -24,7 +24,7 @@ extension RotationPlayerExtensions on RotationPlayer { Vector2? centerOffset, double marginFromOrigin = 16, }) { - double? angle = radAngleDirection ?? this.angle; + final angle = radAngleDirection ?? this.angle; simpleAttackRangeByAngle( angle: angle, @@ -56,7 +56,7 @@ extension RotationPlayerExtensions on RotationPlayer { double marginFromCenter = 16, Vector2? centerOffset, }) { - double? angle = radAngleDirection ?? this.angle; + final angle = radAngleDirection ?? this.angle; simpleAttackMeleeByAngle( angle: angle, animation: animation, diff --git a/lib/util/extensions/position_component_ext.dart b/lib/util/extensions/position_component_ext.dart index 300d65469..22ca0da28 100644 --- a/lib/util/extensions/position_component_ext.dart +++ b/lib/util/extensions/position_component_ext.dart @@ -1,8 +1,8 @@ import 'package:bonfire/bonfire.dart'; extension PositionComponentExt on PositionComponent { - double get left => (position.x * size.x); + double get left => position.x * size.x; double get right => (position.x * size.x) + size.x; - double get top => (position.y * size.y); + double get top => position.y * size.y; double get bottom => (position.y * size.y) + size.y; } diff --git a/lib/util/follower_widget.dart b/lib/util/follower_widget.dart index da5e37ac8..ffded9ba6 100644 --- a/lib/util/follower_widget.dart +++ b/lib/util/follower_widget.dart @@ -26,12 +26,12 @@ class FollowerWidget extends StatefulWidget { final Offset offset; final AlignmentGeometry? alignment; const FollowerWidget({ - Key? key, required this.target, required this.child, + super.key, this.offset = Offset.zero, this.alignment, - }) : super(key: key); + }); /// Use this method to show a widget what follow the component static void show({ @@ -60,7 +60,7 @@ class FollowerWidget extends StatefulWidget { } /// Use this method to remove a widget what follow the component - static remove(String identify) { + static void remove(String identify) { if (_mapOverlayEntry.containsKey(identify)) { _mapOverlayEntry[identify]?.remove(); _mapOverlayEntry.remove(identify); @@ -68,7 +68,7 @@ class FollowerWidget extends StatefulWidget { } /// Use this method to remove all widgets what follow the component. - static removeAll() { + static void removeAll() { _mapOverlayEntry.forEach((key, value) { value.remove(); }); @@ -115,8 +115,8 @@ class FollowerWidgetState extends State { Widget build(BuildContext context) { if (widgetPosition != null) { return Positioned( - top: (widgetPosition!.y + widget.offset.dy), - left: (widgetPosition!.x + widget.offset.dx), + top: widgetPosition!.y + widget.offset.dy, + left: widgetPosition!.x + widget.offset.dx, child: Transform.scale( scale: lastZoom, alignment: widget.alignment, diff --git a/lib/util/functions.dart b/lib/util/functions.dart index 26e31ce9a..266437988 100644 --- a/lib/util/functions.dart +++ b/lib/util/functions.dart @@ -29,8 +29,10 @@ E? firstWhere( Iterable list, bool Function(E element) test, ) { - for (E element in list) { - if (test(element)) return element; + for (final element in list) { + if (test(element)) { + return element; + } } return null; } diff --git a/lib/util/quadtree.dart b/lib/util/quadtree.dart index 736fef301..bc8d79083 100644 --- a/lib/util/quadtree.dart +++ b/lib/util/quadtree.dart @@ -1,14 +1,3 @@ -/// -/// Created by -/// -/// ─▄▀─▄▀ -/// ──▀──▀ -/// █▀▀▀▀▀█▄ -/// █░░░░░█─█ -/// ▀▄▄▄▄▄▀▀ -/// -/// Rafaelbarbosatec -/// on 30/08/21 import 'dart:math'; // defaults should almost never be used, tune the quad tree to fit your problem @@ -50,16 +39,23 @@ class QuadTree extends Rectangle { maxItems: maxItems, ); - QuadTree._(num left, num top, num width, num height, int depth, - {int? maxDepth, int? maxItems}) - : maxDepth = maxDepth ?? default_max_depth, + QuadTree._( + super.left, + super.top, + super.width, + super.height, + int depth, { + int? maxDepth, + int? maxItems, + }) : maxDepth = maxDepth ?? default_max_depth, maxItems = maxItems ?? default_max_items, _depth = depth, - _center = Point(left + width / 2.0, top + height / 2.0), - super(left, top, width, height); + _center = Point(left + width / 2.0, top + height / 2.0); bool insert(T item, Point atPoint, {dynamic id}) { - if (!containsPoint(atPoint)) return false; + if (!containsPoint(atPoint)) { + return false; + } if (_children.isEmpty) { if (_items.length + 1 <= maxItems || _depth + 1 > maxDepth) { _items.add(_ItemAtPoint(id, item, atPoint)); @@ -74,14 +70,14 @@ class QuadTree extends Rectangle { if (_children.isEmpty) { _items.removeWhere((item) => item.id == id); } - for (var element in _children) { + for (final element in _children) { element.removeById(id); } } void clear() { _items.clear(); - for (var element in _children) { + for (final element in _children) { element.clear(); } _children.clear(); @@ -91,7 +87,7 @@ class QuadTree extends Rectangle { if (_children.isEmpty) { _items.removeWhere((i) => i.item == item); } - for (var element in _children) { + for (final element in _children) { element.remove(item); } } @@ -134,7 +130,7 @@ class QuadTree extends Rectangle { _newUpperLeft, // _upperLeftIndex = 0 _newUpperRight, // _upperRightIndex = 1 _newLowerLeft, // _lowerLeftIndex = 2 - _newLowerRight // _lowerRightIndex = 3 + _newLowerRight, // _lowerRightIndex = 3 ]); for (final item in _items) { _insertItemIntoChildren(item.item, item.point, id: item.id); diff --git a/lib/util/talk/talk_dialog.dart b/lib/util/talk/talk_dialog.dart index 8713777e8..328660fbd 100644 --- a/lib/util/talk/talk_dialog.dart +++ b/lib/util/talk/talk_dialog.dart @@ -1,13 +1,14 @@ import 'dart:async'; import 'package:bonfire/bonfire.dart'; +import 'package:bonfire/util/extensions/color_extensions.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class TalkDialog extends StatefulWidget { const TalkDialog({ - Key? key, required this.says, + super.key, this.onFinish, this.onChangeTalk, this.textBoxMinHeight = 100, @@ -18,9 +19,9 @@ class TalkDialog extends StatefulWidget { this.talkAlignment = Alignment.bottomCenter, this.style, this.speed = 50, - }) : super(key: key); + }); - static show( + static Future show( BuildContext context, List sayList, { VoidCallback? onFinish, @@ -31,14 +32,18 @@ class TalkDialog extends StatefulWidget { List logicalKeyboardKeysToNext = const [], EdgeInsetsGeometry? padding, bool dismissible = false, + bool useSafeArea = true, + bool useRootNavigator = true, Alignment talkAlignment = Alignment.bottomCenter, TextStyle? style, int speed = 50, }) { - showDialog( + return showDialog( barrierDismissible: dismissible, barrierColor: backgroundColor, context: context, + useSafeArea: useSafeArea, + useRootNavigator: useRootNavigator, builder: (BuildContext context) { return TalkDialog( says: sayList, @@ -86,9 +91,7 @@ class TalkDialogState extends State { @override void initState() { currentSay = widget.says[currentIndexTalk]; - Future.delayed(Duration.zero, () { - _focusNode.requestFocus(); - }); + Future.delayed(Duration.zero, _focusNode.requestFocus); super.initState(); } @@ -130,7 +133,6 @@ class TalkDialogState extends State { child: currentSay.background ?? const SizedBox.shrink(), ), Row( - mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.end, children: [ ..._buildPerson(PersonSayDirection.LEFT), @@ -152,10 +154,10 @@ class TalkDialogState extends State { : null, decoration: currentSay.boxDecoration ?? BoxDecoration( - color: Colors.black.withOpacity(0.5), + color: Colors.black.setOpacity(0.5), borderRadius: BorderRadius.circular(10.0), border: Border.all( - color: Colors.white.withOpacity(0.5), + color: Colors.white.setOpacity(0.5), ), ), child: TypeWriter( diff --git a/lib/util/text_damage_component.dart b/lib/util/text_damage_component.dart index efa6a38fb..51a13ce8b 100644 --- a/lib/util/text_damage_component.dart +++ b/lib/util/text_damage_component.dart @@ -2,13 +2,12 @@ import 'dart:math'; +import 'package:bonfire/util/bonfire_game_ref.dart'; import 'package:bonfire/util/priority_layer.dart'; import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flutter/cupertino.dart'; -import 'bonfire_game_ref.dart'; - enum DirectionTextDamage { LEFT, RIGHT, RANDOM, NONE } class TextDamageComponent extends TextComponent with BonfireHasGameRef { @@ -57,14 +56,18 @@ class TextDamageComponent extends TextComponent with BonfireHasGameRef { @override void render(Canvas canvas) { - if (isRemoving) return; + if (isRemoving) { + return; + } super.render(canvas); } @override void update(double dt) { super.update(dt); - if (isRemoving) return; + if (isRemoving) { + return; + } position.y += _velocity; position.x += _moveAxisX; _velocity += gravity; diff --git a/lib/util/value_generator_component.dart b/lib/util/value_generator_component.dart index 584a3b77e..33707fd2c 100644 --- a/lib/util/value_generator_component.dart +++ b/lib/util/value_generator_component.dart @@ -38,7 +38,9 @@ class ValueGeneratorComponent extends Component { @override void updateTree(double dt) { - if (!_isRunning) return; + if (!_isRunning) { + return; + } if (_reversing) { _currentValue -= dt * _maxInMilliSeconds; @@ -58,11 +60,11 @@ class ValueGeneratorComponent extends Component { } else { double realValue; if (_reversing) { - double value = (reverseCurve ?? curve) + final value = (reverseCurve ?? curve) .transform(1 - (_currentValue / duration.inMilliseconds)); realValue = begin + (_displacement * (1 - value)); } else { - double value = curve.transform(_currentValue / duration.inMilliseconds); + final value = curve.transform(_currentValue / duration.inMilliseconds); realValue = begin + (_displacement * value); } diff --git a/lib/widgets/bonfire_widget.dart b/lib/widgets/bonfire_widget.dart index cf8f6e22b..888c9d5d5 100644 --- a/lib/widgets/bonfire_widget.dart +++ b/lib/widgets/bonfire_widget.dart @@ -10,6 +10,7 @@ import 'package:bonfire/game_interface/game_interface.dart'; import 'package:bonfire/input/player_controller.dart'; import 'package:bonfire/map/base/game_map.dart'; import 'package:bonfire/player/player.dart'; +import 'package:bonfire/util/extensions/color_extensions.dart'; import 'package:flutter/material.dart'; class BonfireWidget extends StatefulWidget { @@ -63,8 +64,8 @@ class BonfireWidget extends StatefulWidget { final List? globalForces; const BonfireWidget({ - Key? key, required this.map, + super.key, this.playerControllers, this.player, this.interface, @@ -86,7 +87,7 @@ class BonfireWidget extends StatefulWidget { this.mouseCursor, this.onDispose, this.globalForces, - }) : super(key: key); + }); @override BonfireWidgetState createState() => BonfireWidgetState(); @@ -133,7 +134,7 @@ class BonfireWidgetState extends State { debugMode: widget.debugMode, showCollisionArea: widget.showCollisionArea, collisionAreaColor: - widget.collisionAreaColor ?? Colors.lightGreenAccent.withOpacity(0.5), + widget.collisionAreaColor ?? Colors.lightGreenAccent.setOpacity(0.5), lightingColorGame: widget.lightingColorGame, cameraConfig: widget.cameraConfig, colorFilter: widget.colorFilter, diff --git a/lib/widgets/map_navigator/map_navigator.dart b/lib/widgets/map_navigator/map_navigator.dart index 4a454da30..c456a7dc8 100644 --- a/lib/widgets/map_navigator/map_navigator.dart +++ b/lib/widgets/map_navigator/map_navigator.dart @@ -1,8 +1,7 @@ import 'package:bonfire/widgets/map_navigator/map_navigator_controller.dart'; +import 'package:bonfire/widgets/map_navigator/map_navigator_provider.dart'; import 'package:flutter/material.dart'; -import 'map_navigator_provider.dart'; - export 'package:bonfire/widgets/map_navigator/map_navigator_controller.dart'; typedef BonfireMapBuilder = Widget Function( @@ -12,7 +11,9 @@ typedef BonfireMapBuilder = Widget Function( ); typedef MapItemBuilder = MapItem Function( - BuildContext context, Object? arguments); + BuildContext context, + Object? arguments, +); class MapNavigator extends StatefulWidget { final Map maps; @@ -24,9 +25,9 @@ class MapNavigator extends StatefulWidget { final Curve transitionCurve; MapNavigator({ - super.key, required this.maps, required this.builder, + super.key, this.initialMap, this.transitionBuilder, this.layoutBuilder, diff --git a/lib/widgets/map_navigator/map_navigator_provider.dart b/lib/widgets/map_navigator/map_navigator_provider.dart index 4ad5fb45c..1f1e6d418 100644 --- a/lib/widgets/map_navigator/map_navigator_provider.dart +++ b/lib/widgets/map_navigator/map_navigator_provider.dart @@ -4,9 +4,9 @@ import 'package:flutter/material.dart'; class MapNavigatorProvider extends InheritedWidget { final MapNavigatorController controller; const MapNavigatorProvider({ - super.key, required this.controller, required super.child, + super.key, }); static MapNavigatorProvider? maybeOf(BuildContext context) { @@ -14,7 +14,7 @@ class MapNavigatorProvider extends InheritedWidget { } static MapNavigatorProvider of(BuildContext context) { - final MapNavigatorProvider? result = maybeOf(context); + final result = maybeOf(context); assert(result != null, 'No FrogColor found in context'); return result!; } diff --git a/lib/widgets/mini_map/mini_map.dart b/lib/widgets/mini_map/mini_map.dart index 480ffc27e..c37cdd492 100644 --- a/lib/widgets/mini_map/mini_map.dart +++ b/lib/widgets/mini_map/mini_map.dart @@ -1,10 +1,10 @@ import 'dart:async' as async; import 'package:bonfire/bonfire.dart'; +import 'package:bonfire/util/extensions/color_extensions.dart'; +import 'package:bonfire/widgets/mini_map/mini_map_canvas.dart'; import 'package:flutter/material.dart'; -import 'mini_map_canvas.dart'; - /// /// Created by /// @@ -18,7 +18,9 @@ import 'mini_map_canvas.dart'; /// on 12/04/22 typedef MiniMapCustomRender = void Function( - Canvas canvas, T component); + Canvas canvas, + T component, +); class MiniMap extends StatefulWidget { final BonfireGame game; @@ -38,8 +40,8 @@ class MiniMap extends StatefulWidget { final Color? decorationColor; final double zoom; MiniMap({ - Key? key, required this.game, + super.key, this.tileRender, this.componentsRender, Vector2? size, @@ -55,8 +57,7 @@ class MiniMap extends StatefulWidget { this.allyColor, this.zoom = 1.0, this.decorationColor, - }) : size = size ?? Vector2(200, 200), - super(key: key); + }) : size = size ?? Vector2(200, 200); @override State createState() => _MiniMapState(); @@ -98,7 +99,7 @@ class _MiniMapState extends State { height: widget.size.y, decoration: BoxDecoration( border: widget.border, - color: widget.backgroundColor ?? Colors.grey.withOpacity(0.5), + color: widget.backgroundColor ?? Colors.grey.setOpacity(0.5), borderRadius: widget.borderRadius, ), child: ClipRRect( @@ -136,20 +137,20 @@ class _MiniMapState extends State { MiniMapCustomRender tilesRenderDefault() => (canvas, component) { - var collisionList = component.children.query(); + final collisionList = component.children.query(); if (collisionList.isEmpty && widget.tileColor != null) { canvas.drawRect( component.toRect(), tilePaint..color = widget.tileColor!, ); } else { - for (var element in collisionList) { - var rect = element.toRect(); + for (final element in collisionList) { + final rect = element.toRect(); canvas.drawRect( rect.translate(component.x, component.y), tileCollisionPaint ..color = - widget.tileCollisionColor ?? Colors.black.withOpacity(0.5), + widget.tileCollisionColor ?? Colors.black.setOpacity(0.5), ); } } @@ -161,7 +162,7 @@ class _MiniMapState extends State { component.center.toOffset(), component.width / 2, paintComponent - ..color = widget.playerColor ?? Colors.cyan.withOpacity(0.5), + ..color = widget.playerColor ?? Colors.cyan.setOpacity(0.5), ); return; } @@ -171,7 +172,7 @@ class _MiniMapState extends State { component.center.toOffset(), component.width / 2, paintComponent - ..color = widget.enemyColor ?? Colors.red.withOpacity(0.5), + ..color = widget.enemyColor ?? Colors.red.setOpacity(0.5), ); return; } @@ -181,7 +182,7 @@ class _MiniMapState extends State { component.center.toOffset(), component.width / 2, paintComponent - ..color = widget.allyColor ?? Colors.yellow.withOpacity(0.5), + ..color = widget.allyColor ?? Colors.yellow.setOpacity(0.5), ); return; } @@ -191,7 +192,7 @@ class _MiniMapState extends State { component.center.toOffset(), component.width / 2, paintComponent - ..color = widget.npcColor ?? Colors.green.withOpacity(0.5), + ..color = widget.npcColor ?? Colors.green.setOpacity(0.5), ); return; } @@ -200,7 +201,7 @@ class _MiniMapState extends State { canvas.drawRect( component.toRect(), paintComponent - ..color = widget.decorationColor ?? Colors.grey.withOpacity(0.5), + ..color = widget.decorationColor ?? Colors.grey.setOpacity(0.5), ); } }; diff --git a/lib/widgets/mini_map/mini_map_canvas.dart b/lib/widgets/mini_map/mini_map_canvas.dart index f25e2ffab..a405b69cf 100644 --- a/lib/widgets/mini_map/mini_map_canvas.dart +++ b/lib/widgets/mini_map/mini_map_canvas.dart @@ -35,9 +35,9 @@ class MiniMapCanvas extends CustomPainter { @override void paint(Canvas canvas, Size size) { - double scaleX = size.width / gameSize.x; - double scaleY = size.height / gameSize.y; - double scale = max(scaleX, scaleY) * zoom; + final scaleX = size.width / gameSize.x; + final scaleY = size.height / gameSize.y; + final scale = max(scaleX, scaleY) * zoom; canvas.translate( -cameraPosition.x * scale + size.width / 2 - (gameSize.x * scale) / 2, @@ -45,10 +45,10 @@ class MiniMapCanvas extends CustomPainter { ); canvas.save(); canvas.scale(scale); - for (var element in tiles) { + for (final element in tiles) { tileRender?.call(canvas, element); } - for (var element in components) { + for (final element in components) { componentsRender?.call(canvas, element); } canvas.restore(); diff --git a/lib/widgets/typewriter/typewriter.dart b/lib/widgets/typewriter/typewriter.dart index b5fcdb9c7..9fea91261 100644 --- a/lib/widgets/typewriter/typewriter.dart +++ b/lib/widgets/typewriter/typewriter.dart @@ -65,9 +65,9 @@ class TypeWriter extends StatefulWidget { /// {@macro flutter.painting.textPainter.textWidthBasis} final TextWidthBasis textWidthBasis; const TypeWriter({ - Key? key, - this.style, required this.text, + super.key, + this.style, this.speed = 50, this.autoStart = true, this.onFinish, @@ -75,12 +75,12 @@ class TypeWriter extends StatefulWidget { this.textDirection, this.softWrap = true, this.overflow = TextOverflow.clip, - this.textScaler = const TextScaler.linear(1), + this.textScaler = TextScaler.noScaling, this.maxLines, this.locale, this.strutStyle, this.textWidthBasis = TextWidthBasis.parent, - }) : super(key: key); + }); @override State createState() => TypeWriterState(); @@ -131,7 +131,7 @@ class TypeWriterState extends State { ); } - void start({List? text}) async { + Future start({List? text}) async { _finished = false; if (text != null) { textSpanList = text; @@ -139,11 +139,15 @@ class TypeWriterState extends State { // Clean the stream to prevent textStyle from changing before the text _textSpanController.add([const TextSpan()]); - for (var span in textSpanList) { - if (_textSpanController.isClosed) return; - for (int i = 0; i < (span.text?.length ?? 0); i++) { + for (final span in textSpanList) { + if (_textSpanController.isClosed) { + return; + } + for (var i = 0; i < (span.text?.length ?? 0); i++) { await Future.delayed(Duration(milliseconds: widget.speed)); - if (_textSpanController.isClosed || _finished) return; + if (_textSpanController.isClosed || _finished) { + return; + } _textSpanController.add( [ ...textSpanList.sublist(0, textSpanList.indexOf(span)), diff --git a/pubspec.lock b/pubspec.lock index d145c5c71..4d9e84f97 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,10 +5,10 @@ packages: dependency: "direct main" description: name: a_star_algorithm - sha256: c9a92079331f8229f572718ed12c25b0e3adf3570318becfa689f5554e6ffd30 + sha256: efc131ca9a3eaceebe09fa67b9a7235d6e0a6e23ff0de4c009c60d506f791349 url: "https://pub.dev" source: hosted - version: "0.3.2" + version: "0.4.1" archive: dependency: transitive description: @@ -53,10 +53,10 @@ packages: dependency: transitive description: name: collection - sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf url: "https://pub.dev" source: hosted - version: "1.18.0" + version: "1.19.0" crypto: dependency: transitive description: @@ -81,19 +81,19 @@ packages: url: "https://pub.dev" source: hosted version: "1.18.0" + flame_lint: + dependency: "direct dev" + description: + name: flame_lint + sha256: b5bdef4193438b3d6b5827aece830eb295e6b75620570d5013c93f7bef2cb279 + url: "https://pub.dev" + source: hosted + version: "1.2.1" flutter: dependency: "direct main" description: flutter source: sdk version: "0.0.0" - flutter_lints: - dependency: "direct dev" - description: - name: flutter_lints - sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04 - url: "https://pub.dev" - source: hosted - version: "2.0.3" flutter_test: dependency: "direct dev" description: flutter @@ -119,18 +119,18 @@ packages: dependency: transitive description: name: leak_tracker - sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05" + sha256: "7bb2830ebd849694d1ec25bf1f44582d6ac531a57a365a803a6034ff751d2d06" url: "https://pub.dev" source: hosted - version: "10.0.5" + version: "10.0.7" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806" + sha256: "9491a714cca3667b60b5c420da8217e6de0d1ba7a5ec322fab01758f6998f379" url: "https://pub.dev" source: hosted - version: "3.0.5" + version: "3.0.8" leak_tracker_testing: dependency: transitive description: @@ -143,10 +143,10 @@ packages: dependency: transitive description: name: lints - sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" + sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "4.0.0" matcher: dependency: transitive description: @@ -191,7 +191,7 @@ packages: dependency: transitive description: flutter source: sdk - version: "0.0.99" + version: "0.0.0" source_span: dependency: transitive description: @@ -204,10 +204,10 @@ packages: dependency: transitive description: name: stack_trace - sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + sha256: "9f47fd3630d76be3ab26f0ee06d213679aa425996925ff3feffdec504931c377" url: "https://pub.dev" source: hosted - version: "1.11.1" + version: "1.12.0" stream_channel: dependency: transitive description: @@ -220,10 +220,10 @@ packages: dependency: transitive description: name: string_scanner - sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + sha256: "688af5ed3402a4bde5b3a6c15fd768dbf2621a614950b17f04626c431ab3c4c3" url: "https://pub.dev" source: hosted - version: "1.2.0" + version: "1.3.0" term_glyph: dependency: transitive description: @@ -236,10 +236,10 @@ packages: dependency: transitive description: name: test_api - sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb" + sha256: "664d3a9a64782fcdeb83ce9c6b39e78fd2971d4e37827b9b06c3aa1edc5e760c" url: "https://pub.dev" source: hosted - version: "0.7.2" + version: "0.7.3" tiledjsonreader: dependency: "direct main" description: @@ -268,10 +268,10 @@ packages: dependency: transitive description: name: vm_service - sha256: f652077d0bdf60abe4c1f6377448e8655008eef28f128bc023f7b5e8dfeb48fc + sha256: f6be3ed8bd01289b34d679c2b62226f63c0e69f9fd2e50a6b3c1c729a961041b url: "https://pub.dev" source: hosted - version: "14.2.4" + version: "14.3.0" web: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 56c768f00..1ed3021fa 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: bonfire description: (RPG maker) Create RPG-style or similar games more simply with Flame. -version: 3.12.3 +version: 3.12.5 homepage: https://bonfire-engine.github.io repository: https://github.com/RafaelBarbosatec/bonfire issue_tracker: https://github.com/RafaelBarbosatec/bonfire/issues @@ -13,15 +13,14 @@ dependencies: flutter: sdk: flutter + a_star_algorithm: ^0.4.1 + http: ^1.2.2 flame: 1.18.0 tiledjsonreader: ^1.4.1 - http: ^1.2.2 - a_star_algorithm: ^0.3.2 dev_dependencies: + flame_lint: ^1.2.1 flutter_test: sdk: flutter - flutter_lints: ^2.0.0 - flutter: