├── doc ├── README.md └── design.xlsx ├── test └── test.dart ├── linux ├── .gitignore ├── main.cc ├── flutter │ ├── generated_plugin_registrant.h │ ├── generated_plugin_registrant.cc │ ├── generated_plugins.cmake │ └── CMakeLists.txt ├── my_application.h ├── my_application.cc └── CMakeLists.txt ├── macos ├── Flutter │ ├── Flutter-Debug.xcconfig │ ├── Flutter-Release.xcconfig │ └── GeneratedPluginRegistrant.swift ├── Runner │ ├── Configs │ │ ├── Debug.xcconfig │ │ ├── Release.xcconfig │ │ ├── Warnings.xcconfig │ │ └── AppInfo.xcconfig │ ├── Assets.xcassets │ │ └── AppIcon.appiconset │ │ │ ├── app_icon_16.png │ │ │ ├── app_icon_32.png │ │ │ ├── app_icon_64.png │ │ │ ├── app_icon_1024.png │ │ │ ├── app_icon_128.png │ │ │ ├── app_icon_256.png │ │ │ ├── app_icon_512.png │ │ │ └── Contents.json │ ├── AppDelegate.swift │ ├── Release.entitlements │ ├── DebugProfile.entitlements │ ├── MainFlutterWindow.swift │ └── Info.plist ├── .gitignore ├── Runner.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist ├── Runner.xcodeproj │ ├── project.xcworkspace │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ └── xcshareddata │ │ └── xcschemes │ │ └── Runner.xcscheme └── RunnerTests │ └── RunnerTests.swift ├── assets ├── screenshot.jpg ├── images │ ├── destroy.png │ ├── destroy2.png │ ├── diaglog.png │ ├── blackhole.png │ ├── diag_arrow.png │ ├── weapon │ │ ├── MG.png │ │ ├── MG2.png │ │ ├── MG3.png │ │ ├── Cannon.png │ │ ├── Tower.png │ │ ├── Bullet1.png │ │ ├── Bullet2.png │ │ ├── Cannon2.png │ │ ├── Cannon3.png │ │ ├── Missile.png │ │ ├── Bullet_MG.png │ │ ├── explosion1.png │ │ ├── explosion2.png │ │ ├── explosion3.png │ │ ├── Missile_Launcher.png │ │ ├── Missile_Launcher2.png │ │ └── Missile_Launcher3.png │ ├── whitehole.png │ ├── enemy │ │ ├── enemyA.png │ │ ├── enemyB.png │ │ ├── enemyC.png │ │ └── enemyD.png │ └── neutral │ │ ├── mine.png │ │ └── mine_cluster.png ├── spacescape │ ├── images │ │ ├── nuke.png │ │ ├── freeze.png │ │ ├── ship_A.png │ │ ├── ship_B.png │ │ ├── ship_C.png │ │ ├── ship_D.png │ │ ├── ship_E.png │ │ ├── ship_F.png │ │ ├── ship_G.png │ │ ├── ship_H.png │ │ ├── stars1.png │ │ ├── stars2.png │ │ ├── multi_fire.png │ │ ├── icon_plusSmall.png │ │ ├── simpleSpace_tilesheet@2.png │ │ └── README.md │ ├── audio │ │ ├── laser1.ogg │ │ ├── powerUp6.ogg │ │ ├── laserSmall_001.ogg │ │ └── README.md │ └── fonts │ │ └── BungeeInline │ │ ├── BungeeInline-Regular.ttf │ │ ├── README.md │ │ └── OFL.txt ├── enemyParams.json ├── weaponParams.json └── tiles │ └── 0929.tmx ├── windows ├── runner │ ├── resources │ │ └── app_icon.ico │ ├── resource.h │ ├── utils.h │ ├── runner.exe.manifest │ ├── flutter_window.h │ ├── main.cpp │ ├── CMakeLists.txt │ ├── utils.cpp │ ├── flutter_window.cpp │ ├── Runner.rc │ └── win32_window.h ├── .gitignore ├── flutter │ ├── generated_plugin_registrant.h │ ├── generated_plugin_registrant.cc │ ├── generated_plugins.cmake │ └── CMakeLists.txt └── CMakeLists.txt ├── lib ├── base │ ├── scanable.dart │ ├── life_indicator.dart │ ├── game_ref.dart │ ├── game_component.dart │ ├── movable.dart │ └── radar.dart ├── astar │ ├── README.md │ ├── astarnode.dart │ ├── array2d.dart │ └── astarmap.dart ├── links │ └── combined_flame_game.dart ├── neutral │ ├── neutral_setting.dart │ └── neutral_component.dart ├── spacescape │ ├── game │ │ ├── command.dart │ │ ├── knows_game_size.dart │ │ ├── health_bar.dart │ │ ├── audio_player_component.dart │ │ ├── bullet.dart │ │ ├── power_up_manager.dart │ │ └── power_ups.dart │ ├── models │ │ ├── enemy_data.dart │ │ ├── settings.dart │ │ ├── settings.g.dart │ │ ├── player_data.g.dart │ │ ├── spaceship_details.g.dart │ │ ├── spaceship_details.dart │ │ └── player_data.dart │ ├── widgets │ │ └── overlays │ │ │ ├── pause_button.dart │ │ │ ├── game_over_menu.dart │ │ │ └── pause_menu.dart │ ├── screens │ │ ├── game_play.dart │ │ ├── main_menu.dart │ │ └── settings_menu.dart │ └── main.dart ├── map │ ├── map_tile_component.dart │ ├── map_controller.dart │ └── astarmap_minxin.dart ├── enemy │ ├── enemy_setting.dart │ ├── enemy_v1.dart │ ├── enemy_factory.dart │ └── enemy_component.dart ├── weapon │ ├── bullet_component.dart │ ├── cannon.dart │ ├── machine_gun.dart │ ├── missile.dart │ └── weapon_setting.dart ├── view │ ├── mine_view.dart │ ├── gamebar_view.dart │ ├── weaponview_widget.dart │ └── weapon_factory_view.dart ├── main.dart └── game │ ├── game_main.dart │ ├── game_setting.dart │ └── game_test.dart ├── scripts ├── clean_windows_build.bat └── clean_windows_build.ps1 ├── pubspec.yaml ├── LICENSE.SpaceScape ├── .metadata ├── analysis_options.yaml ├── .gitignore └── README.md /doc/README.md: -------------------------------------------------------------------------------- 1 | TBD -------------------------------------------------------------------------------- /test/test.dart: -------------------------------------------------------------------------------- 1 | void main() {} 2 | -------------------------------------------------------------------------------- /linux/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral 2 | -------------------------------------------------------------------------------- /macos/Flutter/Flutter-Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include "ephemeral/Flutter-Generated.xcconfig" 2 | -------------------------------------------------------------------------------- /doc/design.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/doc/design.xlsx -------------------------------------------------------------------------------- /macos/Flutter/Flutter-Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include "ephemeral/Flutter-Generated.xcconfig" 2 | -------------------------------------------------------------------------------- /assets/screenshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/screenshot.jpg -------------------------------------------------------------------------------- /assets/images/destroy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/destroy.png -------------------------------------------------------------------------------- /assets/images/destroy2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/destroy2.png -------------------------------------------------------------------------------- /assets/images/diaglog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/diaglog.png -------------------------------------------------------------------------------- /assets/images/blackhole.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/blackhole.png -------------------------------------------------------------------------------- /assets/images/diag_arrow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/diag_arrow.png -------------------------------------------------------------------------------- /assets/images/weapon/MG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/MG.png -------------------------------------------------------------------------------- /assets/images/weapon/MG2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/MG2.png -------------------------------------------------------------------------------- /assets/images/weapon/MG3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/MG3.png -------------------------------------------------------------------------------- /assets/images/whitehole.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/whitehole.png -------------------------------------------------------------------------------- /assets/images/enemy/enemyA.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/enemy/enemyA.png -------------------------------------------------------------------------------- /assets/images/enemy/enemyB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/enemy/enemyB.png -------------------------------------------------------------------------------- /assets/images/enemy/enemyC.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/enemy/enemyC.png -------------------------------------------------------------------------------- /assets/images/enemy/enemyD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/enemy/enemyD.png -------------------------------------------------------------------------------- /assets/images/neutral/mine.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/neutral/mine.png -------------------------------------------------------------------------------- /assets/images/weapon/Cannon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Cannon.png -------------------------------------------------------------------------------- /assets/images/weapon/Tower.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Tower.png -------------------------------------------------------------------------------- /macos/Runner/Configs/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Debug.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /assets/images/weapon/Bullet1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Bullet1.png -------------------------------------------------------------------------------- /assets/images/weapon/Bullet2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Bullet2.png -------------------------------------------------------------------------------- /assets/images/weapon/Cannon2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Cannon2.png -------------------------------------------------------------------------------- /assets/images/weapon/Cannon3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Cannon3.png -------------------------------------------------------------------------------- /assets/images/weapon/Missile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Missile.png -------------------------------------------------------------------------------- /assets/spacescape/images/nuke.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/nuke.png -------------------------------------------------------------------------------- /macos/Runner/Configs/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Release.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /assets/images/weapon/Bullet_MG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Bullet_MG.png -------------------------------------------------------------------------------- /assets/images/weapon/explosion1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/explosion1.png -------------------------------------------------------------------------------- /assets/images/weapon/explosion2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/explosion2.png -------------------------------------------------------------------------------- /assets/images/weapon/explosion3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/explosion3.png -------------------------------------------------------------------------------- /assets/spacescape/audio/laser1.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/audio/laser1.ogg -------------------------------------------------------------------------------- /assets/spacescape/audio/powerUp6.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/audio/powerUp6.ogg -------------------------------------------------------------------------------- /assets/spacescape/images/freeze.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/freeze.png -------------------------------------------------------------------------------- /assets/spacescape/images/ship_A.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/ship_A.png -------------------------------------------------------------------------------- /assets/spacescape/images/ship_B.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/ship_B.png -------------------------------------------------------------------------------- /assets/spacescape/images/ship_C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/ship_C.png -------------------------------------------------------------------------------- /assets/spacescape/images/ship_D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/ship_D.png -------------------------------------------------------------------------------- /assets/spacescape/images/ship_E.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/ship_E.png -------------------------------------------------------------------------------- /assets/spacescape/images/ship_F.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/ship_F.png -------------------------------------------------------------------------------- /assets/spacescape/images/ship_G.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/ship_G.png -------------------------------------------------------------------------------- /assets/spacescape/images/ship_H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/ship_H.png -------------------------------------------------------------------------------- /assets/spacescape/images/stars1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/stars1.png -------------------------------------------------------------------------------- /assets/spacescape/images/stars2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/stars2.png -------------------------------------------------------------------------------- /macos/.gitignore: -------------------------------------------------------------------------------- 1 | # Flutter-related 2 | **/Flutter/ephemeral/ 3 | **/Pods/ 4 | 5 | # Xcode-related 6 | **/dgph 7 | **/xcuserdata/ 8 | -------------------------------------------------------------------------------- /assets/images/neutral/mine_cluster.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/neutral/mine_cluster.png -------------------------------------------------------------------------------- /windows/runner/resources/app_icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/windows/runner/resources/app_icon.ico -------------------------------------------------------------------------------- /assets/images/weapon/Missile_Launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Missile_Launcher.png -------------------------------------------------------------------------------- /assets/spacescape/images/multi_fire.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/multi_fire.png -------------------------------------------------------------------------------- /assets/images/weapon/Missile_Launcher2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Missile_Launcher2.png -------------------------------------------------------------------------------- /assets/images/weapon/Missile_Launcher3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/images/weapon/Missile_Launcher3.png -------------------------------------------------------------------------------- /assets/spacescape/audio/laserSmall_001.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/audio/laserSmall_001.ogg -------------------------------------------------------------------------------- /assets/spacescape/images/icon_plusSmall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/icon_plusSmall.png -------------------------------------------------------------------------------- /lib/base/scanable.dart: -------------------------------------------------------------------------------- 1 | import 'package:freedefense/base/game_component.dart'; 2 | 3 | mixin Scanable on GameComponent { 4 | bool scanable = true; 5 | } 6 | -------------------------------------------------------------------------------- /lib/astar/README.md: -------------------------------------------------------------------------------- 1 | Astar algorighm initially made by Tyriar. Introduce small modification to serve our game. 2 | 3 | https://github.com/Tyriar/canvas-astar.dart -------------------------------------------------------------------------------- /assets/spacescape/images/simpleSpace_tilesheet@2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/images/simpleSpace_tilesheet@2.png -------------------------------------------------------------------------------- /assets/spacescape/fonts/BungeeInline/BungeeInline-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/assets/spacescape/fonts/BungeeInline/BungeeInline-Regular.ttf -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudseasail/free_defense/HEAD/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png -------------------------------------------------------------------------------- /linux/main.cc: -------------------------------------------------------------------------------- 1 | #include "my_application.h" 2 | 3 | int main(int argc, char** argv) { 4 | g_autoptr(MyApplication) app = my_application_new(); 5 | return g_application_run(G_APPLICATION(app), argc, argv); 6 | } 7 | -------------------------------------------------------------------------------- /assets/spacescape/images/README.md: -------------------------------------------------------------------------------- 1 | # Image assets 2 | 3 | - Assets from [Kenney.nl](https://kenney.nl/assets/simple-space) 4 | 5 | - Extended assets from [DevKage](https://ufrshubham.itch.io/spacescape-extended-assets) 6 | -------------------------------------------------------------------------------- /macos/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /lib/links/combined_flame_game.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/game.dart'; 2 | import 'package:flame/input.dart'; 3 | 4 | class CombinedFlameGame extends FlameGame with HasCollisionDetection, HasKeyboardHandlerComponents { 5 | void reset() {} 6 | } 7 | -------------------------------------------------------------------------------- /assets/spacescape/fonts/BungeeInline/README.md: -------------------------------------------------------------------------------- 1 | # Font assets 2 | 3 | - Get the original font file from [Google Fonts](https://fonts.google.com/specimen/Bungee+Inline?query=Bung) and place **BungeeInline-Regular.ttf** from the downloaded zip in this directory 4 | -------------------------------------------------------------------------------- /macos/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | @NSApplicationMain 5 | class AppDelegate: FlutterAppDelegate { 6 | override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { 7 | return true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /macos/Runner/Release.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /macos/RunnerTests/RunnerTests.swift: -------------------------------------------------------------------------------- 1 | import FlutterMacOS 2 | import Cocoa 3 | import XCTest 4 | 5 | class RunnerTests: XCTestCase { 6 | 7 | func testExample() { 8 | // If you add code to the Runner application, consider adding tests here. 9 | // See https://developer.apple.com/documentation/xctest for more information about using XCTest. 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /scripts/clean_windows_build.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | setlocal 3 | REM Wrapper to clean stale Windows build artifacts that cause CMake cache/source path mismatches. 4 | REM Usage: From the project root, run: 5 | REM scripts\clean_windows_build.bat 6 | 7 | set SCRIPT_DIR=%~dp0 8 | powershell -NoProfile -ExecutionPolicy Bypass -File "%SCRIPT_DIR%clean_windows_build.ps1" 9 | 10 | endlocal 11 | -------------------------------------------------------------------------------- /windows/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral/ 2 | 3 | # Visual Studio user-specific files. 4 | *.suo 5 | *.user 6 | *.userosscache 7 | *.sln.docstates 8 | 9 | # Visual Studio build-related files. 10 | x64/ 11 | x86/ 12 | 13 | # Visual Studio cache files 14 | # files ending in .cache can be ignored 15 | *.[Cc]ache 16 | # but keep track of directories ending in .cache 17 | !*.[Cc]ache/ 18 | -------------------------------------------------------------------------------- /linux/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void fl_register_plugins(FlPluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /windows/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void RegisterPlugins(flutter::PluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /lib/neutral/neutral_setting.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/cache.dart'; 2 | import 'package:flame/components.dart'; 3 | 4 | class NeutralSetting { 5 | late Sprite mine; 6 | late Sprite mineCluster; 7 | 8 | Future load() async { 9 | final images = Images(); 10 | mine = Sprite(await images.load('neutral/mine.png')); 11 | mineCluster = Sprite(await images.load('neutral/mine_cluster.png')); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /macos/Runner/DebugProfile.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.cs.allow-jit 8 | 9 | com.apple.security.network.server 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /windows/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | #include 10 | 11 | void RegisterPlugins(flutter::PluginRegistry* registry) { 12 | AudioplayersWindowsPluginRegisterWithRegistrar( 13 | registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin")); 14 | } 15 | -------------------------------------------------------------------------------- /linux/my_application.h: -------------------------------------------------------------------------------- 1 | #ifndef FLUTTER_MY_APPLICATION_H_ 2 | #define FLUTTER_MY_APPLICATION_H_ 3 | 4 | #include 5 | 6 | G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, 7 | GtkApplication) 8 | 9 | /** 10 | * my_application_new: 11 | * 12 | * Creates a new Flutter-based application. 13 | * 14 | * Returns: a new #MyApplication. 15 | */ 16 | MyApplication* my_application_new(); 17 | 18 | #endif // FLUTTER_MY_APPLICATION_H_ 19 | -------------------------------------------------------------------------------- /macos/Runner/MainFlutterWindow.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | class MainFlutterWindow: NSWindow { 5 | override func awakeFromNib() { 6 | let flutterViewController = FlutterViewController() 7 | let windowFrame = self.frame 8 | self.contentViewController = flutterViewController 9 | self.setFrame(windowFrame, display: true) 10 | 11 | RegisterGeneratedPlugins(registry: flutterViewController) 12 | 13 | super.awakeFromNib() 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /macos/Flutter/GeneratedPluginRegistrant.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | import FlutterMacOS 6 | import Foundation 7 | 8 | import audioplayers_darwin 9 | import path_provider_foundation 10 | 11 | func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { 12 | AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin")) 13 | PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) 14 | } 15 | -------------------------------------------------------------------------------- /windows/runner/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by Runner.rc 4 | // 5 | #define IDI_APP_ICON 101 6 | 7 | // Next default values for new objects 8 | // 9 | #ifdef APSTUDIO_INVOKED 10 | #ifndef APSTUDIO_READONLY_SYMBOLS 11 | #define _APS_NEXT_RESOURCE_VALUE 102 12 | #define _APS_NEXT_COMMAND_VALUE 40001 13 | #define _APS_NEXT_CONTROL_VALUE 1001 14 | #define _APS_NEXT_SYMED_VALUE 101 15 | #endif 16 | #endif 17 | -------------------------------------------------------------------------------- /linux/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | #include 10 | 11 | void fl_register_plugins(FlPluginRegistry* registry) { 12 | g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar = 13 | fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin"); 14 | audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar); 15 | } 16 | -------------------------------------------------------------------------------- /lib/spacescape/game/command.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | 3 | // This class represents a command that will be run 4 | // on every component of type T added to game instance. 5 | class Command { 6 | // A callback function to be run on 7 | // components of type T. 8 | void Function(T target) action; 9 | 10 | Command({required this.action}); 11 | 12 | // Runs the callback on given component 13 | // if it is of type T. 14 | void run(Component c) { 15 | if (c is T) { 16 | action.call(c); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /lib/astar/astarnode.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * canvas-astar.dart 3 | * MIT licensed 4 | * 5 | * Created by Daniel Imms, http://www.growingwiththeweb.com 6 | */ 7 | 8 | class AstarNode { 9 | AstarNode? parent; 10 | AstarNode? next; 11 | late int x; 12 | late int y; 13 | late double g; 14 | late double f; 15 | 16 | AstarNode(this.x, this.y, {this.parent, double cost = 0.0}) { 17 | g = (parent != null ? parent!.g : 0) + cost; 18 | } 19 | 20 | bool operator ==(dynamic other) { 21 | return (x == other.x && y == other.y); 22 | } 23 | 24 | int get hashCode => super.hashCode; 25 | } 26 | -------------------------------------------------------------------------------- /lib/spacescape/game/knows_game_size.dart: -------------------------------------------------------------------------------- 1 | // IMPORTANT NOTE 2 | // This class is obsolete since Flame v1.2.0 version 3 | // This code remains as is as a reference for the YouTube tutorial. 4 | 5 | // import 'package:flame/components.dart'; 6 | 7 | // Adding this mixin to any class derived from BaseComponent will make sure that 8 | // the components gets access to current gameSize. Do not try to access gameSize 9 | // before your components is added to the game instance. 10 | // mixin KnowsGameSize on Component { 11 | // late Vector2 gameSize; 12 | 13 | // void onResize(Vector2 newGameSize) { 14 | // gameSize = newGameSize; 15 | // } 16 | // } 17 | -------------------------------------------------------------------------------- /assets/spacescape/audio/README.md: -------------------------------------------------------------------------------- 1 | # Audio assets 2 | 3 | ## I don't have rights to redistribute all the audio assets, but you can get the original assets for following links: 4 | 5 | - __9. Space Invaders.wav__ background music from [VOiD1 Gaming](https://void1gaming.itch.io/)'s [Free Synthwave music pack](https://void1gaming.itch.io/free-synthwave-music-pack) 6 | 7 | - **laserSmall_001.ogg** sound effect from [Kenney.nl](https://kenney.nl/)'s [Sci-Fi Sounds](https://www.kenney.nl/assets/sci-fi-sounds) 8 | 9 | - __laser1.ogg__ and __powerUp6.ogg__ sound effects from [Kenney.nl](https://kenney.nl/)'s [Digital Audio](https://www.kenney.nl/assets/digital-audio) 10 | -------------------------------------------------------------------------------- /lib/base/life_indicator.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:freedefense/base/game_component.dart'; 4 | 5 | mixin LifeIndicator on GameComponent { 6 | double maxLife = 0; 7 | double life = 0; 8 | 9 | void renderLifIndicator(Canvas c) { 10 | if (maxLife == 0) return; 11 | Vector2 start = Vector2.zero(); 12 | Vector2 mid = Vector2((life / maxLife) * size.x, 0); 13 | Vector2 end = Vector2(size.x, 0); 14 | c.drawLine(start.toOffset(), mid.toOffset(), Paint()..color = Colors.green); 15 | c.drawLine(mid.toOffset(), end.toOffset(), Paint()..color = Colors.red); } 16 | } 17 | -------------------------------------------------------------------------------- /macos/Runner/Configs/Warnings.xcconfig: -------------------------------------------------------------------------------- 1 | WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings 2 | GCC_WARN_UNDECLARED_SELECTOR = YES 3 | CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES 4 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE 5 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES 6 | CLANG_WARN_PRAGMA_PACK = YES 7 | CLANG_WARN_STRICT_PROTOTYPES = YES 8 | CLANG_WARN_COMMA = YES 9 | GCC_WARN_STRICT_SELECTOR_MATCH = YES 10 | CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES 11 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES 12 | GCC_WARN_SHADOW = YES 13 | CLANG_WARN_UNREACHABLE_CODE = YES 14 | -------------------------------------------------------------------------------- /assets/enemyParams.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "life": 80.0, 4 | "speed": 50, 5 | "scale": 0.8, 6 | "image": "enemy/enemyA.png", 7 | "columns": 2, 8 | "rows": 3 9 | }, 10 | { 11 | "life": 150, 12 | "speed": 60, 13 | "scale": 1.0, 14 | "image": "enemy/enemyB.png", 15 | "columns": 2, 16 | "rows": 3 17 | }, 18 | { 19 | "life": 80, 20 | "speed": 100, 21 | "scale": 1.1, 22 | "image": "enemy/enemyC.png", 23 | "columns": 2, 24 | "rows": 3 25 | }, 26 | { 27 | "life": 300, 28 | "speed": 50, 29 | "scale": 0.8, 30 | "image": "enemy/enemyD.png", 31 | "columns": 2, 32 | "rows": 3 33 | } 34 | ] -------------------------------------------------------------------------------- /macos/Runner/Configs/AppInfo.xcconfig: -------------------------------------------------------------------------------- 1 | // Application-level settings for the Runner target. 2 | // 3 | // This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the 4 | // future. If not, the values below would default to using the project name when this becomes a 5 | // 'flutter create' template. 6 | 7 | // The application's name. By default this is also the title of the Flutter window. 8 | PRODUCT_NAME = free_defense 9 | 10 | // The application's bundle identifier 11 | PRODUCT_BUNDLE_IDENTIFIER = com.example.freeDefense 12 | 13 | // The copyright displayed in application information 14 | PRODUCT_COPYRIGHT = Copyright © 2023 com.example. All rights reserved. 15 | -------------------------------------------------------------------------------- /lib/spacescape/models/enemy_data.dart: -------------------------------------------------------------------------------- 1 | /// This class represents all the details required 2 | /// to create an [Enemy] component. 3 | class EnemyData { 4 | // Speed of the enemy. 5 | final double speed; 6 | 7 | // Sprite ID from the main sprite sheet. 8 | final int spriteId; 9 | 10 | // Level of this enemy. 11 | final int level; 12 | 13 | // Indicates if this enemy can move horizontally. 14 | final bool hMove; 15 | 16 | // Points gains after destroying this enemy. 17 | final int killPoint; 18 | 19 | const EnemyData({ 20 | required this.speed, 21 | required this.spriteId, 22 | required this.level, 23 | required this.hMove, 24 | required this.killPoint, 25 | }); 26 | } 27 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: freedefense 2 | description: tower defense game 3 | 4 | version: 1.0.0 5 | 6 | environment: 7 | sdk: ">=2.17.0 <3.0.0" 8 | 9 | dependencies: 10 | flutter: 11 | sdk: flutter 12 | flame: ^1.12.0 13 | path_provider: 2.1.0 14 | provider: 6.0.5 15 | hive: 2.2.3 16 | hive_generator: 2.0.1 17 | hive_flutter: 1.1.0 18 | flutter_carousel_slider: 1.1.0 19 | flame_audio: 2.0.5 20 | 21 | dev_dependencies: 22 | flutter_test: 23 | sdk: flutter 24 | 25 | flutter: 26 | assets: 27 | - assets/images/weapon/ 28 | - assets/images/enemy/ 29 | - assets/images/neutral/ 30 | - assets/images/ 31 | - assets/weaponParams.json 32 | - assets/enemyParams.json 33 | - assets/spacescape/images/ 34 | -------------------------------------------------------------------------------- /lib/spacescape/game/health_bar.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:flutter/material.dart'; 3 | 4 | import 'player.dart'; 5 | 6 | class HealthBar extends PositionComponent { 7 | final Player player; 8 | 9 | HealthBar({ 10 | required this.player, 11 | super.position, 12 | super.size, 13 | super.scale, 14 | super.angle, 15 | super.anchor, 16 | super.children, 17 | super.priority, 18 | }); 19 | 20 | @override 21 | void render(Canvas canvas) { 22 | // Draws a rectangular health bar at top right corner. 23 | canvas.drawRect( 24 | Rect.fromLTWH(-2, 5, player.health.toDouble(), 20), 25 | Paint()..color = Colors.blue, 26 | ); 27 | super.render(canvas); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /windows/runner/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_UTILS_H_ 2 | #define RUNNER_UTILS_H_ 3 | 4 | #include 5 | #include 6 | 7 | // Creates a console for the process, and redirects stdout and stderr to 8 | // it for both the runner and the Flutter library. 9 | void CreateAndAttachConsole(); 10 | 11 | // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string 12 | // encoded in UTF-8. Returns an empty std::string on failure. 13 | std::string Utf8FromUtf16(const wchar_t* utf16_string); 14 | 15 | // Gets the command line arguments passed in as a std::vector, 16 | // encoded in UTF-8. Returns an empty std::vector on failure. 17 | std::vector GetCommandLineArguments(); 18 | 19 | #endif // RUNNER_UTILS_H_ 20 | -------------------------------------------------------------------------------- /lib/base/game_ref.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:freedefense/game/game_main.dart'; 3 | 4 | mixin GameRef on Component { 5 | T? _gameRef; 6 | 7 | T get gameRef { 8 | if (_gameRef == null) { 9 | var c = parent; 10 | while (c != null) { 11 | if (c is HasGameRef) { 12 | _gameRef = c.gameRef; 13 | return _gameRef!; 14 | } else if (c is T) { 15 | _gameRef = c; 16 | return c; 17 | } else { 18 | c = c.parent; 19 | } 20 | } 21 | throw StateError('Cannot find reference $T in the component tree'); 22 | } 23 | return _gameRef!; 24 | } 25 | 26 | @override 27 | void onRemove() { 28 | super.onRemove(); 29 | _gameRef = null; 30 | } 31 | 32 | registerToGame() { 33 | gameRef.add(this); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /linux/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | audioplayers_linux 7 | ) 8 | 9 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 10 | ) 11 | 12 | set(PLUGIN_BUNDLED_LIBRARIES) 13 | 14 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 15 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) 16 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 17 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 18 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 19 | endforeach(plugin) 20 | 21 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 22 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) 23 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 24 | endforeach(ffi_plugin) 25 | -------------------------------------------------------------------------------- /windows/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | audioplayers_windows 7 | ) 8 | 9 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 10 | ) 11 | 12 | set(PLUGIN_BUNDLED_LIBRARIES) 13 | 14 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 15 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) 16 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 17 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 18 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 19 | endforeach(plugin) 20 | 21 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 22 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) 23 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 24 | endforeach(ffi_plugin) 25 | -------------------------------------------------------------------------------- /lib/spacescape/models/settings.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/foundation.dart'; 2 | import 'package:hive/hive.dart'; 3 | 4 | part 'settings.g.dart'; 5 | 6 | @HiveType(typeId: 2) 7 | class Settings extends ChangeNotifier with HiveObjectMixin { 8 | static const String settingsBox = 'SettingsBox'; 9 | static const String settingsKey = 'Settings'; 10 | 11 | @HiveField(0) 12 | bool _sfx = false; 13 | bool get soundEffects => _sfx; 14 | set soundEffects(bool value) { 15 | _sfx = value; 16 | notifyListeners(); 17 | save(); 18 | } 19 | 20 | @HiveField(1) 21 | bool _bgm = false; 22 | bool get backgroundMusic => _bgm; 23 | set backgroundMusic(bool value) { 24 | _bgm = value; 25 | notifyListeners(); 26 | save(); 27 | } 28 | 29 | Settings({ 30 | bool soundEffects = false, 31 | bool backgroundMusic = false, 32 | }) : _bgm = backgroundMusic, 33 | _sfx = soundEffects; 34 | } 35 | -------------------------------------------------------------------------------- /lib/spacescape/widgets/overlays/pause_button.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | import '../../../links/combined_flame_game.dart'; 4 | import 'pause_menu.dart'; 5 | 6 | // This class represents the pause button overlay. 7 | class PauseButton extends StatelessWidget { 8 | static const String id = 'PauseButton'; 9 | final CombinedFlameGame game; 10 | 11 | const PauseButton({Key? key, required this.game}) : super(key: key); 12 | 13 | @override 14 | Widget build(BuildContext context) { 15 | return Align( 16 | alignment: Alignment.topCenter, 17 | child: TextButton( 18 | child: const Icon( 19 | Icons.pause_rounded, 20 | color: Colors.white, 21 | ), 22 | onPressed: () { 23 | game.pauseEngine(); 24 | game.overlays.add(PauseMenu.id); 25 | game.overlays.remove(PauseButton.id); 26 | }, 27 | ), 28 | ); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /windows/runner/runner.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PerMonitorV2 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /lib/neutral/neutral_component.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:freedefense/base/game_component.dart'; 3 | import 'package:freedefense/base/radar.dart'; 4 | import 'package:freedefense/enemy/enemy_component.dart'; 5 | 6 | enum NeutralType { GATE_START, GATE_END, MINDER, STONE } 7 | 8 | class NeutralComponent extends GameComponent with Radar { 9 | double life = 0; 10 | late NeutralType neutualType; 11 | NeutralComponent({ 12 | required Vector2 position, 13 | required Vector2 size, 14 | required this.neutualType, 15 | }) : super(position: position, size: size, priority: 20) { 16 | radarOn = false; 17 | 18 | if (neutualType == NeutralType.GATE_END) { 19 | radarOn = true; 20 | radarRange = (size.x + size.y) / 4; 21 | radarCollisionDepth = 0.9; 22 | radarScanAlert = (c) => (c as EnemyComponent).onArrived(); 23 | } 24 | } 25 | @override 26 | Future? onLoad() async { 27 | await super.onLoad(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /lib/astar/array2d.dart: -------------------------------------------------------------------------------- 1 | // /** 2 | // * canvas-astar.dart 3 | // * MIT licensed 4 | // * 5 | // * Created by Daniel Imms, http://www.growingwiththeweb.com 6 | // */ 7 | 8 | class Array2d { 9 | late List> array; 10 | T defaultValue; 11 | 12 | Array2d(int width, int height, {required this.defaultValue}) { 13 | array = []; 14 | this.width = width; 15 | this.height = height; 16 | } 17 | 18 | operator [](int x) => array[x]; 19 | 20 | set width(int v) { 21 | while (array.length > v) array.removeLast(); 22 | while (array.length < v) { 23 | List newList = []; 24 | if (array.length > 0) { 25 | for (int y = 0; y < array.first.length; y++) newList.add(defaultValue); 26 | } 27 | array.add(newList); 28 | } 29 | } 30 | 31 | set height(int v) { 32 | while (array.first.length > v) { 33 | for (int x = 0; x < array.length; x++) array[x].removeLast(); 34 | } 35 | while (array.first.length < v) { 36 | for (int x = 0; x < array.length; x++) array[x].add(defaultValue); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /windows/runner/flutter_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_FLUTTER_WINDOW_H_ 2 | #define RUNNER_FLUTTER_WINDOW_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include "win32_window.h" 10 | 11 | // A window that does nothing but host a Flutter view. 12 | class FlutterWindow : public Win32Window { 13 | public: 14 | // Creates a new FlutterWindow hosting a Flutter view running |project|. 15 | explicit FlutterWindow(const flutter::DartProject& project); 16 | virtual ~FlutterWindow(); 17 | 18 | protected: 19 | // Win32Window: 20 | bool OnCreate() override; 21 | void OnDestroy() override; 22 | LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, 23 | LPARAM const lparam) noexcept override; 24 | 25 | private: 26 | // The project to run. 27 | flutter::DartProject project_; 28 | 29 | // The Flutter instance hosted by this window. 30 | std::unique_ptr flutter_controller_; 31 | }; 32 | 33 | #endif // RUNNER_FLUTTER_WINDOW_H_ 34 | -------------------------------------------------------------------------------- /LICENSE.SpaceScape: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Shubham Kamble 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /macos/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(FLUTTER_BUILD_NAME) 21 | CFBundleVersion 22 | $(FLUTTER_BUILD_NUMBER) 23 | LSMinimumSystemVersion 24 | $(MACOSX_DEPLOYMENT_TARGET) 25 | NSHumanReadableCopyright 26 | $(PRODUCT_COPYRIGHT) 27 | NSMainNibFile 28 | MainMenu 29 | NSPrincipalClass 30 | NSApplication 31 | 32 | 33 | -------------------------------------------------------------------------------- /lib/spacescape/models/settings.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'settings.dart'; 4 | 5 | // ************************************************************************** 6 | // TypeAdapterGenerator 7 | // ************************************************************************** 8 | 9 | class SettingsAdapter extends TypeAdapter { 10 | @override 11 | final int typeId = 2; 12 | 13 | @override 14 | Settings read(BinaryReader reader) { 15 | final numOfFields = reader.readByte(); 16 | final fields = { 17 | for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), 18 | }; 19 | return Settings() 20 | .._sfx = fields[0] as bool 21 | .._bgm = fields[1] as bool; 22 | } 23 | 24 | @override 25 | void write(BinaryWriter writer, Settings obj) { 26 | writer 27 | ..writeByte(2) 28 | ..writeByte(0) 29 | ..write(obj._sfx) 30 | ..writeByte(1) 31 | ..write(obj._bgm); 32 | } 33 | 34 | @override 35 | int get hashCode => typeId.hashCode; 36 | 37 | @override 38 | bool operator ==(Object other) => 39 | identical(this, other) || 40 | other is SettingsAdapter && 41 | runtimeType == other.runtimeType && 42 | typeId == other.typeId; 43 | } 44 | -------------------------------------------------------------------------------- /lib/map/map_tile_component.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:flame/events.dart'; 3 | import 'package:flutter/material.dart'; 4 | import 'package:freedefense/base/game_component.dart'; 5 | import 'package:freedefense/game/game_controller.dart'; 6 | 7 | enum MapTileBuildStatus { Empty, BuildPreview, BuildDone } 8 | 9 | enum MapTileBuildEvent { None, BuildPreview, BuildDone, BuildCancel } 10 | 11 | class MapTileComponent extends GameComponent with TapCallbacks { 12 | MapTileBuildStatus buildStatus = MapTileBuildStatus.Empty; 13 | GameComponent? refComponent; 14 | bool ableToBuild = true; 15 | Sprite? background; 16 | 17 | MapTileComponent({ 18 | Vector2? position, 19 | Vector2? size, 20 | }) : super( 21 | position: position, 22 | size: size, 23 | ); 24 | 25 | void render(Canvas c) { 26 | super.render(c); 27 | // if (background != null) { 28 | // background!.renderRect(c, size.toRect()); 29 | c.drawRect( 30 | size.toRect(), 31 | Paint() 32 | ..style = PaintingStyle.stroke 33 | ..color = Colors.green); 34 | } 35 | 36 | @override 37 | bool onTapDown(TapDownEvent event) { 38 | gameRef.gameController.send(this, GameControl.WEAPON_BUILDING); 39 | return false; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: "db7ef5bf9f59442b0e200a90587e8fa5e0c6336a" 8 | channel: "stable" 9 | 10 | project_type: app 11 | 12 | # Tracks metadata for the flutter migrate command 13 | migration: 14 | platforms: 15 | - platform: root 16 | create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a 17 | base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a 18 | - platform: linux 19 | create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a 20 | base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a 21 | - platform: macos 22 | create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a 23 | base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a 24 | - platform: windows 25 | create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a 26 | base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a 27 | 28 | # User provided section 29 | 30 | # List of Local paths (relative to this file) that should be 31 | # ignored by the migrate tool. 32 | # 33 | # Files that are not part of the templates will be ignored by default. 34 | unmanaged_files: 35 | - 'lib/main.dart' 36 | - 'ios/Runner.xcodeproj/project.pbxproj' 37 | -------------------------------------------------------------------------------- /lib/map/map_controller.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/extensions.dart'; 2 | import 'package:freedefense/astar/astarnode.dart'; 3 | import 'package:freedefense/map/astarmap_minxin.dart'; 4 | import 'package:freedefense/base/game_component.dart'; 5 | 6 | import 'map_tile_component.dart'; 7 | 8 | class MapController extends GameComponent with AstarMapMixin { 9 | late Vector2 tileSize; 10 | late Vector2 mapGrid; 11 | 12 | MapController({ 13 | required this.tileSize, 14 | required this.mapGrid, 15 | position, 16 | size, 17 | }) : super(position: position, size: size); 18 | 19 | @override 20 | Future onLoad() async { 21 | await super.onLoad(); 22 | 23 | for (var w = 0; w < mapGrid.x; w++) { 24 | for (var h = 0; h < mapGrid.y; h++) { 25 | this.add(MapTileComponent( 26 | position: Vector2(w * tileSize.x, h * tileSize.y) + 27 | (Vector2(tileSize.x / 2, tileSize.y / 2)), 28 | size: tileSize)); 29 | } 30 | } 31 | 32 | initBackground(); 33 | astarMapInit(mapGrid); 34 | } 35 | 36 | void initBackground() {} 37 | 38 | bool testBlock(Vector2 position) { 39 | astarMapAddObstacle(position); 40 | AstarNode? goal = astarMapResolve( 41 | gameRef.gameSetting.enemySpawn, gameRef.gameSetting.enemyTarget); 42 | astarMapRemoveObstacle(position); 43 | return goal == null ? true : false; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /lib/enemy/enemy_setting.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import 'package:flame/cache.dart'; 4 | import 'package:flame/sprite.dart'; 5 | 6 | import '../game/game_setting.dart'; 7 | 8 | class EnemySetting { 9 | late final double life; 10 | late final double speed; 11 | late final double scale; 12 | late final double enemySize; 13 | late final SpriteSheet spriteSheet; 14 | 15 | EnemySetting(); 16 | } 17 | 18 | class EnemySettingV1 { 19 | List enemy = []; 20 | 21 | EnemySettingV1(); 22 | 23 | final images = Images(); 24 | 25 | Future load() async { 26 | String enemyParamsString = await loadAsset('assets/enemyParams.json'); 27 | final enemyParams = json.decode(enemyParamsString); 28 | print("EnemySettingV1 enemyParams = ${enemyParams}"); 29 | 30 | for (var enemyParam in enemyParams) { 31 | print("EnemySettingV1 enemyParam = ${enemyParam}"); 32 | 33 | enemy.add(EnemySetting() 34 | ..life = enemyParam['life'].toDouble() 35 | ..speed = enemyParam['speed'].toDouble() 36 | ..scale = enemyParam['scale'].toDouble() 37 | ..spriteSheet = SpriteSheet.fromColumnsAndRows( 38 | image: await images.load('${enemyParam['image']}'), 39 | columns: enemyParam['columns'], 40 | rows: enemyParam['rows'], 41 | )); 42 | } 43 | 44 | print("EnemySettingV1 = ${enemy}"); 45 | print("EnemySettingV1 = ${enemy.length}"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /windows/runner/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "flutter_window.h" 6 | #include "utils.h" 7 | 8 | int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, 9 | _In_ wchar_t *command_line, _In_ int show_command) { 10 | // Attach to console when present (e.g., 'flutter run') or create a 11 | // new console when running with a debugger. 12 | if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { 13 | CreateAndAttachConsole(); 14 | } 15 | 16 | // Initialize COM, so that it is available for use in the library and/or 17 | // plugins. 18 | ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); 19 | 20 | flutter::DartProject project(L"data"); 21 | 22 | std::vector command_line_arguments = 23 | GetCommandLineArguments(); 24 | 25 | project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); 26 | 27 | FlutterWindow window(project); 28 | Win32Window::Point origin(10, 10); 29 | Win32Window::Size size(1280, 720); 30 | if (!window.Create(L"free_defense", origin, size)) { 31 | return EXIT_FAILURE; 32 | } 33 | window.SetQuitOnClose(true); 34 | 35 | ::MSG msg; 36 | while (::GetMessage(&msg, nullptr, 0, 0)) { 37 | ::TranslateMessage(&msg); 38 | ::DispatchMessage(&msg); 39 | } 40 | 41 | ::CoUninitialize(); 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # This file configures the analyzer, which statically analyzes Dart code to 2 | # check for errors, warnings, and lints. 3 | # 4 | # The issues identified by the analyzer are surfaced in the UI of Dart-enabled 5 | # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be 6 | # invoked from the command line by running `flutter analyze`. 7 | 8 | # The following line activates a set of recommended lints for Flutter apps, 9 | # packages, and plugins designed to encourage good coding practices. 10 | include: package:flutter_lints/flutter.yaml 11 | 12 | linter: 13 | # The lint rules applied to this project can be customized in the 14 | # section below to disable rules from the `package:flutter_lints/flutter.yaml` 15 | # included above or to enable additional rules. A list of all available lints 16 | # and their documentation is published at https://dart.dev/lints. 17 | # 18 | # Instead of disabling a lint rule for the entire project in the 19 | # section below, it can also be suppressed for a single line of code 20 | # or a specific dart file by using the `// ignore: name_of_lint` and 21 | # `// ignore_for_file: name_of_lint` syntax on the line or in the file 22 | # producing the lint. 23 | rules: 24 | # avoid_print: false # Uncomment to disable the `avoid_print` rule 25 | # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule 26 | 27 | # Additional information about this file can be found at 28 | # https://dart.dev/guides/language/analysis-options 29 | -------------------------------------------------------------------------------- /scripts/clean_windows_build.ps1: -------------------------------------------------------------------------------- 1 | # Clears stale Windows build artifacts that can cause CMake cache/source path mismatch errors. 2 | # Usage: From the project root, run: 3 | # powershell -ExecutionPolicy Bypass -File .\scripts\clean_windows_build.ps1 4 | 5 | $ErrorActionPreference = 'Stop' 6 | 7 | function Remove-IfExists { 8 | param( 9 | [Parameter(Mandatory=$true)][string]$Path 10 | ) 11 | if (Test-Path -LiteralPath $Path) { 12 | Write-Host "Removing: $Path" -ForegroundColor Yellow 13 | Remove-Item -LiteralPath $Path -Recurse -Force -ErrorAction SilentlyContinue 14 | } else { 15 | Write-Host "Not found (skip): $Path" -ForegroundColor DarkGray 16 | } 17 | } 18 | 19 | # Resolve repo root (script is located under scripts/) 20 | $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path 21 | $RepoRoot = Split-Path -Parent $ScriptDir 22 | Set-Location $RepoRoot 23 | 24 | # Paths to clean 25 | $paths = @( 26 | Join-Path $RepoRoot 'build\windows', 27 | Join-Path $RepoRoot 'build\win32', 28 | Join-Path $RepoRoot 'windows\flutter\ephemeral' 29 | ) 30 | 31 | Write-Host "Cleaning Windows build artifacts to fix CMake cache mismatches..." -ForegroundColor Cyan 32 | foreach ($p in $paths) { 33 | Remove-IfExists -Path $p 34 | } 35 | 36 | Write-Host "Cleanup complete. You can now regenerate build files, e.g.:" -ForegroundColor Green 37 | Write-Host " flutter clean" -ForegroundColor Green 38 | Write-Host " flutter pub get" -ForegroundColor Green 39 | Write-Host " flutter build windows" -ForegroundColor Green 40 | -------------------------------------------------------------------------------- /lib/base/game_component.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | import 'dart:ui'; 3 | 4 | import 'package:flame/components.dart'; 5 | import 'package:freedefense/base/game_ref.dart'; 6 | import 'package:freedefense/game/game_main.dart'; 7 | 8 | class GameComponent extends SpriteAnimationComponent with GameRef { 9 | Sprite? sprite; 10 | 11 | // set sprite(Sprite s) => this.sprite = s; 12 | 13 | GameComponent({ 14 | Vector2? position, 15 | Vector2? size, 16 | int? priority, 17 | }) : super(position: position, size: size, priority: priority, anchor: Anchor.center, removeOnFinish: true); 18 | 19 | bool active = true; 20 | get length => (size.x + size.y) / 2; 21 | get radius => length / 2; 22 | // loadedImage(imagePath) => 23 | // Sprite.fromImage(Flame.images.loadedFiles[imagePath].loadedImage); 24 | 25 | @override 26 | void render(Canvas canvas) { 27 | sprite?.render( 28 | canvas, 29 | size: size, 30 | overridePaint: paint, 31 | ); 32 | 33 | sprite?.render( 34 | canvas, 35 | size: size, 36 | overridePaint: paint, 37 | ); 38 | super.render(canvas); 39 | } 40 | 41 | double angleNearTo(Vector2 target) { 42 | double distance = position.distanceTo(target); 43 | if (distance == 0) return 0; 44 | double radians = acos((-target.y + position.y) / distance); 45 | if (target.x < position.x) { 46 | radians = pi * 2 - radians; 47 | } 48 | return radians; 49 | } 50 | 51 | Vector2 positionInParent(Vector2 point) { 52 | return point + position; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /lib/spacescape/models/player_data.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'player_data.dart'; 4 | 5 | // ************************************************************************** 6 | // TypeAdapterGenerator 7 | // ************************************************************************** 8 | 9 | class PlayerDataAdapter extends TypeAdapter { 10 | @override 11 | final int typeId = 0; 12 | 13 | @override 14 | PlayerData read(BinaryReader reader) { 15 | final numOfFields = reader.readByte(); 16 | final fields = { 17 | for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), 18 | }; 19 | return PlayerData( 20 | spaceshipType: fields[0] as SpaceshipType, 21 | ownedSpaceships: (fields[1] as List).cast(), 22 | money: fields[3] as int, 23 | ).._highScore = fields[2] as int; 24 | } 25 | 26 | @override 27 | void write(BinaryWriter writer, PlayerData obj) { 28 | writer 29 | ..writeByte(4) 30 | ..writeByte(0) 31 | ..write(obj.spaceshipType) 32 | ..writeByte(1) 33 | ..write(obj.ownedSpaceships) 34 | ..writeByte(2) 35 | ..write(obj._highScore) 36 | ..writeByte(3) 37 | ..write(obj.money); 38 | } 39 | 40 | @override 41 | int get hashCode => typeId.hashCode; 42 | 43 | @override 44 | bool operator ==(Object other) => 45 | identical(this, other) || 46 | other is PlayerDataAdapter && 47 | runtimeType == other.runtimeType && 48 | typeId == other.typeId; 49 | } 50 | -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "16x16", 5 | "idiom" : "mac", 6 | "filename" : "app_icon_16.png", 7 | "scale" : "1x" 8 | }, 9 | { 10 | "size" : "16x16", 11 | "idiom" : "mac", 12 | "filename" : "app_icon_32.png", 13 | "scale" : "2x" 14 | }, 15 | { 16 | "size" : "32x32", 17 | "idiom" : "mac", 18 | "filename" : "app_icon_32.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "32x32", 23 | "idiom" : "mac", 24 | "filename" : "app_icon_64.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "128x128", 29 | "idiom" : "mac", 30 | "filename" : "app_icon_128.png", 31 | "scale" : "1x" 32 | }, 33 | { 34 | "size" : "128x128", 35 | "idiom" : "mac", 36 | "filename" : "app_icon_256.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "256x256", 41 | "idiom" : "mac", 42 | "filename" : "app_icon_256.png", 43 | "scale" : "1x" 44 | }, 45 | { 46 | "size" : "256x256", 47 | "idiom" : "mac", 48 | "filename" : "app_icon_512.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "512x512", 53 | "idiom" : "mac", 54 | "filename" : "app_icon_512.png", 55 | "scale" : "1x" 56 | }, 57 | { 58 | "size" : "512x512", 59 | "idiom" : "mac", 60 | "filename" : "app_icon_1024.png", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /lib/weapon/bullet_component.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | 3 | import 'package:flame/components.dart'; 4 | import 'package:freedefense/base/game_component.dart'; 5 | import 'package:freedefense/base/movable.dart'; 6 | import 'package:freedefense/base/radar.dart'; 7 | import 'package:freedefense/enemy/enemy_component.dart'; 8 | 9 | class BulletComponent extends GameComponent with Movable, Radar { 10 | // double range = 0; 11 | Function? onExplosion; 12 | double damage = 0; 13 | BulletComponent({ 14 | required Vector2 position, 15 | required Vector2 size, 16 | }) : super(position: position, size: size, priority: 50); 17 | 18 | @override 19 | FutureOr? onLoad() { 20 | radarOn = true; 21 | radarRange = (size.x + size.y) / 4; 22 | radarScanAlert = onHitEnemy; 23 | radarScanNothing = null; 24 | radarCollisionDepth = 0.2; 25 | onMoveFinish = this.outOfRange; 26 | return super.onLoad(); 27 | } 28 | 29 | @override 30 | void update(double dt) { 31 | if (active) { 32 | updateMovable(dt); 33 | } 34 | super.update(dt); 35 | } 36 | 37 | void onHitEnemy(GameComponent enemy) { 38 | radarOn = false; 39 | (enemy as EnemyComponent).receiveDamage(damage); 40 | this.removeFromParent(); 41 | onExplosion?.call(enemy); 42 | } 43 | 44 | void outOfRange() { 45 | radarOn = false; 46 | this.removeFromParent(); 47 | } 48 | } 49 | 50 | class ExplosionComponent extends GameComponent { 51 | ExplosionComponent({ 52 | required Vector2 position, 53 | required Vector2 size, 54 | }) : super(position: position, size: size, priority: 55); 55 | } 56 | -------------------------------------------------------------------------------- /lib/map/astarmap_minxin.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:freedefense/astar/astarmap.dart'; 3 | import 'package:freedefense/astar/astarnode.dart'; 4 | 5 | mixin AstarMapMixin { 6 | late AstarMap astarMap; 7 | late Vector2 tileSize; 8 | 9 | void astarMapInit(Vector2 size) { 10 | astarMap = AstarMap(size.x.toInt(), size.y.toInt()); 11 | } 12 | 13 | void astarMapAddObstacle(Vector2 position) { 14 | AstarNode node = _positionToNode(position); 15 | astarMap.addObstacle(node.x, node.y); 16 | } 17 | 18 | void astarMapRemoveObstacle(Vector2 position) { 19 | AstarNode node = _positionToNode(position); 20 | astarMap.removeObstacle(node.x, node.y); 21 | } 22 | 23 | AstarNode? astarMapResolve(Vector2 start, Vector2 end) { 24 | AstarNode _start = _positionToNode(start); 25 | AstarNode _end = _positionToNode(end); 26 | AstarNode? goal = astarMap.astar(_start, _end); 27 | AstarNode? node = goal; 28 | if (goal == null) return null; 29 | 30 | while (node!.parent != null) { 31 | node.parent!.next = node; 32 | node = node.parent; 33 | } 34 | return node; 35 | } 36 | 37 | Vector2? astarMapResolveNextPosition(Vector2 start, Vector2 end) { 38 | AstarNode? node = astarMapResolve(start, end); 39 | return node != null ? nodeToPosition(node.next!) : null; 40 | } 41 | 42 | AstarNode _positionToNode(Vector2 position) { 43 | return AstarNode(position.x ~/ tileSize.x, position.y ~/ tileSize.y); 44 | } 45 | 46 | // leftTop position 47 | Vector2 nodeToPosition(AstarNode node) { 48 | return Vector2(node.x * tileSize.x, node.y * tileSize.y); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /lib/base/movable.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:freedefense/base/game_component.dart'; 3 | import 'dart:math'; 4 | 5 | mixin Movable on GameComponent { 6 | double speed = 0; 7 | Function? onMoveFinish; 8 | bool _finish = true; 9 | 10 | Vector2 _direction = Vector2.zero(); 11 | double _totalLength = 0; 12 | double _movedLength = 0; 13 | 14 | void moveTo(Vector2 to, [Function? onFinish]) { 15 | moveFromTo(position, to, onFinish); 16 | } 17 | 18 | void moveFromTo(Vector2 from, Vector2 to, [Function? onFinish]) { 19 | // Vector2 = from; 20 | double dx = to.x - from.x; 21 | double dy = to.y - from.y; 22 | double dl = sqrt(pow(dx, 2) + pow(dy, 2)); 23 | _totalLength = dl; 24 | _direction = Vector2(dx / dl, dy / dl); 25 | _movedLength = 0; 26 | _finish = false; 27 | onMoveFinish = onFinish; 28 | angle = angleNearTo(to); 29 | } 30 | 31 | void updateMovable(double t) { 32 | // super.update(t); 33 | if (!_finish) { 34 | /*finish on the next tick, to make sure the Vector2 is able to be sensored*/ 35 | if (_movedLength > _totalLength) { 36 | moveFinish(); 37 | } 38 | double _delta = t * speed; 39 | double dx = _delta * _direction.x; 40 | double dy = _delta * _direction.y; 41 | //overwirte Vector2 to make sure it update area. 42 | position = position + Vector2(dx, dy); 43 | //OPT: check only after time expire, to avoid pow cacl in very tick 44 | _movedLength += sqrt(pow(dx, 2) + pow(dy, 2)); 45 | } 46 | } 47 | 48 | void moveFinish() { 49 | _finish = true; 50 | onMoveFinish?.call(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /lib/spacescape/game/audio_player_component.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:flame/experimental.dart'; 3 | import 'package:flame_audio/flame_audio.dart'; 4 | import 'package:provider/provider.dart'; 5 | 6 | import 'game.dart'; 7 | 8 | import '../models/settings.dart'; 9 | 10 | class AudioPlayerComponent extends Component 11 | with HasGameReference { 12 | @override 13 | Future? onLoad() async { 14 | FlameAudio.bgm.initialize(); 15 | 16 | await FlameAudio.audioCache 17 | .loadAll(['laser1.ogg', 'powerUp6.ogg', 'laserSmall_001.ogg']); 18 | 19 | try { 20 | await FlameAudio.audioCache.load( 21 | '9. Space Invaders.wav', 22 | ); 23 | } catch (_) { 24 | // ignore: avoid_print 25 | print('Missing VOiD1 Gaming music pack: ' 26 | 'https://void1gaming.itch.io/free-synthwave-music-pack ' 27 | 'See assets/audio/README.md for more information.'); 28 | } 29 | 30 | return super.onLoad(); 31 | } 32 | 33 | void playBgm(String filename) { 34 | if (!FlameAudio.audioCache.loadedFiles.containsKey(filename)) return; 35 | 36 | if (game.buildContext != null) { 37 | if (Provider.of(game.buildContext!, listen: false) 38 | .backgroundMusic) { 39 | FlameAudio.bgm.play(filename); 40 | } 41 | } 42 | } 43 | 44 | void playSfx(String filename) { 45 | if (game.buildContext != null) { 46 | if (Provider.of(game.buildContext!, listen: false) 47 | .soundEffects) { 48 | FlameAudio.play(filename); 49 | } 50 | } 51 | } 52 | 53 | void stopBgm() { 54 | FlameAudio.bgm.stop(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /lib/enemy/enemy_v1.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'package:flame/components.dart'; 4 | import 'package:flame/sprite.dart'; 5 | import 'package:freedefense/game/game_setting.dart'; 6 | import 'package:freedefense/enemy/enemy_component.dart'; 7 | 8 | import 'enemy_setting.dart'; 9 | 10 | GameSetting setting = GameSetting(); 11 | 12 | class EnemyV1 extends EnemyComponent { 13 | late SpriteSheet spriteSheet; 14 | EnemyV1({required Vector2 position, required EnemyType type}) 15 | : super(position: position, size: Vector2.zero()) { 16 | enemyType = type; 17 | EnemySetting s = setting.enemies.enemy[enemyType.index]; 18 | maxLife = s.life; 19 | speed = s.speed; 20 | size = setting.enemySize * s.scale; 21 | spriteSheet = s.spriteSheet; 22 | } 23 | 24 | double initAngle = pi / 2; 25 | 26 | set angle(double a) { 27 | super.angle = a - initAngle; 28 | } 29 | 30 | @override 31 | Future? onLoad() { 32 | super.onLoad(); 33 | setLiveAnimation(); 34 | return null; 35 | } 36 | 37 | void onKilled() { 38 | setDeadAnimation(); 39 | super.onKilled(); 40 | } 41 | 42 | void setLiveAnimation() { 43 | List sprites = []; 44 | sprites.add(spriteSheet.getSprite(0, 0)); 45 | sprites.add(spriteSheet.getSprite(0, 1)); 46 | animation = SpriteAnimation.spriteList(sprites, stepTime: 0.4, loop: true); 47 | } 48 | 49 | void setDeadAnimation() { 50 | List sprites = []; 51 | sprites.add(spriteSheet.getSprite(0, 0)); 52 | sprites.add(spriteSheet.getSprite(1, 0)); 53 | sprites.add(spriteSheet.getSprite(2, 0)); 54 | animation = SpriteAnimation.spriteList(sprites, stepTime: 0.1, loop: false); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | log/ 12 | 13 | # IntelliJ related 14 | *.iml 15 | *.ipr 16 | *.iws 17 | .idea/ 18 | 19 | # Visual Studio Code related 20 | .vscode/ 21 | 22 | # Flutter/Dart/Pub related 23 | **/doc/api/ 24 | .dart_tool/ 25 | .flutter-plugins 26 | .packages 27 | .pub-cache/ 28 | .pub/ 29 | /build/ 30 | 31 | pubspec.lock 32 | android/ 33 | ios/ 34 | 35 | # Android related 36 | **/android/**/gradle-wrapper.jar 37 | **/android/.gradle 38 | **/android/captures/ 39 | **/android/gradlew 40 | **/android/gradlew.bat 41 | **/android/local.properties 42 | **/android/**/GeneratedPluginRegistrant.java 43 | 44 | # Web related 45 | **/web/** 46 | generated_plugin_registrant.dart 47 | 48 | # iOS/XCode related 49 | **/ios/**/*.mode1v3 50 | **/ios/**/*.mode2v3 51 | **/ios/**/*.moved-aside 52 | **/ios/**/*.pbxuser 53 | **/ios/**/*.perspectivev3 54 | **/ios/**/*sync/ 55 | **/ios/**/.sconsign.dblite 56 | **/ios/**/.tags* 57 | **/ios/**/.vagrant/ 58 | **/ios/**/DerivedData/ 59 | **/ios/**/Icon? 60 | **/ios/**/Pods/ 61 | **/ios/**/.symlinks/ 62 | **/ios/**/profile 63 | **/ios/**/xcuserdata 64 | **/ios/.generated/ 65 | **/ios/Flutter/App.framework 66 | **/ios/Flutter/Flutter.framework 67 | **/ios/Flutter/Generated.xcconfig 68 | **/ios/Flutter/app.flx 69 | **/ios/Flutter/app.zip 70 | **/ios/Flutter/flutter_assets/ 71 | **/ios/ServiceDefinitions.json 72 | **/ios/Runner/GeneratedPluginRegistrant.* 73 | 74 | # Exceptions to above rules. 75 | !**/ios/**/default.mode1v3 76 | !**/ios/**/default.mode2v3 77 | !**/ios/**/default.pbxuser 78 | !**/ios/**/default.perspectivev3 79 | !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages 80 | 81 | .flutter-plugins-dependencies 82 | -------------------------------------------------------------------------------- /lib/view/mine_view.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:freedefense/base/game_component.dart'; 4 | import 'package:freedefense/game/game_setting.dart'; 5 | 6 | class MineView extends GameComponent { 7 | late GameComponent icon; 8 | TextComponent? text; 9 | bool? maskGreen; 10 | 11 | MineView({required Vector2 position, required Vector2 size, TextStyle? style}) 12 | : super(position: position, size: size) { 13 | active = false; 14 | _style = style ?? const TextStyle(color: Colors.white70, fontSize: 15); 15 | } 16 | 17 | late TextStyle _style; 18 | 19 | int _n = 0; 20 | int get number => _n; 21 | set number(int n) { 22 | _n = n; 23 | text?.text = '$_n'; 24 | } 25 | 26 | @override 27 | Future? onLoad() async { 28 | await super.onLoad(); 29 | if (size.x > size.y) { 30 | icon = GameComponent(position: (size / 2)..x = size.x * (1 / 3), size: Vector2(size.y, size.x * (2 / 3))); 31 | text = TextComponent( 32 | position: (size / 2)..x = size.x * (5 / 6), textRenderer: TextPaint(style: _style), anchor: Anchor.center); 33 | } else { 34 | icon = GameComponent(position: (size / 2)..y = size.y * (1 / 3), size: Vector2(size.x, size.y * (2 / 3))); 35 | text = TextComponent( 36 | position: (size / 2)..y = size.y * (5 / 6), textRenderer: TextPaint(style: _style), anchor: Anchor.center); 37 | } 38 | 39 | icon.sprite = GameSetting().neutral.mine; 40 | number = 0; 41 | add(icon); 42 | add(text!); 43 | } 44 | 45 | @override 46 | void render(Canvas c) { 47 | if (maskGreen != null) { 48 | Color? color = maskGreen! ? Colors.green[200] : Colors.red[200]; 49 | c.drawRect(size.toRect(), Paint()..color = color!.withOpacity(0.3)); 50 | } 51 | super.render(c); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /lib/spacescape/screens/game_play.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/game.dart'; 2 | import 'package:flutter/material.dart'; 3 | 4 | import '../../links/combined_flame_game.dart'; 5 | import '../widgets/overlays/game_over_menu.dart'; 6 | import '../widgets/overlays/pause_button.dart'; 7 | import '../widgets/overlays/pause_menu.dart'; 8 | 9 | // Creating this as a file private object so as to 10 | // avoid unwanted rebuilds of the whole game object. 11 | CombinedFlameGame _spacescapeGame = CombinedFlameGame(); 12 | 13 | // This class represents the actual game screen 14 | // where all the action happens. 15 | class GamePlay extends StatelessWidget { 16 | const GamePlay({Key? key}) : super(key: key); 17 | 18 | @override 19 | Widget build(BuildContext context) { 20 | return Scaffold( 21 | // WillPopScope provides us a way to decide if 22 | // this widget should be poped or not when user 23 | // presses the back button. 24 | body: PopScope( 25 | canPop: false, 26 | // GameWidget is useful to inject the underlying 27 | // widget of any class extending from Flame's Game class. 28 | child: GameWidget( 29 | game: _spacescapeGame, 30 | // Initially only pause button overlay will be visible. 31 | initialActiveOverlays: const [PauseButton.id], 32 | overlayBuilderMap: { 33 | PauseButton.id: (BuildContext context, CombinedFlameGame game) => PauseButton( 34 | game: game, 35 | ), 36 | PauseMenu.id: (BuildContext context, CombinedFlameGame game) => PauseMenu( 37 | game: game, 38 | ), 39 | GameOverMenu.id: (BuildContext context, CombinedFlameGame game) => GameOverMenu( 40 | game: game, 41 | ), 42 | }, 43 | ), 44 | ), 45 | ); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /lib/spacescape/game/bullet.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/collisions.dart'; 2 | import 'package:flame/components.dart'; 3 | 4 | import 'enemy.dart'; 5 | 6 | // This component represent a bullet in game world. 7 | class Bullet extends SpriteComponent with CollisionCallbacks { 8 | // Speed of the bullet. 9 | final double _speed = 450; 10 | 11 | // Controls the direction in which bullet travels. 12 | Vector2 direction = Vector2(0, -1); 13 | 14 | // Level of this bullet. Essentially represents the 15 | // level of spaceship that fired this bullet. 16 | final int level; 17 | 18 | Bullet({ 19 | required Sprite? sprite, 20 | required Vector2? position, 21 | required Vector2? size, 22 | required this.level, 23 | }) : super(sprite: sprite, position: position, size: size); 24 | 25 | @override 26 | void onMount() { 27 | super.onMount(); 28 | 29 | // Adding a circular hitbox with radius as 0.4 times 30 | // the smallest dimension of this components size. 31 | final shape = CircleHitbox.relative( 32 | 0.4, 33 | parentSize: size, 34 | position: size / 2, 35 | anchor: Anchor.center, 36 | ); 37 | add(shape); 38 | } 39 | 40 | @override 41 | void onCollision(Set intersectionPoints, PositionComponent other) { 42 | super.onCollision(intersectionPoints, other); 43 | 44 | // If the other Collidable is Enemy, remove this bullet. 45 | if (other is Enemy) { 46 | removeFromParent(); 47 | } 48 | } 49 | 50 | @override 51 | void update(double dt) { 52 | super.update(dt); 53 | 54 | // Moves the bullet to a new position with _speed and direction. 55 | position += direction * _speed * dt; 56 | 57 | // If bullet crosses the upper boundary of screen 58 | // mark it to be removed it from the game world. 59 | if (position.y < 0) { 60 | removeFromParent(); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /lib/weapon/cannon.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'package:flame/components.dart'; 4 | import 'package:freedefense/base/game_component.dart'; 5 | import 'package:freedefense/weapon/bullet_component.dart'; 6 | import 'package:freedefense/weapon/weapon_component.dart'; 7 | import 'package:freedefense/weapon/weapon_setting.dart'; 8 | 9 | class Cannon extends WeaponComponent { 10 | Cannon({required Vector2 position, required WeaponSetting weaponSetting}) 11 | : super(position: position, weaponSetting: weaponSetting) { 12 | setting = weaponSetting; 13 | this.size = setting.size; 14 | this.weaponType = WeaponType.CANNON; 15 | this.range = setting.range; 16 | this.fireInterval = setting.fireInterval; 17 | this.sprite = setting.tower; 18 | this.barrel.sprite = setting.barrel[0]; 19 | this.barrel.size = size; 20 | this.barrel.rotateSpeed = setting.rotateSpeed; 21 | } 22 | 23 | @override 24 | void fireBullet(Vector2 target) { 25 | BulletComponent bullet = BulletComponent(position: _bulletPosition(), size: setting.bulletSize) 26 | ..angle = barrel.angle 27 | ..damage = setting.currentDamage 28 | ..sprite = setting.bullet 29 | ..speed = setting.currentBulletSpeed 30 | ..onExplosion = bulletExplosion; 31 | bullet.moveTo(target); 32 | parent?.add(bullet); 33 | } 34 | 35 | Vector2 _bulletPosition() { 36 | // double bulletR = (setting.bulletSize.x + setting.bulletSize.y) / 4; 37 | double r = radius /*+ bulletR*/; 38 | Vector2 localPosition = Vector2(r * sin(barrel.angle), -r * cos(barrel.angle)); 39 | localPosition += (size / 2); 40 | return positionOf(localPosition); 41 | } 42 | 43 | void bulletExplosion(GameComponent enemy) { 44 | enemy.add(ExplosionComponent(position: enemy.size / 2, size: setting.explosionSize) 45 | ..animation = SpriteAnimation.spriteList(setting.explosionSprites, stepTime: 0.06, loop: false)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /windows/runner/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | project(runner LANGUAGES CXX) 3 | 4 | # Define the application target. To change its name, change BINARY_NAME in the 5 | # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer 6 | # work. 7 | # 8 | # Any new source files that you add to the application should be added here. 9 | add_executable(${BINARY_NAME} WIN32 10 | "flutter_window.cpp" 11 | "main.cpp" 12 | "utils.cpp" 13 | "win32_window.cpp" 14 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 15 | "Runner.rc" 16 | "runner.exe.manifest" 17 | ) 18 | 19 | # Apply the standard set of build settings. This can be removed for applications 20 | # that need different build settings. 21 | apply_standard_settings(${BINARY_NAME}) 22 | 23 | # Add preprocessor definitions for the build version. 24 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") 25 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") 26 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") 27 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") 28 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") 29 | 30 | # Disable Windows macros that collide with C++ standard library functions. 31 | target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") 32 | 33 | # Add dependency libraries and include directories. Add any application-specific 34 | # dependencies here. 35 | target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) 36 | target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") 37 | target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") 38 | 39 | # Run the Flutter tool portions of the build. This must not be removed. 40 | add_dependencies(${BINARY_NAME} flutter_assemble) 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Powered by Flame](https://img.shields.io/badge/Powered%20by-%F0%9F%94%A5-orange.svg)](https://flame-engine.org) 2 | 3 | # FreeDefense V1 4 | 5 | FreeDefense Game with Flutter and Flame. 6 | 7 | 8 | 9 | ## DEMO: [Web version for V0] 10 | [Web version] http://freedefense.vquant.ml/ 11 | 12 | Controls: 13 | - Click: preview the weapon. (do not block the enemies!) 14 | - Click again: build weapon. 15 | - Click on weapon: update and destroy the weapon 16 | - Collect mine to build weapon 17 | 18 | ## TODO 19 | * [ ] Game 20 | - [ ] Toast to indicate wrong action 21 | - [ ] Game guide 22 | - [v] Collect coin and use coin to create cannon 23 | - [ ] Game Failure/Re-start 24 | * [ ] Weapons 25 | - [ ] Add more Weapon types 26 | - [v] Upgrade Weapon with more features. (faster bullet/better aiming/more damage) 27 | * [v] Enemies 28 | - [v] Add life indicator 29 | * [ ] Next version [TBD] 30 | - [ ] More topography 31 | - [ ] Medal system 32 | 33 | 34 | 35 | 36 | 37 | ## Troubleshooting: Windows CMake cache/source mismatch 38 | 39 | If you hit an error similar to: 40 | 41 | CMake Error: The current CMakeCache.txt directory F:/.../build/windows/x64/CMakeCache.txt is different than the directory C:/.../build/windows/x64 where CMakeCache.txt was created. This may result in binaries being created in the wrong place. 42 | 43 | This happens when the project is moved between different folders or drives and the previously generated CMake cache still points to the old path. To fix: 44 | 45 | - Run the cleanup script that removes stale Windows build artifacts: 46 | - PowerShell: powershell -ExecutionPolicy Bypass -File .\scripts\clean_windows_build.ps1 47 | - CMD: scripts\clean_windows_build.bat 48 | - Then regenerate build files: 49 | - flutter clean 50 | - flutter pub get 51 | - flutter build windows 52 | 53 | The script deletes build\windows, build\win32, and windows\flutter\ephemeral so CMake and Flutter regenerate fresh build files for the current path. 54 | -------------------------------------------------------------------------------- /windows/runner/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | void CreateAndAttachConsole() { 11 | if (::AllocConsole()) { 12 | FILE *unused; 13 | if (freopen_s(&unused, "CONOUT$", "w", stdout)) { 14 | _dup2(_fileno(stdout), 1); 15 | } 16 | if (freopen_s(&unused, "CONOUT$", "w", stderr)) { 17 | _dup2(_fileno(stdout), 2); 18 | } 19 | std::ios::sync_with_stdio(); 20 | FlutterDesktopResyncOutputStreams(); 21 | } 22 | } 23 | 24 | std::vector GetCommandLineArguments() { 25 | // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. 26 | int argc; 27 | wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); 28 | if (argv == nullptr) { 29 | return std::vector(); 30 | } 31 | 32 | std::vector command_line_arguments; 33 | 34 | // Skip the first argument as it's the binary name. 35 | for (int i = 1; i < argc; i++) { 36 | command_line_arguments.push_back(Utf8FromUtf16(argv[i])); 37 | } 38 | 39 | ::LocalFree(argv); 40 | 41 | return command_line_arguments; 42 | } 43 | 44 | std::string Utf8FromUtf16(const wchar_t* utf16_string) { 45 | if (utf16_string == nullptr) { 46 | return std::string(); 47 | } 48 | int target_length = ::WideCharToMultiByte( 49 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 50 | -1, nullptr, 0, nullptr, nullptr) 51 | -1; // remove the trailing null character 52 | int input_length = (int)wcslen(utf16_string); 53 | std::string utf8_string; 54 | if (target_length <= 0 || target_length > utf8_string.max_size()) { 55 | return utf8_string; 56 | } 57 | utf8_string.resize(target_length); 58 | int converted_length = ::WideCharToMultiByte( 59 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 60 | input_length, utf8_string.data(), target_length, nullptr, nullptr); 61 | if (converted_length == 0) { 62 | return std::string(); 63 | } 64 | return utf8_string; 65 | } 66 | -------------------------------------------------------------------------------- /lib/weapon/machine_gun.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'package:flame/components.dart'; 4 | import 'package:freedefense/base/game_component.dart'; 5 | import 'package:freedefense/game/game_setting.dart'; 6 | import 'package:freedefense/weapon/bullet_component.dart'; 7 | import 'package:freedefense/weapon/weapon_component.dart'; 8 | import 'package:freedefense/weapon/weapon_setting.dart'; 9 | 10 | class MachineGun extends WeaponComponent { 11 | MachineGun({ 12 | required Vector2 position, required WeaponSetting weaponSetting 13 | }) : super(position: position, weaponSetting: weaponSetting) { 14 | setting = 15 | GameSetting().weapons.weapon[WeaponType.MG.index]; 16 | this.size = setting.size; 17 | this.weaponType = WeaponType.MG; 18 | this.range = setting.range; 19 | this.fireInterval = setting.fireInterval; 20 | this.sprite = setting.tower; 21 | this.barrel.sprite = setting.barrel[0]; 22 | this.barrel.size = size; 23 | this.barrel.rotateSpeed = setting.rotateSpeed; 24 | } 25 | 26 | @override 27 | void fireBullet(Vector2 target) { 28 | BulletComponent bullet = 29 | BulletComponent(position: _bulletPosition(), size: setting.bulletSize) 30 | ..angle = barrel.angle 31 | ..damage = setting.damage 32 | ..sprite = setting.bullet 33 | ..speed = setting.bulletSpeed 34 | ..onExplosion = bulletExplosion; 35 | bullet.moveTo(target); 36 | parent?.add(bullet); 37 | } 38 | 39 | Vector2 _bulletPosition() { 40 | // double bulletR = (setting.bulletSize.x + setting.bulletSize.y) / 4; 41 | double r = radius /*+ bulletR*/; 42 | Vector2 localPosition = 43 | Vector2(r * sin(barrel.angle), -r * cos(barrel.angle)); 44 | localPosition += (size / 2); 45 | return positionOf(localPosition); 46 | } 47 | 48 | void bulletExplosion(GameComponent enemy) { 49 | enemy.add(ExplosionComponent( 50 | position: enemy.size / 2, size: setting.explosionSize) 51 | ..animation = SpriteAnimation.spriteList(setting.explosionSprites, 52 | stepTime: 0.06, loop: false)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /lib/weapon/missile.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'package:flame/components.dart'; 4 | import 'package:freedefense/base/game_component.dart'; 5 | import 'package:freedefense/game/game_setting.dart'; 6 | import 'package:freedefense/weapon/bullet_component.dart'; 7 | import 'package:freedefense/weapon/weapon_component.dart'; 8 | import 'package:freedefense/weapon/weapon_setting.dart'; 9 | 10 | class Missile extends WeaponComponent { 11 | 12 | Missile({ 13 | required Vector2 position, required WeaponSetting weaponSetting 14 | }) : super(position: position, weaponSetting: weaponSetting) { 15 | setting = 16 | GameSetting().weapons.weapon[WeaponType.MISSILE.index]; 17 | this.size = setting.size; 18 | this.weaponType = WeaponType.MISSILE; 19 | this.range = setting.range; 20 | this.fireInterval = setting.fireInterval; 21 | this.sprite = setting.tower; 22 | this.barrel.sprite = setting.barrel[0]; 23 | this.barrel.size = size; 24 | this.barrel.rotateSpeed = setting.rotateSpeed; 25 | } 26 | 27 | @override 28 | void fireBullet(Vector2 target) { 29 | BulletComponent bullet = 30 | BulletComponent(position: _bulletPosition(), size: setting.bulletSize) 31 | ..angle = barrel.angle 32 | ..damage = setting.damage 33 | ..sprite = setting.bullet 34 | ..speed = setting.bulletSpeed 35 | ..onExplosion = bulletExplosion; 36 | bullet.moveTo(target); 37 | parent?.add(bullet); 38 | } 39 | 40 | Vector2 _bulletPosition() { 41 | // double bulletR = (setting.bulletSize.x + setting.bulletSize.y) / 4; 42 | double r = radius /*+ bulletR*/; 43 | Vector2 localPosition = 44 | Vector2(r * sin(barrel.angle), -r * cos(barrel.angle)); 45 | localPosition += (size / 2); 46 | return positionOf(localPosition); 47 | } 48 | 49 | void bulletExplosion(GameComponent enemy) { 50 | enemy.add(ExplosionComponent( 51 | position: enemy.size / 2, size: setting.explosionSize) 52 | ..animation = SpriteAnimation.spriteList(setting.explosionSprites, 53 | stepTime: 0.06, loop: false)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /lib/spacescape/models/spaceship_details.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'spaceship_details.dart'; 4 | 5 | // ************************************************************************** 6 | // TypeAdapterGenerator 7 | // ************************************************************************** 8 | 9 | class SpaceshipTypeAdapter extends TypeAdapter { 10 | @override 11 | final int typeId = 1; 12 | 13 | @override 14 | SpaceshipType read(BinaryReader reader) { 15 | switch (reader.readByte()) { 16 | case 0: 17 | return SpaceshipType.canary; 18 | case 1: 19 | return SpaceshipType.dusky; 20 | case 2: 21 | return SpaceshipType.condor; 22 | case 3: 23 | return SpaceshipType.cXC; 24 | case 4: 25 | return SpaceshipType.raptor; 26 | case 5: 27 | return SpaceshipType.raptorX; 28 | case 6: 29 | return SpaceshipType.albatross; 30 | case 7: 31 | return SpaceshipType.dK809; 32 | default: 33 | return SpaceshipType.canary; 34 | } 35 | } 36 | 37 | @override 38 | void write(BinaryWriter writer, SpaceshipType obj) { 39 | switch (obj) { 40 | case SpaceshipType.canary: 41 | writer.writeByte(0); 42 | break; 43 | case SpaceshipType.dusky: 44 | writer.writeByte(1); 45 | break; 46 | case SpaceshipType.condor: 47 | writer.writeByte(2); 48 | break; 49 | case SpaceshipType.cXC: 50 | writer.writeByte(3); 51 | break; 52 | case SpaceshipType.raptor: 53 | writer.writeByte(4); 54 | break; 55 | case SpaceshipType.raptorX: 56 | writer.writeByte(5); 57 | break; 58 | case SpaceshipType.albatross: 59 | writer.writeByte(6); 60 | break; 61 | case SpaceshipType.dK809: 62 | writer.writeByte(7); 63 | break; 64 | } 65 | } 66 | 67 | @override 68 | int get hashCode => typeId.hashCode; 69 | 70 | @override 71 | bool operator ==(Object other) => 72 | identical(this, other) || 73 | other is SpaceshipTypeAdapter && 74 | runtimeType == other.runtimeType && 75 | typeId == other.typeId; 76 | } 77 | -------------------------------------------------------------------------------- /lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/flame.dart'; 2 | import 'package:flame/game.dart'; 3 | import 'package:flutter/material.dart'; 4 | import 'package:flutter/services.dart'; 5 | import 'package:freedefense/game/game_main.dart'; 6 | 7 | // import 'package:freedefense/game/game_main.dart'; 8 | import 'package:freedefense/game/game_test.dart'; 9 | import 'package:freedefense/view/weaponview_widget.dart'; 10 | 11 | void main() async { 12 | WidgetsFlutterBinding.ensureInitialized(); 13 | 14 | await Flame.device.fullScreen(); 15 | await Flame.device.setOrientation(DeviceOrientation.portraitUp); 16 | 17 | GameTest game = GameTest(); 18 | 19 | runApp( 20 | GameWidget( 21 | game: game, 22 | overlayBuilderMap: { 23 | "${WeaponViewWidget.name}-0": WeaponViewWidget.builder, 24 | "${WeaponViewWidget.name}-1": WeaponViewWidget.builder, 25 | 'start': _pauseMenuBuilder, 26 | 'gameover': _gameOverBuilder, 27 | }, 28 | initialActiveOverlays: const ['start'], 29 | ), 30 | ); 31 | } 32 | 33 | Widget _pauseMenuBuilder(BuildContext buildContext, GameMain game) { 34 | return Center( 35 | child: Container( 36 | width: 100, 37 | height: 100, 38 | color: Colors.orange, 39 | child: Center( 40 | child: TextButton( 41 | style: TextButton.styleFrom( 42 | foregroundColor: Colors.white, padding: const EdgeInsets.all(16.0), 43 | textStyle: const TextStyle(fontSize: 20), 44 | ), 45 | onPressed: () { 46 | game.start(); 47 | game.overlays.remove('start'); 48 | }, 49 | child: const Text('Start'), 50 | )), 51 | )); 52 | } 53 | 54 | Widget _gameOverBuilder(BuildContext buildContext, GameMain game) { 55 | return Center( 56 | child: Container( 57 | width: 100, 58 | height: 100, 59 | color: Colors.red, 60 | child: Center( 61 | child: TextButton( 62 | style: TextButton.styleFrom( 63 | foregroundColor: Colors.white, padding: const EdgeInsets.all(16.0), 64 | textStyle: const TextStyle(fontSize: 20), 65 | ), 66 | onPressed: () { 67 | game.overlays.remove('gameover'); 68 | }, 69 | child: const Text('Game Over'), 70 | )), 71 | )); 72 | } 73 | 74 | void test() {} 75 | -------------------------------------------------------------------------------- /lib/base/radar.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:freedefense/base/game_component.dart'; 3 | 4 | mixin Radar on GameComponent { 5 | bool _radarOn = false; 6 | bool radarScanBest = false; 7 | double radarRange = 0; 8 | double radarCollisionDepth = 0.1; 9 | void Function(GameComponent)? radarScanAlert; 10 | void Function()? radarScanNothing; 11 | 12 | set radarOn(bool e) { 13 | _radarOn = e; 14 | } 15 | 16 | bool get radarOn => _radarOn; 17 | 18 | void radarScan(Iterable targets) { 19 | if (radarOn) { 20 | _bestDistance = 100000; 21 | Iterable _targets = targets 22 | .where((e) => ((e is T) && ((e as GameComponent).active))) 23 | .cast(); 24 | _targets 25 | .takeWhile((value) => _collisionTest(value as GameComponent)) 26 | .forEach((element) {}); 27 | 28 | if (_bestTarget != null) { 29 | radarScanAlert?.call(_bestTarget!); 30 | _bestTarget = null; 31 | } else { 32 | radarScanNothing?.call(); 33 | } 34 | } 35 | } 36 | 37 | double _bestDistance = 100000; 38 | GameComponent? _bestTarget; 39 | 40 | bool _collisionTest(GameComponent target) { 41 | Vector2 targetPosition = target.position; 42 | double targetCollisionSize = (target.size.x + target.size.y) / 4; 43 | double collisionRange = (targetCollisionSize + radarRange); 44 | collisionRange = collisionRange * (1 - radarCollisionDepth); 45 | double distance = position.distanceTo(targetPosition); 46 | if (distance < collisionRange) { 47 | if (radarScanBest) { 48 | if (distance < _bestDistance) { 49 | _bestDistance = distance; 50 | _bestTarget = target; 51 | } 52 | return true; 53 | } else { 54 | _bestTarget = target; 55 | return false; 56 | } 57 | } 58 | return true; 59 | } 60 | 61 | bool collision(GameComponent target) { 62 | Vector2 targetPosition = target.position; 63 | double targetCollisionSize = (target.size.x + target.size.y) / 4; 64 | double collisionRange = (targetCollisionSize + radarRange); 65 | collisionRange = collisionRange * (1 - radarCollisionDepth); 66 | double distance = position.distanceTo(targetPosition); 67 | if (distance < collisionRange) { 68 | return true; 69 | } 70 | return false; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /windows/runner/flutter_window.cpp: -------------------------------------------------------------------------------- 1 | #include "flutter_window.h" 2 | 3 | #include 4 | 5 | #include "flutter/generated_plugin_registrant.h" 6 | 7 | FlutterWindow::FlutterWindow(const flutter::DartProject& project) 8 | : project_(project) {} 9 | 10 | FlutterWindow::~FlutterWindow() {} 11 | 12 | bool FlutterWindow::OnCreate() { 13 | if (!Win32Window::OnCreate()) { 14 | return false; 15 | } 16 | 17 | RECT frame = GetClientArea(); 18 | 19 | // The size here must match the window dimensions to avoid unnecessary surface 20 | // creation / destruction in the startup path. 21 | flutter_controller_ = std::make_unique( 22 | frame.right - frame.left, frame.bottom - frame.top, project_); 23 | // Ensure that basic setup of the controller was successful. 24 | if (!flutter_controller_->engine() || !flutter_controller_->view()) { 25 | return false; 26 | } 27 | RegisterPlugins(flutter_controller_->engine()); 28 | SetChildContent(flutter_controller_->view()->GetNativeWindow()); 29 | 30 | flutter_controller_->engine()->SetNextFrameCallback([&]() { 31 | this->Show(); 32 | }); 33 | 34 | // Flutter can complete the first frame before the "show window" callback is 35 | // registered. The following call ensures a frame is pending to ensure the 36 | // window is shown. It is a no-op if the first frame hasn't completed yet. 37 | flutter_controller_->ForceRedraw(); 38 | 39 | return true; 40 | } 41 | 42 | void FlutterWindow::OnDestroy() { 43 | if (flutter_controller_) { 44 | flutter_controller_ = nullptr; 45 | } 46 | 47 | Win32Window::OnDestroy(); 48 | } 49 | 50 | LRESULT 51 | FlutterWindow::MessageHandler(HWND hwnd, UINT const message, 52 | WPARAM const wparam, 53 | LPARAM const lparam) noexcept { 54 | // Give Flutter, including plugins, an opportunity to handle window messages. 55 | if (flutter_controller_) { 56 | std::optional result = 57 | flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, 58 | lparam); 59 | if (result) { 60 | return *result; 61 | } 62 | } 63 | 64 | switch (message) { 65 | case WM_FONTCHANGE: 66 | flutter_controller_->engine()->ReloadSystemFonts(); 67 | break; 68 | } 69 | 70 | return Win32Window::MessageHandler(hwnd, message, wparam, lparam); 71 | } 72 | -------------------------------------------------------------------------------- /lib/spacescape/widgets/overlays/game_over_menu.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | import '../../../links/combined_flame_game.dart'; 4 | import '../../screens/main_menu.dart'; 5 | import 'pause_button.dart'; 6 | 7 | // This class represents the game over menu overlay. 8 | class GameOverMenu extends StatelessWidget { 9 | static const String id = 'GameOverMenu'; 10 | final CombinedFlameGame game; 11 | 12 | const GameOverMenu({Key? key, required this.game}) : super(key: key); 13 | 14 | @override 15 | Widget build(BuildContext context) { 16 | return Center( 17 | child: Column( 18 | mainAxisAlignment: MainAxisAlignment.center, 19 | children: [ 20 | // Pause menu title. 21 | const Padding( 22 | padding: EdgeInsets.symmetric(vertical: 50.0), 23 | child: Text( 24 | 'Game Over', 25 | style: TextStyle( 26 | fontSize: 50.0, 27 | color: Colors.black, 28 | shadows: [ 29 | Shadow( 30 | blurRadius: 20.0, 31 | color: Colors.white, 32 | offset: Offset(0, 0), 33 | ) 34 | ], 35 | ), 36 | ), 37 | ), 38 | 39 | // Restart button. 40 | SizedBox( 41 | width: MediaQuery.of(context).size.width / 3, 42 | child: ElevatedButton( 43 | onPressed: () { 44 | game.overlays.remove(GameOverMenu.id); 45 | game.overlays.add(PauseButton.id); 46 | game.reset(); 47 | game.resumeEngine(); 48 | }, 49 | child: const Text('Restart'), 50 | ), 51 | ), 52 | 53 | // Exit button. 54 | SizedBox( 55 | width: MediaQuery.of(context).size.width / 3, 56 | child: ElevatedButton( 57 | onPressed: () { 58 | game.overlays.remove(GameOverMenu.id); 59 | game.reset(); 60 | game.resumeEngine(); 61 | 62 | Navigator.of(context).pushReplacement( 63 | MaterialPageRoute( 64 | builder: (context) => const MainMenu(), 65 | ), 66 | ); 67 | }, 68 | child: const Text('Exit'), 69 | ), 70 | ), 71 | ], 72 | ), 73 | ); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /assets/weaponParams.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "label": "CANNON", 4 | "cost": 10, 5 | "range": 1.5, 6 | "damage": 15.0, 7 | "fireInterval": 0.8, 8 | "rotateSpeed": 2, 9 | "bulletSpeed": 2, 10 | "sizeX": 0.8, 11 | "sizeY": 0.8, 12 | "bulletSizeX": 0.1, 13 | "bulletSizeY": 0.2, 14 | "explosionSizeX": 0.8, 15 | "explosionSizeY": 0.8, 16 | "barrelImg0": "Cannon", 17 | "barrelImg1": "Cannon2", 18 | "barrelImg2": "Cannon3", 19 | "bulletImg": "Bullet1", 20 | "damageDelta": 1.0, 21 | "rangeDelta": 1.25, 22 | "fireIntervalDelta": 2.0, 23 | "rotateSpeedDelta": 1.25, 24 | "bulletSpeedDelta": 1.0, 25 | "explosionImage": "weapon/explosion1.png", 26 | "columns": 8, 27 | "rows": 8, 28 | "explosionTimeStep": 1.5, 29 | "expFrame" : [[0.0,4.0], [1.0,4.0], [2.0,4.0], [3.0,4.0], [4.0,4.0], [5.0,4.0], [6.0,4.0], [7.0,4.0]] 30 | }, 31 | { 32 | "label": "MG", 33 | "cost": 15, 34 | "range": 2, 35 | "damage": 5.0, 36 | "fireInterval": 0.2, 37 | "rotateSpeed": 4, 38 | "bulletSpeed": 5, 39 | "sizeX": 0.8, 40 | "sizeY": 0.8, 41 | "bulletSizeX": 0.1, 42 | "bulletSizeY": 0.3, 43 | "explosionSizeX": 0.5, 44 | "explosionSizeY": 0.5, 45 | "barrelImg0": "MG", 46 | "barrelImg1": "MG2", 47 | "barrelImg2": "MG3", 48 | "bulletImg": "Bullet2", 49 | "damageDelta": 2.0, 50 | "rangeDelta": 1.25, 51 | "fireIntervalDelta": 1.5, 52 | "rotateSpeedDelta": 1.25, 53 | "bulletSpeedDelta": 1.0, 54 | "explosionImage": "weapon/explosion2.png", 55 | "columns": 6, 56 | "rows": 1, 57 | "explosionTimeStep": 0.05, 58 | "expFrame" : [[0.0,0.0], [0.0,1.0], [0.0,2.0], [0.0,3.0], [0.0,4.0], [0.0,5.0]] 59 | }, 60 | { 61 | "label": "MISSILE", 62 | "cost": 30, 63 | "range": 3, 64 | "damage": 30.0, 65 | "fireInterval": 1.5, 66 | "rotateSpeed": 1, 67 | "bulletSpeed": 0.7, 68 | "sizeX": 0.9, 69 | "sizeY": 0.9, 70 | "bulletSizeX": 0.3, 71 | "bulletSizeY": 0.4, 72 | "explosionSizeX": 0.7, 73 | "explosionSizeY": 0.7, 74 | "barrelImg0": "Missile_Launcher", 75 | "barrelImg1": "Missile_Launcher2", 76 | "barrelImg2": "Missile_Launcher3", 77 | "bulletImg": "Missile", 78 | "damageDelta": 1.0, 79 | "rangeDelta": 1.5, 80 | "fireIntervalDelta": 2.0, 81 | "rotateSpeedDelta": 1.5, 82 | "bulletSpeedDelta": 2.0, 83 | "explosionImage": "weapon/explosion3.png", 84 | "columns": 5, 85 | "rows": 3, 86 | "explosionTimeStep": 0.1, 87 | "expFrame" : [[0.0,0.0], [0.5,3.0], [1.0,0.0], [1.5,3.0], [2.0,0.0], [2.5,3.0]] 88 | } 89 | ] -------------------------------------------------------------------------------- /lib/spacescape/screens/main_menu.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:freedefense/spacescape/screens/select_spaceship.dart'; 3 | import 'package:freedefense/spacescape/screens/settings_menu.dart'; 4 | 5 | // Represents the main menu screen of FreeDefence (from SpaceScapes), allowing 6 | // players to start the game or modify in-game settings. 7 | class MainMenu extends StatelessWidget { 8 | const MainMenu({Key? key}) : super(key: key); 9 | 10 | @override 11 | Widget build(BuildContext context) { 12 | return Scaffold( 13 | body: Center( 14 | child: Column( 15 | mainAxisAlignment: MainAxisAlignment.center, 16 | children: [ 17 | // Game title. 18 | const Padding( 19 | padding: EdgeInsets.symmetric(vertical: 50.0), 20 | child: Text( 21 | 'FreeDefense', 22 | style: TextStyle( 23 | fontSize: 50.0, 24 | color: Colors.black, 25 | shadows: [ 26 | Shadow( 27 | blurRadius: 20.0, 28 | color: Colors.white, 29 | offset: Offset(0, 0), 30 | ) 31 | ], 32 | ), 33 | ), 34 | ), 35 | 36 | // Play button. 37 | SizedBox( 38 | width: MediaQuery.of(context).size.width / 3, 39 | child: ElevatedButton( 40 | onPressed: () { 41 | // Push and replace current screen (i.e MainMenu) with 42 | // SelectSpaceship(), so that player can select a spaceship. 43 | Navigator.of(context).pushReplacement( 44 | MaterialPageRoute( 45 | builder: (context) => const SelectSpaceship(), 46 | ), 47 | ); 48 | }, 49 | child: const Text('PLAY HERE'), 50 | ), 51 | ), 52 | 53 | // Settings button. 54 | SizedBox( 55 | width: MediaQuery.of(context).size.width / 3, 56 | child: ElevatedButton( 57 | onPressed: () { 58 | Navigator.of(context).push( 59 | MaterialPageRoute( 60 | builder: (context) => const SettingsMenu(), 61 | ), 62 | ); 63 | }, 64 | child: const Text('Settings HERE'), 65 | ), 66 | ), 67 | ], 68 | ), 69 | ), 70 | ); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /lib/spacescape/screens/settings_menu.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:provider/provider.dart'; 3 | 4 | import '../models/settings.dart'; 5 | 6 | // This class represents the settings menu. 7 | class SettingsMenu extends StatelessWidget { 8 | const SettingsMenu({Key? key}) : super(key: key); 9 | 10 | @override 11 | Widget build(BuildContext context) { 12 | return Scaffold( 13 | body: Center( 14 | child: Column( 15 | mainAxisAlignment: MainAxisAlignment.center, 16 | children: [ 17 | // Game title. 18 | const Padding( 19 | padding: EdgeInsets.symmetric(vertical: 50.0), 20 | child: Text( 21 | 'Settings', 22 | style: TextStyle( 23 | fontSize: 50.0, 24 | color: Colors.black, 25 | shadows: [ 26 | Shadow( 27 | blurRadius: 20.0, 28 | color: Colors.white, 29 | offset: Offset(0, 0), 30 | ) 31 | ], 32 | ), 33 | ), 34 | ), 35 | 36 | // Switch for sound effects. 37 | Selector( 38 | selector: (context, settings) => settings.soundEffects, 39 | builder: (context, value, child) { 40 | return SwitchListTile( 41 | title: const Text('Sound Effects'), 42 | value: value, 43 | onChanged: (newValue) { 44 | Provider.of(context, listen: false).soundEffects = newValue; 45 | }, 46 | ); 47 | }, 48 | ), 49 | 50 | // Switch for background music. 51 | Selector( 52 | selector: (context, settings) => settings.backgroundMusic, 53 | builder: (context, value, child) { 54 | return SwitchListTile( 55 | title: const Text('Background Music'), 56 | value: value, 57 | onChanged: (newValue) { 58 | Provider.of(context, listen: false).backgroundMusic = newValue; 59 | }, 60 | ); 61 | }, 62 | ), 63 | 64 | // Back button. 65 | SizedBox( 66 | width: MediaQuery.of(context).size.width / 4, 67 | child: ElevatedButton( 68 | onPressed: () { 69 | Navigator.of(context).pop(); 70 | }, 71 | child: const Icon(Icons.arrow_back), 72 | ), 73 | ), 74 | ], 75 | ), 76 | ), 77 | ); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /lib/view/gamebar_view.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | 3 | import 'package:flame/components.dart'; 4 | import 'package:flutter/material.dart'; 5 | import 'package:freedefense/base/game_component.dart'; 6 | import 'package:freedefense/game/game_controller.dart'; 7 | import 'package:freedefense/game/game_setting.dart'; 8 | import 'package:freedefense/view/mine_view.dart'; 9 | 10 | GameSetting setting = GameSetting(); 11 | 12 | class GamebarView extends GameComponent { 13 | GamebarView() : super(position: setting.barPosition, size: setting.barSize) { 14 | active = false; 15 | } 16 | late TextComponent startIndicator; 17 | 18 | late TextComponent missedStatus; 19 | late TextComponent killedStatus; 20 | late TextComponent waveStatus; 21 | 22 | late MineView mine; 23 | 24 | int _wave = 0; 25 | int _killedEnemy = 0; 26 | int _missedEnemy = 0; 27 | int _mineCollected = 0; 28 | int _lives = 20; 29 | 30 | @override 31 | FutureOr? onLoad() { 32 | waveStatus = TextComponent( 33 | textRenderer: TextPaint( 34 | style: const TextStyle(color: Colors.white70, fontSize: 22)), 35 | position: (size / 2), 36 | anchor: Anchor.center, 37 | ); 38 | add(waveStatus); 39 | 40 | missedStatus = TextComponent( 41 | textRenderer: TextPaint( 42 | style: const TextStyle(color: Colors.white70, fontSize: 12)), 43 | position: (size / 2)..x = (size.x * (1 / 8)), 44 | anchor: Anchor.center, 45 | ); 46 | add(missedStatus); 47 | 48 | killedStatus = TextComponent( 49 | textRenderer: TextPaint( 50 | style: const TextStyle(color: Colors.white70, fontSize: 12)), 51 | position: (size / 2)..x = (size.x * (3 / 8)), 52 | anchor: Anchor.center, 53 | ); 54 | add(killedStatus); 55 | 56 | mine = MineView( 57 | position: (size / 2)..x = (size.x * (6 / 8)), 58 | size: Vector2(size.y * 1.5, size.y) * 0.7, 59 | style: const TextStyle(color: Colors.white70, fontSize: 12)); 60 | add(mine); 61 | 62 | return super.onLoad(); 63 | } 64 | 65 | int get wave => _wave; 66 | set wave(n) { 67 | _wave = n; 68 | waveStatus.text = 'Wave: $_wave'; 69 | } 70 | 71 | int get killedEnemy => _killedEnemy; 72 | set killedEnemy(int n) { 73 | _killedEnemy = n; 74 | killedStatus.text = 'Killed: $_killedEnemy'; 75 | } 76 | 77 | int get missedEnemy => _missedEnemy; 78 | set missedEnemy(int n) { 79 | _missedEnemy = n; 80 | missedStatus.text = 'Lives: ${_lives - _missedEnemy}'; 81 | if (_lives - _missedEnemy <= 0) { 82 | gameRef.gameController.send(this, GameControl.GAME_OVER); 83 | } 84 | } 85 | 86 | int get mineCollected => _mineCollected; 87 | set mineCollected(int n) { 88 | _mineCollected = n; 89 | mine.number = _mineCollected; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /lib/spacescape/widgets/overlays/pause_menu.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | import '../../../links/combined_flame_game.dart'; 4 | import '../../screens/main_menu.dart'; 5 | import 'pause_button.dart'; 6 | 7 | // This class represents the pause menu overlay. 8 | class PauseMenu extends StatelessWidget { 9 | static const String id = 'PauseMenu'; 10 | final CombinedFlameGame game; 11 | 12 | const PauseMenu({Key? key, required this.game}) : super(key: key); 13 | 14 | @override 15 | Widget build(BuildContext context) { 16 | return Center( 17 | child: Column( 18 | mainAxisAlignment: MainAxisAlignment.center, 19 | children: [ 20 | // Pause menu title. 21 | const Padding( 22 | padding: EdgeInsets.symmetric(vertical: 50.0), 23 | child: Text( 24 | 'Paused', 25 | style: TextStyle( 26 | fontSize: 50.0, 27 | color: Colors.black, 28 | shadows: [ 29 | Shadow( 30 | blurRadius: 20.0, 31 | color: Colors.white, 32 | offset: Offset(0, 0), 33 | ) 34 | ], 35 | ), 36 | ), 37 | ), 38 | 39 | // Resume button. 40 | SizedBox( 41 | width: MediaQuery.of(context).size.width / 3, 42 | child: ElevatedButton( 43 | onPressed: () { 44 | game.resumeEngine(); 45 | game.overlays.remove(PauseMenu.id); 46 | game.overlays.add(PauseButton.id); 47 | }, 48 | child: const Text('Resume'), 49 | ), 50 | ), 51 | 52 | // Restart button. 53 | SizedBox( 54 | width: MediaQuery.of(context).size.width / 3, 55 | child: ElevatedButton( 56 | onPressed: () { 57 | game.overlays.remove(PauseMenu.id); 58 | game.overlays.add(PauseButton.id); 59 | game.reset(); 60 | game.resumeEngine(); 61 | }, 62 | child: const Text('Restart'), 63 | ), 64 | ), 65 | 66 | // Exit button. 67 | SizedBox( 68 | width: MediaQuery.of(context).size.width / 3, 69 | child: ElevatedButton( 70 | onPressed: () { 71 | game.overlays.remove(PauseMenu.id); 72 | game.reset(); 73 | game.resumeEngine(); 74 | 75 | Navigator.of(context).pushReplacement( 76 | MaterialPageRoute( 77 | builder: (context) => const MainMenu(), 78 | ), 79 | ); 80 | }, 81 | child: const Text('Exit'), 82 | ), 83 | ), 84 | ], 85 | ), 86 | ); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /lib/game/game_main.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/events.dart'; 2 | import 'package:flame/game.dart'; 3 | import 'package:freedefense/base/game_component.dart'; 4 | import 'package:freedefense/game/game_controller.dart'; 5 | import 'package:freedefense/game/game_setting.dart'; 6 | import 'package:freedefense/map/map_controller.dart'; 7 | import 'package:freedefense/view/gamebar_view.dart'; 8 | import 'package:freedefense/view/weapon_factory_view.dart'; 9 | 10 | class GameMain extends FlameGame with TapCallbacks { 11 | late MapController mapController; 12 | late WeaponFactoryView weaponFactory; 13 | late GameController gameController; 14 | late GamebarView gamebarView; 15 | bool started = false; 16 | 17 | bool loadDone = false; 18 | 19 | // GameView view = GameView(); 20 | GameSetting gameSetting = GameSetting(); 21 | // GameController controller = GameController(); 22 | // EnemySpawner enemySpawner = EnemySpawner(); 23 | // StatusBar statusBar; 24 | // GameUtil util; 25 | 26 | GameMain(); 27 | 28 | @override 29 | void onGameResize(Vector2 size) { 30 | if (!loadDone) setting.setScreenSize(size); 31 | super.onGameResize(size); 32 | } 33 | 34 | int currentTimeMillis() { 35 | return new DateTime.now().millisecondsSinceEpoch; 36 | } 37 | 38 | @override 39 | Future onLoad() async { 40 | int timeRecord = currentTimeMillis(); 41 | await super.onLoad(); 42 | 43 | // await setting.onLoad(); 44 | await setting.neutral.load(); 45 | 46 | mapController = MapController( 47 | tileSize: setting.mapTileSize, mapGrid: setting.mapGrid, position: setting.mapPosition, size: setting.mapSize); 48 | /*game controller should have same range as map */ 49 | gameController = GameController(position: setting.mapPosition, size: setting.mapSize); 50 | 51 | gamebarView = GamebarView(); 52 | weaponFactory = WeaponFactoryView(); 53 | 54 | await setting.weapons.load(gameSetting); 55 | 56 | add(mapController); 57 | add(gameController); 58 | add(gamebarView); 59 | add(weaponFactory); 60 | 61 | setting.enemies.load(); 62 | 63 | loadDone = true; 64 | int d = currentTimeMillis() - timeRecord; 65 | print("GameMain onLoad done takke $d"); 66 | } 67 | 68 | @override 69 | void update(double t) { 70 | super.update(t); 71 | // if (recordFps()) { 72 | // double _fps = fps(); 73 | // int len = components.length; 74 | // print('GameMain FPS $_fps, components $len'); 75 | // } 76 | // Iterable test = components 77 | // .where((o) => o is! MapTileComponent) 78 | // .where((o) => o is! 0x7d2b523304a0) (first time) 79 | // print(test.length); 80 | } 81 | 82 | void start() { 83 | if (loadDone) { 84 | gameController.send(GameComponent(), GameControl.ENEMY_SPAWN); 85 | gamebarView.killedEnemy = 0; 86 | gamebarView.mineCollected = 999; 87 | gamebarView.missedEnemy = 0; 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /lib/game/game_setting.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math' as math; 2 | 3 | import 'package:flame/components.dart'; 4 | import 'package:flutter/services.dart'; 5 | 6 | import '../enemy/enemy_setting.dart'; 7 | import '../neutral/neutral_setting.dart'; 8 | import '../weapon/weapon_setting.dart'; 9 | 10 | GameSetting gameSetting = GameSetting(); 11 | 12 | class GameSetting { 13 | GameSetting._privateConstructor(); 14 | 15 | static final GameSetting _instance = GameSetting._privateConstructor(); 16 | 17 | factory GameSetting() { 18 | return _instance; 19 | } 20 | 21 | EnemySettingV1 enemies = EnemySettingV1(); 22 | WeaponSettingV1 weapons = WeaponSettingV1(); 23 | NeutralSetting neutral = NeutralSetting(); 24 | 25 | Vector2 mapGrid = Vector2(10, 10); 26 | late Vector2 mapPosition; 27 | late Vector2 mapSize; 28 | late Vector2 viewPosition; 29 | late Vector2 viewSize; 30 | late Vector2 barPosition; 31 | late Vector2 barSize; 32 | late Vector2 mapTileSize; 33 | 34 | double cannonBulletSpeed = 400; 35 | double cannonBulletDamage = 10; 36 | 37 | Vector2 enemySizeCale = Vector2(0.5, 0.5); 38 | late Vector2 enemySize; 39 | late Vector2 enemySpawn; 40 | late Vector2 enemyTarget; 41 | double enemySpeed = 80; 42 | 43 | late Vector2 screenSize; 44 | 45 | Vector2 dotMultiple(Vector2 x, Vector2 y) { 46 | return Vector2(x.x * y.x, x.y * y.y); 47 | } 48 | 49 | Vector2 dotDivide(Vector2 x, Vector2 y) { 50 | return Vector2(x.x / y.x, x.y / y.y); 51 | } 52 | 53 | Vector2 scaleOnMapTile(Vector2 scale) { 54 | return dotMultiple(mapTileSize, scale); 55 | } 56 | 57 | void setScreenSize(Vector2 size) { 58 | screenSize = size; 59 | optimizeMapGrid(size); 60 | 61 | enemySize = dotMultiple(enemySizeCale, mapTileSize); 62 | enemySpawn = Vector2(0, 0) + (mapTileSize / 2); 63 | enemyTarget = (mapSize) - (mapTileSize / 2); 64 | 65 | print('screenSize $screenSize, mapGrid $mapGrid, mapTileSize $mapTileSize'); 66 | } 67 | 68 | void optimizeMapGrid(Vector2 size) { 69 | mapGrid = Vector2(10, 10); 70 | double grid = math.min(mapGrid.x, mapGrid.y); 71 | Vector2 optSize = size / grid; 72 | grid = math.min(optSize.x, optSize.y); 73 | 74 | /*Bar at top*/ 75 | barPosition = Vector2(size.x / 2, grid / 2); 76 | barSize = Vector2(size.x, grid); 77 | viewPosition = Vector2(size.x / 2, size.y - (grid / 2)); 78 | viewSize = Vector2(size.x, grid * 1.5); 79 | /*Map in the middle*/ 80 | mapPosition = Vector2(size.x / 2, size.y / 2); 81 | mapSize = Vector2(size.x - 2, size.y - barSize.y - viewSize.y - 2); 82 | mapGrid = mapSize / grid; 83 | mapGrid = Vector2(mapGrid.x.toInt().toDouble(), mapGrid.y.toInt().toDouble()); 84 | mapTileSize = dotDivide(mapSize, mapGrid); 85 | } 86 | 87 | Future onLoad() async { 88 | await neutral.load(); 89 | await weapons.load(gameSetting); 90 | await enemies.load(); 91 | } 92 | } 93 | 94 | Future loadAsset(String assetFileName) async { 95 | return await rootBundle.loadString(assetFileName); 96 | } 97 | -------------------------------------------------------------------------------- /lib/enemy/enemy_factory.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:freedefense/base/game_component.dart'; 3 | import 'package:freedefense/enemy/enemy_component.dart'; 4 | import 'package:freedefense/enemy/enemy_v1.dart'; 5 | import 'dart:math' as math; 6 | 7 | import 'package:freedefense/game/game_controller.dart'; 8 | 9 | class EnemyFactory extends GameComponent { 10 | EnemyFactory() : super(position: Vector2.zero(), size: Vector2.zero()) { 11 | active = false; 12 | } 13 | 14 | EnemyComponent spawnEnemey(Vector2 anchor, EnemyType type) { 15 | late EnemyComponent enemy; 16 | enemy = EnemyV1(position: anchor, type: type); 17 | 18 | return enemy; 19 | } 20 | 21 | EnemyComponent spawnOneEnemy(EnemyType type) { 22 | EnemyComponent enemy; 23 | Vector2 initPosition = gameRef.gameController.gateStart.position; 24 | enemy = spawnEnemey(initPosition, type); 25 | gameRef.gameController.add(enemy); 26 | enpowerEnemy(enemy); 27 | enemy.moveSmart(gameRef.gameController.gateEnd.position); 28 | return enemy; 29 | } 30 | 31 | int currentWave = 0; 32 | int _spwanCount = 0; 33 | double _interval = 1; 34 | 35 | void start() => nextWave(); 36 | 37 | void nextWave() { 38 | currentWave++; 39 | gameRef.gameController.send(this, GameControl.ENEMY_NEXT_WAVE); 40 | switch (currentWave) { 41 | case 1: 42 | spawnEnemy(20, 1.2, spawnEnemyA); 43 | break; 44 | case 2: 45 | spawnEnemy(30, 0.8, spawnEnemyB); 46 | break; 47 | case 3: 48 | spawnEnemy(15, 2, spawnEnemyC); 49 | break; 50 | case 4: 51 | spawnEnemy(10, 1.5, spawnEnemyD); 52 | break; 53 | default: 54 | spawnEnemy(10, 2, spawnEnemyMix); 55 | break; 56 | } 57 | } 58 | 59 | void spawnEnemy(int number, double interval, Function spawnF) { 60 | _spwanCount = number; 61 | _interval = interval; 62 | spawnEnemyLoop(spawnF); 63 | } 64 | 65 | void spawnEnemyLoop(Function spawnF) { 66 | if (_spwanCount <= 0) { 67 | add(TimerComponent( 68 | period: _interval, 69 | repeat: false, 70 | removeOnFinish: true, 71 | onTick: () => nextWave())); 72 | } else { 73 | spawnF(); 74 | add(TimerComponent( 75 | period: _interval, 76 | repeat: false, 77 | removeOnFinish: true, 78 | onTick: () => spawnEnemyLoop(spawnF))); 79 | _spwanCount--; 80 | } 81 | } 82 | 83 | void spawnEnemyA() => spawnOneEnemy(EnemyType.ENEMYA); 84 | 85 | void spawnEnemyB() => spawnOneEnemy(EnemyType.ENEMYB); 86 | 87 | void spawnEnemyC() => spawnOneEnemy(EnemyType.ENEMYC); 88 | 89 | void spawnEnemyD() => spawnOneEnemy(EnemyType.ENEMYD); 90 | 91 | void spawnEnemyMix() { 92 | math.Random rnd = math.Random(); 93 | int r = rnd.nextInt(4); 94 | spawnOneEnemy(EnemyType.values[r]); 95 | } 96 | 97 | void enpowerEnemy(EnemyComponent enemy) { 98 | num exp = (currentWave - 1); 99 | enemy.maxLife *= math.pow(1.1, exp); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /linux/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file controls Flutter-level build steps. It should not be edited. 2 | cmake_minimum_required(VERSION 3.10) 3 | 4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 5 | 6 | # Configuration provided via flutter tool. 7 | include(${EPHEMERAL_DIR}/generated_config.cmake) 8 | 9 | # TODO: Move the rest of this into files in ephemeral. See 10 | # https://github.com/flutter/flutter/issues/57146. 11 | 12 | # Serves the same purpose as list(TRANSFORM ... PREPEND ...), 13 | # which isn't available in 3.10. 14 | function(list_prepend LIST_NAME PREFIX) 15 | set(NEW_LIST "") 16 | foreach(element ${${LIST_NAME}}) 17 | list(APPEND NEW_LIST "${PREFIX}${element}") 18 | endforeach(element) 19 | set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) 20 | endfunction() 21 | 22 | # === Flutter Library === 23 | # System-level dependencies. 24 | find_package(PkgConfig REQUIRED) 25 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) 26 | pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) 27 | pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) 28 | 29 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") 30 | 31 | # Published to parent scope for install step. 32 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 33 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 34 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 35 | set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) 36 | 37 | list(APPEND FLUTTER_LIBRARY_HEADERS 38 | "fl_basic_message_channel.h" 39 | "fl_binary_codec.h" 40 | "fl_binary_messenger.h" 41 | "fl_dart_project.h" 42 | "fl_engine.h" 43 | "fl_json_message_codec.h" 44 | "fl_json_method_codec.h" 45 | "fl_message_codec.h" 46 | "fl_method_call.h" 47 | "fl_method_channel.h" 48 | "fl_method_codec.h" 49 | "fl_method_response.h" 50 | "fl_plugin_registrar.h" 51 | "fl_plugin_registry.h" 52 | "fl_standard_message_codec.h" 53 | "fl_standard_method_codec.h" 54 | "fl_string_codec.h" 55 | "fl_value.h" 56 | "fl_view.h" 57 | "flutter_linux.h" 58 | ) 59 | list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") 60 | add_library(flutter INTERFACE) 61 | target_include_directories(flutter INTERFACE 62 | "${EPHEMERAL_DIR}" 63 | ) 64 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") 65 | target_link_libraries(flutter INTERFACE 66 | PkgConfig::GTK 67 | PkgConfig::GLIB 68 | PkgConfig::GIO 69 | ) 70 | add_dependencies(flutter flutter_assemble) 71 | 72 | # === Flutter tool backend === 73 | # _phony_ is a non-existent file to force this command to run every time, 74 | # since currently there's no way to get a full input/output list from the 75 | # flutter tool. 76 | add_custom_command( 77 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 78 | ${CMAKE_CURRENT_BINARY_DIR}/_phony_ 79 | COMMAND ${CMAKE_COMMAND} -E env 80 | ${FLUTTER_TOOL_ENVIRONMENT} 81 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" 82 | ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} 83 | VERBATIM 84 | ) 85 | add_custom_target(flutter_assemble DEPENDS 86 | "${FLUTTER_LIBRARY}" 87 | ${FLUTTER_LIBRARY_HEADERS} 88 | ) 89 | -------------------------------------------------------------------------------- /lib/game/game_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/cupertino.dart'; 2 | import 'package:freedefense/base/game_component.dart'; 3 | import 'package:freedefense/base/radar.dart'; 4 | import 'package:freedefense/base/scanable.dart'; 5 | import 'package:freedefense/enemy/enemy_component.dart'; 6 | import 'package:freedefense/game/game_main.dart'; 7 | import 'package:freedefense/weapon/bullet_component.dart'; 8 | import 'package:freedefense/weapon/cannon.dart'; 9 | import 'package:freedefense/weapon/weapon_component.dart'; 10 | 11 | class GameTest extends GameMain with GameDebug { 12 | @override 13 | Future onLoad() async { 14 | // recordTime(); 15 | await super.onLoad(); 16 | 17 | // timeDelay("Game onLoad "); 18 | } 19 | 20 | @override 21 | void update(double t) { 22 | recordTime(); 23 | super.update(t); 24 | timeDelay("Game update "); 25 | // if (loadDone) listComponents(); 26 | } 27 | 28 | @override 29 | void render(Canvas c) { 30 | recordTime(); 31 | super.render(c); 32 | timeDelay("Game render "); 33 | } 34 | 35 | // void debug(double t) { 36 | // if (debug) { 37 | // // double _fps = Flame.device.fps(); 38 | // // print('GameMain FPS $_fps'); 39 | // Iterable components = gameController.children; 40 | 41 | // var total = components.length; 42 | // var radars = components.where((element) => element is Radar).length; 43 | // var tiles = components.where((element) => element is MapTileComponent); 44 | // var cannons = components.where((element) => element is Cannon).length; 45 | 46 | // // print('total components $total, radars $radars, tiles $tiles, cannons $cannons, enemies $enemies, sensors $sensors, bullets $bullets'); 47 | // } 48 | // } 49 | } 50 | 51 | mixin GameDebug on GameMain { 52 | bool debug = false; 53 | int currentTimeMillis() { 54 | return new DateTime.now().millisecondsSinceEpoch; 55 | } 56 | 57 | int timeRecord = 0; 58 | void recordTime() { 59 | if (debug) { 60 | timeRecord = currentTimeMillis(); 61 | // print('start timeRecord at $timeRecord'); 62 | } 63 | } 64 | 65 | void timeDelay(String m) { 66 | if (debug) { 67 | if (timeRecord > 0) { 68 | int d = currentTimeMillis() - timeRecord; 69 | print('$m takes $d'); 70 | timeRecord = 0; 71 | } 72 | } 73 | } 74 | 75 | @override 76 | void update(double t) { 77 | if (t < 1) super.update(t); 78 | } 79 | 80 | void listComponents() { 81 | if (!debug) return; 82 | 83 | int weapon = 0, enemy = 0, cannon = 0, bullet = 0, exp = 0; 84 | int radar = 0, scanable = 0; 85 | GameComponent c = gameController; 86 | 87 | void _count(c) { 88 | if (c is WeaponComponent) weapon++; 89 | if (c is EnemyComponent) enemy++; 90 | if (c is Cannon) cannon++; 91 | if (c is BulletComponent) bullet++; 92 | if (c is ExplosionComponent) exp++; 93 | if (c is Radar) radar++; 94 | if (c is Scanable) scanable++; 95 | } 96 | 97 | void _loopChildren(c) { 98 | _count(c); 99 | if (c.children.length > 0) { 100 | c.children.forEach((e) => _loopChildren(e)); 101 | } 102 | } 103 | 104 | _loopChildren(c); 105 | 106 | print( 107 | "weapon $weapon, enemy $enemy, cannon $cannon, bullet $bullet, exp $exp, radar $radar, scanable $scanable"); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /lib/enemy/enemy_component.dart: -------------------------------------------------------------------------------- 1 | import 'dart:ui'; 2 | 3 | import 'package:flame/components.dart'; 4 | import 'package:freedefense/astar/astarnode.dart'; 5 | import 'package:freedefense/base/game_component.dart'; 6 | import 'package:freedefense/base/life_indicator.dart'; 7 | import 'package:freedefense/base/movable.dart'; 8 | import 'package:freedefense/base/scanable.dart'; 9 | import 'dart:math'; 10 | 11 | import 'package:freedefense/game/game_controller.dart'; 12 | 13 | enum EnemyType { ENEMYA, ENEMYB, ENEMYC, ENEMYD } 14 | 15 | class EnemyComponent extends GameComponent 16 | with Scanable, Movable, EnemySmartMove, LifeIndicator { 17 | double _maxLife = 0; 18 | double life = 0; 19 | int mineValue = 5; 20 | bool dead = false; 21 | late EnemyType enemyType; 22 | EnemyComponent({ 23 | required Vector2 position, 24 | required Vector2 size, 25 | }) : super(position: position, size: size, priority: 30); 26 | 27 | get maxLife => _maxLife; 28 | set maxLife(double m) { 29 | _maxLife = m; 30 | life = m; 31 | } 32 | 33 | @override 34 | void update(double t) { 35 | super.update(t); 36 | 37 | if (life < 0) { 38 | if (!dead) onKilled(); 39 | dead = true; 40 | active = false; 41 | } 42 | 43 | if (active) { 44 | updateMovable(t); 45 | } 46 | } 47 | 48 | @override 49 | void render(Canvas c) { 50 | super.render(c); 51 | renderLifIndicator(c); 52 | } 53 | 54 | @override 55 | void onRemove() { 56 | pathNode = null; 57 | super.onRemove(); 58 | } 59 | 60 | void receiveDamage(double damage) { 61 | life -= damage; 62 | } 63 | 64 | void onArrived() { 65 | if (!dead) { 66 | active = false; 67 | gameRef.gameController.send(this, GameControl.ENEMY_MISSED); 68 | this.removeFromParent(); 69 | } 70 | } 71 | 72 | void onKilled() { 73 | active = false; 74 | gameRef.gameController.send(this, GameControl.ENEMY_KILLED); 75 | gameRef.gamebarView.mineCollected += mineValue; 76 | this.removeFromParent(); 77 | } 78 | } 79 | 80 | mixin EnemySmartMove on GameComponent { 81 | /*Enemy move path controller */ 82 | AstarNode? pathNode; 83 | void moveSmart(Vector2 to) { 84 | pathNode = gameRef.mapController.astarMapResolve(position, to); 85 | if (pathNode != null) { 86 | pathNextMove(); 87 | } 88 | } 89 | 90 | void pathNextMove() { 91 | if (pathNode != null) { 92 | pathNode = pathNode!.next; 93 | if (pathNode != null) { 94 | (this as Movable).moveTo(moveRadomPosition(pathNode!), pathNextMove); 95 | } else { 96 | // If we reach the exit, but fail to hit it because of CPU load 97 | // Just 'Arrive' 98 | (this as EnemyComponent).onArrived(); 99 | } 100 | } 101 | } 102 | 103 | Vector2 moveRadomPosition(AstarNode node) { 104 | if (node.next == null) { 105 | /*target goto center*/ 106 | Vector2 lefttop = gameRef.mapController.nodeToPosition(node); 107 | return lefttop + (gameRef.mapController.tileSize / 2); 108 | } else { 109 | Vector2 lefttop = gameRef.mapController.nodeToPosition(node); 110 | Vector2 randomArea = Vector2( 111 | gameRef.mapController.tileSize.x - this.size.x, 112 | gameRef.mapController.tileSize.y - this.size.y); 113 | lefttop = lefttop + Vector2(this.size.x / 2, this.size.y / 2); 114 | double rndx = Random().nextDouble(); 115 | double rndy = Random().nextDouble(); 116 | return lefttop + Vector2(randomArea.x * rndx, randomArea.y * rndy); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /windows/runner/Runner.rc: -------------------------------------------------------------------------------- 1 | // Microsoft Visual C++ generated resource script. 2 | // 3 | #pragma code_page(65001) 4 | #include "resource.h" 5 | 6 | #define APSTUDIO_READONLY_SYMBOLS 7 | ///////////////////////////////////////////////////////////////////////////// 8 | // 9 | // Generated from the TEXTINCLUDE 2 resource. 10 | // 11 | #include "winres.h" 12 | 13 | ///////////////////////////////////////////////////////////////////////////// 14 | #undef APSTUDIO_READONLY_SYMBOLS 15 | 16 | ///////////////////////////////////////////////////////////////////////////// 17 | // English (United States) resources 18 | 19 | #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) 20 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US 21 | 22 | #ifdef APSTUDIO_INVOKED 23 | ///////////////////////////////////////////////////////////////////////////// 24 | // 25 | // TEXTINCLUDE 26 | // 27 | 28 | 1 TEXTINCLUDE 29 | BEGIN 30 | "resource.h\0" 31 | END 32 | 33 | 2 TEXTINCLUDE 34 | BEGIN 35 | "#include ""winres.h""\r\n" 36 | "\0" 37 | END 38 | 39 | 3 TEXTINCLUDE 40 | BEGIN 41 | "\r\n" 42 | "\0" 43 | END 44 | 45 | #endif // APSTUDIO_INVOKED 46 | 47 | 48 | ///////////////////////////////////////////////////////////////////////////// 49 | // 50 | // Icon 51 | // 52 | 53 | // Icon with lowest ID value placed first to ensure application icon 54 | // remains consistent on all systems. 55 | IDI_APP_ICON ICON "resources\\app_icon.ico" 56 | 57 | 58 | ///////////////////////////////////////////////////////////////////////////// 59 | // 60 | // Version 61 | // 62 | 63 | #if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) 64 | #define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD 65 | #else 66 | #define VERSION_AS_NUMBER 1,0,0,0 67 | #endif 68 | 69 | #if defined(FLUTTER_VERSION) 70 | #define VERSION_AS_STRING FLUTTER_VERSION 71 | #else 72 | #define VERSION_AS_STRING "1.0.0" 73 | #endif 74 | 75 | VS_VERSION_INFO VERSIONINFO 76 | FILEVERSION VERSION_AS_NUMBER 77 | PRODUCTVERSION VERSION_AS_NUMBER 78 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK 79 | #ifdef _DEBUG 80 | FILEFLAGS VS_FF_DEBUG 81 | #else 82 | FILEFLAGS 0x0L 83 | #endif 84 | FILEOS VOS__WINDOWS32 85 | FILETYPE VFT_APP 86 | FILESUBTYPE 0x0L 87 | BEGIN 88 | BLOCK "StringFileInfo" 89 | BEGIN 90 | BLOCK "040904e4" 91 | BEGIN 92 | VALUE "CompanyName", "com.example" "\0" 93 | VALUE "FileDescription", "free_defense" "\0" 94 | VALUE "FileVersion", VERSION_AS_STRING "\0" 95 | VALUE "InternalName", "free_defense" "\0" 96 | VALUE "LegalCopyright", "Copyright (C) 2023 com.example. All rights reserved." "\0" 97 | VALUE "OriginalFilename", "free_defense.exe" "\0" 98 | VALUE "ProductName", "free_defense" "\0" 99 | VALUE "ProductVersion", VERSION_AS_STRING "\0" 100 | END 101 | END 102 | BLOCK "VarFileInfo" 103 | BEGIN 104 | VALUE "Translation", 0x409, 1252 105 | END 106 | END 107 | 108 | #endif // English (United States) resources 109 | ///////////////////////////////////////////////////////////////////////////// 110 | 111 | 112 | 113 | #ifndef APSTUDIO_INVOKED 114 | ///////////////////////////////////////////////////////////////////////////// 115 | // 116 | // Generated from the TEXTINCLUDE 3 resource. 117 | // 118 | 119 | 120 | ///////////////////////////////////////////////////////////////////////////// 121 | #endif // not APSTUDIO_INVOKED 122 | -------------------------------------------------------------------------------- /assets/tiles/0929.tmx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | zAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAywEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAywEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADLAQAAywEAAMsBAADMAQAAywEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAAzAEAAMwBAADMAQAA 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /lib/spacescape/models/spaceship_details.dart: -------------------------------------------------------------------------------- 1 | // This class represents all the data 2 | // which defines a spaceship. 3 | import 'package:hive/hive.dart'; 4 | 5 | part 'spaceship_details.g.dart'; 6 | 7 | class Spaceship { 8 | // Name of the spaceship. 9 | final String name; 10 | 11 | // Cost of the spaceship. 12 | final int cost; 13 | 14 | // Cost of the spaceship. 15 | final double speed; 16 | 17 | // SpriteId to be used for displaying 18 | // this spaceship in game world. 19 | final int spriteId; 20 | 21 | // Path to the asset to be used for displaying 22 | // this spaceship outside game world. 23 | final String assetPath; 24 | 25 | // Level of the spaceship. 26 | final int level; 27 | 28 | const Spaceship({ 29 | required this.name, 30 | required this.cost, 31 | required this.speed, 32 | required this.spriteId, 33 | required this.assetPath, 34 | required this.level, 35 | }); 36 | 37 | /// Given a spaceshipType, this method returns a corresponding 38 | /// Spaceship object which holds all the details of that spaceship. 39 | static Spaceship getSpaceshipByType(SpaceshipType spaceshipType) { 40 | /// It is highly unlikely that it [spaceships] does not contain given [spaceshipType]. 41 | /// But if that ever happens, we will just return data for [SpaceshipType.Canary]. 42 | return spaceships[spaceshipType] ?? spaceships.entries.first.value; 43 | } 44 | 45 | /// This map holds all the meta-data of each [SpaceshipType]. 46 | static const Map spaceships = { 47 | SpaceshipType.canary: Spaceship( 48 | name: 'Canary', 49 | cost: 0, 50 | speed: 250, 51 | spriteId: 0, 52 | assetPath: 'assets/spacescape/images/ship_A.png', 53 | level: 1, 54 | ), 55 | SpaceshipType.dusky: Spaceship( 56 | name: 'Dusky', 57 | cost: 100, 58 | speed: 400, 59 | spriteId: 1, 60 | assetPath: 'assets/images/ship_B.png', 61 | level: 2, 62 | ), 63 | SpaceshipType.condor: Spaceship( 64 | name: 'Condor', 65 | cost: 200, 66 | speed: 300, 67 | spriteId: 2, 68 | assetPath: 'assets/images/ship_C.png', 69 | level: 2, 70 | ), 71 | SpaceshipType.cXC: Spaceship( 72 | name: 'CXC', 73 | cost: 400, 74 | speed: 300, 75 | spriteId: 3, 76 | assetPath: 'assets/images/ship_D.png', 77 | level: 3, 78 | ), 79 | SpaceshipType.raptor: Spaceship( 80 | name: 'Raptor', 81 | cost: 550, 82 | speed: 300, 83 | spriteId: 4, 84 | assetPath: 'assets/images/ship_E.png', 85 | level: 3, 86 | ), 87 | SpaceshipType.raptorX: Spaceship( 88 | name: 'Raptor-X', 89 | cost: 700, 90 | speed: 350, 91 | spriteId: 5, 92 | assetPath: 'assets/images/ship_F.png', 93 | level: 3, 94 | ), 95 | SpaceshipType.albatross: Spaceship( 96 | name: 'Albatross', 97 | cost: 850, 98 | speed: 400, 99 | spriteId: 6, 100 | assetPath: 'assets/images/ship_G.png', 101 | level: 4, 102 | ), 103 | SpaceshipType.dK809: Spaceship( 104 | name: 'DK-809', 105 | cost: 1000, 106 | speed: 450, 107 | spriteId: 7, 108 | assetPath: 'assets/images/ship_H.png', 109 | level: 4, 110 | ), 111 | }; 112 | } 113 | 114 | // This enum represents all the spaceship 115 | // types available in this game. 116 | @HiveType(typeId: 1) 117 | enum SpaceshipType { 118 | @HiveField(0) 119 | canary, 120 | 121 | @HiveField(1) 122 | dusky, 123 | 124 | @HiveField(2) 125 | condor, 126 | 127 | @HiveField(3) 128 | cXC, 129 | 130 | @HiveField(4) 131 | raptor, 132 | 133 | @HiveField(5) 134 | raptorX, 135 | 136 | @HiveField(6) 137 | albatross, 138 | 139 | @HiveField(7) 140 | dK809, 141 | } 142 | -------------------------------------------------------------------------------- /windows/runner/win32_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_WIN32_WINDOW_H_ 2 | #define RUNNER_WIN32_WINDOW_H_ 3 | 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | // A class abstraction for a high DPI-aware Win32 Window. Intended to be 11 | // inherited from by classes that wish to specialize with custom 12 | // rendering and input handling 13 | class Win32Window { 14 | public: 15 | struct Point { 16 | unsigned int x; 17 | unsigned int y; 18 | Point(unsigned int x, unsigned int y) : x(x), y(y) {} 19 | }; 20 | 21 | struct Size { 22 | unsigned int width; 23 | unsigned int height; 24 | Size(unsigned int width, unsigned int height) 25 | : width(width), height(height) {} 26 | }; 27 | 28 | Win32Window(); 29 | virtual ~Win32Window(); 30 | 31 | // Creates a win32 window with |title| that is positioned and sized using 32 | // |origin| and |size|. New windows are created on the default monitor. Window 33 | // sizes are specified to the OS in physical pixels, hence to ensure a 34 | // consistent size this function will scale the inputted width and height as 35 | // as appropriate for the default monitor. The window is invisible until 36 | // |Show| is called. Returns true if the window was created successfully. 37 | bool Create(const std::wstring& title, const Point& origin, const Size& size); 38 | 39 | // Show the current window. Returns true if the window was successfully shown. 40 | bool Show(); 41 | 42 | // Release OS resources associated with window. 43 | void Destroy(); 44 | 45 | // Inserts |content| into the window tree. 46 | void SetChildContent(HWND content); 47 | 48 | // Returns the backing Window handle to enable clients to set icon and other 49 | // window properties. Returns nullptr if the window has been destroyed. 50 | HWND GetHandle(); 51 | 52 | // If true, closing this window will quit the application. 53 | void SetQuitOnClose(bool quit_on_close); 54 | 55 | // Return a RECT representing the bounds of the current client area. 56 | RECT GetClientArea(); 57 | 58 | protected: 59 | // Processes and route salient window messages for mouse handling, 60 | // size change and DPI. Delegates handling of these to member overloads that 61 | // inheriting classes can handle. 62 | virtual LRESULT MessageHandler(HWND window, 63 | UINT const message, 64 | WPARAM const wparam, 65 | LPARAM const lparam) noexcept; 66 | 67 | // Called when CreateAndShow is called, allowing subclass window-related 68 | // setup. Subclasses should return false if setup fails. 69 | virtual bool OnCreate(); 70 | 71 | // Called when Destroy is called. 72 | virtual void OnDestroy(); 73 | 74 | private: 75 | friend class WindowClassRegistrar; 76 | 77 | // OS callback called by message pump. Handles the WM_NCCREATE message which 78 | // is passed when the non-client area is being created and enables automatic 79 | // non-client DPI scaling so that the non-client area automatically 80 | // responds to changes in DPI. All other messages are handled by 81 | // MessageHandler. 82 | static LRESULT CALLBACK WndProc(HWND const window, 83 | UINT const message, 84 | WPARAM const wparam, 85 | LPARAM const lparam) noexcept; 86 | 87 | // Retrieves a class instance pointer for |window| 88 | static Win32Window* GetThisFromHandle(HWND const window) noexcept; 89 | 90 | // Update the window frame's theme to match the system theme. 91 | static void UpdateTheme(HWND const window); 92 | 93 | bool quit_on_close_ = false; 94 | 95 | // window handle for top level window. 96 | HWND window_handle_ = nullptr; 97 | 98 | // window handle for hosted content. 99 | HWND child_content_ = nullptr; 100 | }; 101 | 102 | #endif // RUNNER_WIN32_WINDOW_H_ 103 | -------------------------------------------------------------------------------- /lib/spacescape/models/player_data.dart: -------------------------------------------------------------------------------- 1 | import 'package:hive/hive.dart'; 2 | import 'package:flutter/material.dart'; 3 | 4 | import 'spaceship_details.dart'; 5 | 6 | part 'player_data.g.dart'; 7 | 8 | // This class represents all the persistent data that we 9 | // might want to store for tracking player progress. 10 | @HiveType(typeId: 0) 11 | class PlayerData extends ChangeNotifier with HiveObjectMixin { 12 | static const String playerDataBox = 'PlayerDataBox'; 13 | static const String playerDataKey = 'PlayerData'; 14 | 15 | // The spaceship type of player's current spaceship. 16 | @HiveField(0) 17 | SpaceshipType spaceshipType; 18 | 19 | // List of all the spaceships owned by player. 20 | // Note that just storing their type is enough. 21 | @HiveField(1) 22 | final List ownedSpaceships; 23 | 24 | // Highest player score so far. 25 | @HiveField(2) 26 | late int _highScore; 27 | int get highScore => _highScore; 28 | 29 | // Balance money. 30 | @HiveField(3) 31 | int money; 32 | 33 | // Keeps track of current score. 34 | // If game is not running, this will 35 | // represent score of last round. 36 | int _currentScore = 0; 37 | 38 | int get currentScore => _currentScore; 39 | 40 | set currentScore(int newScore) { 41 | _currentScore = newScore; 42 | // While setting currentScore to a new value 43 | // also make sure to update highScore. 44 | if (_highScore < _currentScore) { 45 | _highScore = _currentScore; 46 | } 47 | } 48 | 49 | PlayerData({ 50 | required this.spaceshipType, 51 | required this.ownedSpaceships, 52 | int highScore = 0, 53 | required this.money, 54 | }) { 55 | _highScore = highScore; 56 | } 57 | 58 | /// Creates a new instance of [PlayerData] from given map. 59 | PlayerData.fromMap(Map map) 60 | : spaceshipType = map['currentSpaceshipType'], 61 | ownedSpaceships = map['ownedSpaceshipTypes'] 62 | .map((e) => e as SpaceshipType) // Map out each element. 63 | .cast() // Cast each element to SpaceshipType. 64 | .toList(), // Convert to a List. 65 | _highScore = map['highScore'], 66 | money = map['money']; 67 | 68 | // A default map which should be used for creating the 69 | // very first PlayerData instance when game is launched 70 | // for the first time. 71 | static Map defaultData = { 72 | 'currentSpaceshipType': SpaceshipType.canary, 73 | 'ownedSpaceshipTypes': [SpaceshipType.canary], 74 | 'highScore': 0, 75 | 'money': 0, 76 | }; 77 | 78 | /// Returns true if given [SpaceshipType] is owned by player. 79 | bool isOwned(SpaceshipType spaceshipType) { 80 | return ownedSpaceships.contains(spaceshipType); 81 | } 82 | 83 | /// Returns true if player has enough money to by given [SpaceshipType]. 84 | bool canBuy(SpaceshipType spaceshipType) { 85 | return (money >= Spaceship.getSpaceshipByType(spaceshipType).cost); 86 | } 87 | 88 | /// Returns true if player's current spaceship type is same as given [SpaceshipType]. 89 | bool isEquipped(SpaceshipType spaceshipType) { 90 | return (this.spaceshipType == spaceshipType); 91 | } 92 | 93 | /// Buys the given [SpaceshipType] if player has enough money and does not already own it. 94 | void buy(SpaceshipType spaceshipType) { 95 | if (canBuy(spaceshipType) && (!isOwned(spaceshipType))) { 96 | money -= Spaceship.getSpaceshipByType(spaceshipType).cost; 97 | ownedSpaceships.add(spaceshipType); 98 | notifyListeners(); 99 | 100 | // Saves player data to disk. 101 | save(); 102 | } 103 | } 104 | 105 | /// Sets the given [SpaceshipType] as the current spaceship type for player. 106 | void equip(SpaceshipType spaceshipType) { 107 | this.spaceshipType = spaceshipType; 108 | notifyListeners(); 109 | 110 | // Saves player data to disk. 111 | save(); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 37 | 38 | 39 | 40 | 43 | 49 | 50 | 51 | 52 | 53 | 63 | 65 | 71 | 72 | 73 | 74 | 80 | 82 | 88 | 89 | 90 | 91 | 93 | 94 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /lib/spacescape/main.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/flame.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:hive_flutter/hive_flutter.dart'; 4 | import 'package:provider/provider.dart'; 5 | 6 | import 'models/player_data.dart'; 7 | import 'models/settings.dart'; 8 | import 'models/spaceship_details.dart'; 9 | import 'screens/main_menu.dart'; 10 | 11 | Future main() async { 12 | WidgetsFlutterBinding.ensureInitialized(); 13 | 14 | // This opens the app in fullscreen mode. 15 | await Flame.device.fullScreen(); 16 | 17 | // Initialize hive. 18 | await initHive(); 19 | 20 | runApp( 21 | MultiProvider( 22 | providers: [ 23 | FutureProvider( 24 | create: (BuildContext context) => getPlayerData(), 25 | initialData: PlayerData.fromMap(PlayerData.defaultData), 26 | ), 27 | FutureProvider( 28 | create: (BuildContext context) => getSettings(), 29 | initialData: Settings(soundEffects: false, backgroundMusic: false), 30 | ), 31 | ], 32 | builder: (context, child) { 33 | // We use .value constructor here because the required objects 34 | // are already created by upstream FutureProviders. 35 | return MultiProvider( 36 | providers: [ 37 | ChangeNotifierProvider.value( 38 | value: Provider.of(context), 39 | ), 40 | ChangeNotifierProvider.value( 41 | value: Provider.of(context), 42 | ), 43 | ], 44 | child: child, 45 | ); 46 | }, 47 | child: MaterialApp( 48 | debugShowCheckedModeBanner: false, 49 | // Dark more because we are too cool for white theme. 50 | themeMode: ThemeMode.dark, 51 | // Use custom theme with 'BungeeInline' font. 52 | darkTheme: ThemeData( 53 | brightness: Brightness.dark, 54 | fontFamily: 'BungeeInline', 55 | scaffoldBackgroundColor: Colors.black, 56 | ), 57 | // MainMenu will be the first screen for now. 58 | // But this might change in future if we decide 59 | // to add a splash screen. 60 | home: const MainMenu(), 61 | ), 62 | ), 63 | ); 64 | } 65 | 66 | // This function initializes hive with app's 67 | // documents directory and also registers 68 | // all the hive adapters. 69 | Future initHive() async { 70 | await Hive.initFlutter(); 71 | 72 | Hive.registerAdapter(PlayerDataAdapter()); 73 | Hive.registerAdapter(SpaceshipTypeAdapter()); 74 | Hive.registerAdapter(SettingsAdapter()); 75 | } 76 | 77 | /// This function reads the stored [PlayerData] from disk. 78 | Future getPlayerData() async { 79 | // Open the player data box and read player data from it. 80 | final box = await Hive.openBox(PlayerData.playerDataBox); 81 | final playerData = box.get(PlayerData.playerDataKey); 82 | 83 | // If player data is null, it means this is a fresh launch 84 | // of the game. In such case, we first store the default 85 | // player data in the player data box and then return the same. 86 | if (playerData == null) { 87 | box.put( 88 | PlayerData.playerDataKey, 89 | PlayerData.fromMap(PlayerData.defaultData), 90 | ); 91 | } 92 | 93 | return box.get(PlayerData.playerDataKey)!; 94 | } 95 | 96 | /// This function reads the stored [Settings] from disk. 97 | Future getSettings() async { 98 | // Open the settings box and read settings from it. 99 | final box = await Hive.openBox(Settings.settingsBox); 100 | final settings = box.get(Settings.settingsKey); 101 | 102 | // If settings is null, it means this is a fresh launch 103 | // of the game. In such case, we first store the default 104 | // settings in the settings box and then return the same. 105 | if (settings == null) { 106 | box.put(Settings.settingsKey, Settings(soundEffects: true, backgroundMusic: true)); 107 | } 108 | 109 | return box.get(Settings.settingsKey)!; 110 | } 111 | -------------------------------------------------------------------------------- /linux/my_application.cc: -------------------------------------------------------------------------------- 1 | #include "my_application.h" 2 | 3 | #include 4 | #ifdef GDK_WINDOWING_X11 5 | #include 6 | #endif 7 | 8 | #include "flutter/generated_plugin_registrant.h" 9 | 10 | struct _MyApplication { 11 | GtkApplication parent_instance; 12 | char** dart_entrypoint_arguments; 13 | }; 14 | 15 | G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) 16 | 17 | // Implements GApplication::activate. 18 | static void my_application_activate(GApplication* application) { 19 | MyApplication* self = MY_APPLICATION(application); 20 | GtkWindow* window = 21 | GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); 22 | 23 | // Use a header bar when running in GNOME as this is the common style used 24 | // by applications and is the setup most users will be using (e.g. Ubuntu 25 | // desktop). 26 | // If running on X and not using GNOME then just use a traditional title bar 27 | // in case the window manager does more exotic layout, e.g. tiling. 28 | // If running on Wayland assume the header bar will work (may need changing 29 | // if future cases occur). 30 | gboolean use_header_bar = TRUE; 31 | #ifdef GDK_WINDOWING_X11 32 | GdkScreen* screen = gtk_window_get_screen(window); 33 | if (GDK_IS_X11_SCREEN(screen)) { 34 | const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); 35 | if (g_strcmp0(wm_name, "GNOME Shell") != 0) { 36 | use_header_bar = FALSE; 37 | } 38 | } 39 | #endif 40 | if (use_header_bar) { 41 | GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); 42 | gtk_widget_show(GTK_WIDGET(header_bar)); 43 | gtk_header_bar_set_title(header_bar, "free_defense"); 44 | gtk_header_bar_set_show_close_button(header_bar, TRUE); 45 | gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); 46 | } else { 47 | gtk_window_set_title(window, "free_defense"); 48 | } 49 | 50 | gtk_window_set_default_size(window, 1280, 720); 51 | gtk_widget_show(GTK_WIDGET(window)); 52 | 53 | g_autoptr(FlDartProject) project = fl_dart_project_new(); 54 | fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); 55 | 56 | FlView* view = fl_view_new(project); 57 | gtk_widget_show(GTK_WIDGET(view)); 58 | gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); 59 | 60 | fl_register_plugins(FL_PLUGIN_REGISTRY(view)); 61 | 62 | gtk_widget_grab_focus(GTK_WIDGET(view)); 63 | } 64 | 65 | // Implements GApplication::local_command_line. 66 | static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { 67 | MyApplication* self = MY_APPLICATION(application); 68 | // Strip out the first argument as it is the binary name. 69 | self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); 70 | 71 | g_autoptr(GError) error = nullptr; 72 | if (!g_application_register(application, nullptr, &error)) { 73 | g_warning("Failed to register: %s", error->message); 74 | *exit_status = 1; 75 | return TRUE; 76 | } 77 | 78 | g_application_activate(application); 79 | *exit_status = 0; 80 | 81 | return TRUE; 82 | } 83 | 84 | // Implements GObject::dispose. 85 | static void my_application_dispose(GObject* object) { 86 | MyApplication* self = MY_APPLICATION(object); 87 | g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); 88 | G_OBJECT_CLASS(my_application_parent_class)->dispose(object); 89 | } 90 | 91 | static void my_application_class_init(MyApplicationClass* klass) { 92 | G_APPLICATION_CLASS(klass)->activate = my_application_activate; 93 | G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; 94 | G_OBJECT_CLASS(klass)->dispose = my_application_dispose; 95 | } 96 | 97 | static void my_application_init(MyApplication* self) {} 98 | 99 | MyApplication* my_application_new() { 100 | return MY_APPLICATION(g_object_new(my_application_get_type(), 101 | "application-id", APPLICATION_ID, 102 | "flags", G_APPLICATION_NON_UNIQUE, 103 | nullptr)); 104 | } 105 | -------------------------------------------------------------------------------- /windows/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file controls Flutter-level build steps. It should not be edited. 2 | cmake_minimum_required(VERSION 3.14) 3 | 4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 5 | 6 | # Configuration provided via flutter tool. 7 | include(${EPHEMERAL_DIR}/generated_config.cmake) 8 | 9 | # TODO: Move the rest of this into files in ephemeral. See 10 | # https://github.com/flutter/flutter/issues/57146. 11 | set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") 12 | 13 | # Set fallback configurations for older versions of the flutter tool. 14 | if (NOT DEFINED FLUTTER_TARGET_PLATFORM) 15 | set(FLUTTER_TARGET_PLATFORM "windows-x64") 16 | endif() 17 | 18 | # === Flutter Library === 19 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") 20 | 21 | # Published to parent scope for install step. 22 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 23 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 24 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 25 | set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) 26 | 27 | list(APPEND FLUTTER_LIBRARY_HEADERS 28 | "flutter_export.h" 29 | "flutter_windows.h" 30 | "flutter_messenger.h" 31 | "flutter_plugin_registrar.h" 32 | "flutter_texture_registrar.h" 33 | ) 34 | list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") 35 | add_library(flutter INTERFACE) 36 | target_include_directories(flutter INTERFACE 37 | "${EPHEMERAL_DIR}" 38 | ) 39 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") 40 | add_dependencies(flutter flutter_assemble) 41 | 42 | # === Wrapper === 43 | list(APPEND CPP_WRAPPER_SOURCES_CORE 44 | "core_implementations.cc" 45 | "standard_codec.cc" 46 | ) 47 | list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") 48 | list(APPEND CPP_WRAPPER_SOURCES_PLUGIN 49 | "plugin_registrar.cc" 50 | ) 51 | list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") 52 | list(APPEND CPP_WRAPPER_SOURCES_APP 53 | "flutter_engine.cc" 54 | "flutter_view_controller.cc" 55 | ) 56 | list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") 57 | 58 | # Wrapper sources needed for a plugin. 59 | add_library(flutter_wrapper_plugin STATIC 60 | ${CPP_WRAPPER_SOURCES_CORE} 61 | ${CPP_WRAPPER_SOURCES_PLUGIN} 62 | ) 63 | apply_standard_settings(flutter_wrapper_plugin) 64 | set_target_properties(flutter_wrapper_plugin PROPERTIES 65 | POSITION_INDEPENDENT_CODE ON) 66 | set_target_properties(flutter_wrapper_plugin PROPERTIES 67 | CXX_VISIBILITY_PRESET hidden) 68 | target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) 69 | target_include_directories(flutter_wrapper_plugin PUBLIC 70 | "${WRAPPER_ROOT}/include" 71 | ) 72 | add_dependencies(flutter_wrapper_plugin flutter_assemble) 73 | 74 | # Wrapper sources needed for the runner. 75 | add_library(flutter_wrapper_app STATIC 76 | ${CPP_WRAPPER_SOURCES_CORE} 77 | ${CPP_WRAPPER_SOURCES_APP} 78 | ) 79 | apply_standard_settings(flutter_wrapper_app) 80 | target_link_libraries(flutter_wrapper_app PUBLIC flutter) 81 | target_include_directories(flutter_wrapper_app PUBLIC 82 | "${WRAPPER_ROOT}/include" 83 | ) 84 | add_dependencies(flutter_wrapper_app flutter_assemble) 85 | 86 | # === Flutter tool backend === 87 | # _phony_ is a non-existent file to force this command to run every time, 88 | # since currently there's no way to get a full input/output list from the 89 | # flutter tool. 90 | set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") 91 | set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) 92 | add_custom_command( 93 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 94 | ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} 95 | ${CPP_WRAPPER_SOURCES_APP} 96 | ${PHONY_OUTPUT} 97 | COMMAND ${CMAKE_COMMAND} -E env 98 | ${FLUTTER_TOOL_ENVIRONMENT} 99 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" 100 | ${FLUTTER_TARGET_PLATFORM} $ 101 | VERBATIM 102 | ) 103 | add_custom_target(flutter_assemble DEPENDS 104 | "${FLUTTER_LIBRARY}" 105 | ${FLUTTER_LIBRARY_HEADERS} 106 | ${CPP_WRAPPER_SOURCES_CORE} 107 | ${CPP_WRAPPER_SOURCES_PLUGIN} 108 | ${CPP_WRAPPER_SOURCES_APP} 109 | ) 110 | -------------------------------------------------------------------------------- /lib/view/weaponview_widget.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/components.dart'; 2 | import 'package:flame/widgets.dart'; 3 | import 'package:flutter/widgets.dart'; 4 | import 'package:freedefense/base/game_component.dart'; 5 | import 'package:freedefense/game/game_controller.dart'; 6 | import 'package:freedefense/game/game_main.dart'; 7 | import 'package:freedefense/game/game_setting.dart'; 8 | import 'package:freedefense/weapon/weapon_component.dart'; 9 | 10 | class WeaponViewWidget { 11 | static const String name = 'weaponview'; 12 | 13 | static Widget builder(BuildContext buildContext, GameMain game) { 14 | Vector2 size = Vector2(GameSetting().screenSize.x * 0.8, 500); 15 | Vector2 arrowSize = Vector2(20, 20); 16 | if (_selected == null) { 17 | return Center(); 18 | } else { 19 | _selected?.dialogVisible = false; 20 | } 21 | Vector2 anchor = 22 | game.gameController.absolutePositionOf(_selected!.position); 23 | if (anchor.y > GameSetting().screenSize.y / 2) { 24 | anchor = Vector2(anchor.x - size.x / 2, 25 | anchor.y - _selected!.size.y / 2 - size.y - arrowSize.y); 26 | } else { 27 | anchor = Vector2(anchor.x - size.x / 2, 28 | anchor.y + _selected!.size.y / 2 + arrowSize.y); 29 | } 30 | anchor.x = GameSetting().screenSize.x / 2 - size.x / 2; 31 | String imagePath = ""; 32 | int index =_selected?.barrelModelIndex ?? 2; 33 | if (index < 2) { 34 | imagePath = _selected?.setting.paths[(_selected?.barrelModelIndex ?? 0) + 1] ?? ""; 35 | } 36 | 37 | _selected?.dialogVisible = true; 38 | return Positioned( 39 | top: anchor.y, 40 | left: anchor.x, 41 | child: Container( 42 | decoration: BoxDecoration( 43 | image: DecorationImage( 44 | image: AssetImage("assets/images/diaglog.png"), 45 | fit: BoxFit.fill)), 46 | width: size.x / 2, 47 | height: size.y / 2, 48 | child: Stack(alignment: Alignment.center, children: [ 49 | (imagePath != "") 50 | ? Positioned( 51 | top: 75, 52 | child: SpriteButton.asset( 53 | path: imagePath , 54 | pressedPath: imagePath, 55 | width: 45, 56 | height: 45, 57 | onPressed: () { 58 | _selected?.upgradeBarrel(); 59 | _selected?.dialogVisible = false; 60 | hide(); 61 | }, 62 | label: const Text( 63 | 'Upgrade', 64 | style: TextStyle(color: Color(0xFF5D275D)), 65 | ), 66 | )) 67 | : Container(), 68 | Positioned( 69 | top: 25, 70 | child: SpriteButton.asset( 71 | path: 'destroy.png', 72 | pressedPath: 'destroy2.png', 73 | width: 45, 74 | height: 45, 75 | onPressed: () { 76 | _selected?.active = false; 77 | _selected?.removeFromParent(); 78 | _selected?.gameRef.gameController.send( 79 | _selected as GameComponent, 80 | GameControl.WEAPON_DESTROYED); 81 | _selected?.dialogVisible = false; 82 | hide(); 83 | }, 84 | label: const Text( 85 | 'Destroy0', 86 | style: TextStyle(color: Color(0xFF5D275D)), 87 | ), 88 | )) 89 | ])), 90 | ); 91 | } 92 | 93 | static int count = 0; 94 | static WeaponComponent? _selected; 95 | 96 | static show(WeaponComponent w) { 97 | hide(); 98 | _selected = w; 99 | count++; 100 | String finalName = "$name-${count % 2}"; 101 | _selected?.gameRef.overlays.add(finalName); 102 | } 103 | 104 | static hide() { 105 | _selected?.dialogVisible = false; 106 | String finalName = "$name-${count % 2}"; 107 | _selected?.gameRef.overlays.remove(finalName); 108 | _selected = null; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /windows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Project-level configuration. 2 | cmake_minimum_required(VERSION 3.14) 3 | project(free_defense LANGUAGES CXX) 4 | 5 | # The name of the executable created for the application. Change this to change 6 | # the on-disk name of your application. 7 | set(BINARY_NAME "free_defense") 8 | 9 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent 10 | # versions of CMake. 11 | cmake_policy(VERSION 3.14...3.25) 12 | 13 | # Define build configuration option. 14 | get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) 15 | if(IS_MULTICONFIG) 16 | set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" 17 | CACHE STRING "" FORCE) 18 | else() 19 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 20 | set(CMAKE_BUILD_TYPE "Debug" CACHE 21 | STRING "Flutter build mode" FORCE) 22 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 23 | "Debug" "Profile" "Release") 24 | endif() 25 | endif() 26 | # Define settings for the Profile build mode. 27 | set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") 28 | set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") 29 | set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") 30 | set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") 31 | 32 | # Use Unicode for all projects. 33 | add_definitions(-DUNICODE -D_UNICODE) 34 | 35 | # Compilation settings that should be applied to most targets. 36 | # 37 | # Be cautious about adding new options here, as plugins use this function by 38 | # default. In most cases, you should add new options to specific targets instead 39 | # of modifying this function. 40 | function(APPLY_STANDARD_SETTINGS TARGET) 41 | target_compile_features(${TARGET} PUBLIC cxx_std_17) 42 | target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") 43 | target_compile_options(${TARGET} PRIVATE /EHsc) 44 | target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") 45 | target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") 46 | endfunction() 47 | 48 | # Flutter library and tool build rules. 49 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 50 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 51 | 52 | # Application build; see runner/CMakeLists.txt. 53 | add_subdirectory("runner") 54 | 55 | 56 | # Generated plugin build rules, which manage building the plugins and adding 57 | # them to the application. 58 | include(flutter/generated_plugins.cmake) 59 | 60 | 61 | # === Installation === 62 | # Support files are copied into place next to the executable, so that it can 63 | # run in place. This is done instead of making a separate bundle (as on Linux) 64 | # so that building and running from within Visual Studio will work. 65 | set(BUILD_BUNDLE_DIR "$") 66 | # Make the "install" step default, as it's required to run. 67 | set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) 68 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 69 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 70 | endif() 71 | 72 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 73 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") 74 | 75 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 76 | COMPONENT Runtime) 77 | 78 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 79 | COMPONENT Runtime) 80 | 81 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 82 | COMPONENT Runtime) 83 | 84 | if(PLUGIN_BUNDLED_LIBRARIES) 85 | install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" 86 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 87 | COMPONENT Runtime) 88 | endif() 89 | 90 | # Copy the native assets provided by the build.dart from all packages. 91 | set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") 92 | install(DIRECTORY "${NATIVE_ASSETS_DIR}" 93 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 94 | COMPONENT Runtime) 95 | 96 | # Fully re-copy the assets directory on each build to avoid having stale files 97 | # from a previous install. 98 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 99 | install(CODE " 100 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 101 | " COMPONENT Runtime) 102 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 103 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 104 | 105 | # Install the AOT library on non-Debug builds only. 106 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 107 | CONFIGURATIONS Profile;Release 108 | COMPONENT Runtime) 109 | -------------------------------------------------------------------------------- /assets/spacescape/fonts/BungeeInline/OFL.txt: -------------------------------------------------------------------------------- 1 | Copyright 2008 The Bungee Project Authors (david@djr.com) 2 | 3 | This Font Software is licensed under the SIL Open Font License, Version 1.1. 4 | This license is copied below, and is also available with a FAQ at: 5 | http://scripts.sil.org/OFL 6 | 7 | 8 | ----------------------------------------------------------- 9 | SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 10 | ----------------------------------------------------------- 11 | 12 | PREAMBLE 13 | The goals of the Open Font License (OFL) are to stimulate worldwide 14 | development of collaborative font projects, to support the font creation 15 | efforts of academic and linguistic communities, and to provide a free and 16 | open framework in which fonts may be shared and improved in partnership 17 | with others. 18 | 19 | The OFL allows the licensed fonts to be used, studied, modified and 20 | redistributed freely as long as they are not sold by themselves. The 21 | fonts, including any derivative works, can be bundled, embedded, 22 | redistributed and/or sold with any software provided that any reserved 23 | names are not used by derivative works. The fonts and derivatives, 24 | however, cannot be released under any other type of license. The 25 | requirement for fonts to remain under this license does not apply 26 | to any document created using the fonts or their derivatives. 27 | 28 | DEFINITIONS 29 | "Font Software" refers to the set of files released by the Copyright 30 | Holder(s) under this license and clearly marked as such. This may 31 | include source files, build scripts and documentation. 32 | 33 | "Reserved Font Name" refers to any names specified as such after the 34 | copyright statement(s). 35 | 36 | "Original Version" refers to the collection of Font Software components as 37 | distributed by the Copyright Holder(s). 38 | 39 | "Modified Version" refers to any derivative made by adding to, deleting, 40 | or substituting -- in part or in whole -- any of the components of the 41 | Original Version, by changing formats or by porting the Font Software to a 42 | new environment. 43 | 44 | "Author" refers to any designer, engineer, programmer, technical 45 | writer or other person who contributed to the Font Software. 46 | 47 | PERMISSION & CONDITIONS 48 | Permission is hereby granted, free of charge, to any person obtaining 49 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 50 | redistribute, and sell modified and unmodified copies of the Font 51 | Software, subject to the following conditions: 52 | 53 | 1) Neither the Font Software nor any of its individual components, 54 | in Original or Modified Versions, may be sold by itself. 55 | 56 | 2) Original or Modified Versions of the Font Software may be bundled, 57 | redistributed and/or sold with any software, provided that each copy 58 | contains the above copyright notice and this license. These can be 59 | included either as stand-alone text files, human-readable headers or 60 | in the appropriate machine-readable metadata fields within text or 61 | binary files as long as those fields can be easily viewed by the user. 62 | 63 | 3) No Modified Version of the Font Software may use the Reserved Font 64 | Name(s) unless explicit written permission is granted by the corresponding 65 | Copyright Holder. This restriction only applies to the primary font name as 66 | presented to the users. 67 | 68 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 69 | Software shall not be used to promote, endorse or advertise any 70 | Modified Version, except to acknowledge the contribution(s) of the 71 | Copyright Holder(s) and the Author(s) or with their explicit written 72 | permission. 73 | 74 | 5) The Font Software, modified or unmodified, in part or in whole, 75 | must be distributed entirely under this license, and must not be 76 | distributed under any other license. The requirement for fonts to 77 | remain under this license does not apply to any document created 78 | using the Font Software. 79 | 80 | TERMINATION 81 | This license becomes null and void if any of the above conditions are 82 | not met. 83 | 84 | DISCLAIMER 85 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 86 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 87 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 88 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 89 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 90 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 91 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 92 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 93 | OTHER DEALINGS IN THE FONT SOFTWARE. 94 | -------------------------------------------------------------------------------- /lib/weapon/weapon_setting.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:math'; 3 | 4 | import 'package:flame/cache.dart'; 5 | import 'package:flame/components.dart'; 6 | import 'package:flame/sprite.dart'; 7 | 8 | import '../game/game_setting.dart'; 9 | 10 | class WeaponSetting { 11 | String label = ""; 12 | int cost = 0; 13 | late Vector2 size; 14 | late Vector2 bulletSize; 15 | double damage = 0; 16 | double range = 0; 17 | double fireInterval = 0; 18 | double rotateSpeed = pi * 2; 19 | 20 | /*r per sec */ 21 | double bulletSpeed = 0; 22 | 23 | /* d per sec */ 24 | 25 | double damageDelta = 0; 26 | double rangeDelta = 0; 27 | double fireIntervalDelta = 0; 28 | double rotateSpeedDelta = 0; 29 | double bulletSpeedDelta = 0; 30 | 31 | double currentDamage = 0; 32 | double currentBulletSpeed = 0; 33 | 34 | late final Sprite tower; 35 | late final List barrel = List.filled(3, null); 36 | late final List paths = List.filled(3, null); 37 | late final Sprite bullet; 38 | late final SpriteSheet explosion; 39 | late final Vector2 explosionSize; 40 | late final List explosionSprites; 41 | 42 | WeaponSetting.empty() {} 43 | 44 | fill(gameSetting, weaponParam, tileSize, weaponTower, images) async { 45 | label = weaponParam['label']; 46 | cost = weaponParam['cost']; 47 | range = weaponParam['range'] * tileSize; 48 | damage = weaponParam['damage']; 49 | currentDamage = damage; 50 | fireInterval = weaponParam['fireInterval']; 51 | rotateSpeed = pi * weaponParam['rotateSpeed']; 52 | bulletSpeed = tileSize * weaponParam['bulletSpeed']; 53 | currentBulletSpeed = bulletSpeed; 54 | size = gameSetting.scaleOnMapTile(Vector2(weaponParam['sizeX'], weaponParam['sizeY'])); 55 | bulletSize = gameSetting.scaleOnMapTile(Vector2(weaponParam['bulletSizeX'], weaponParam['bulletSizeY'])); 56 | explosionSize = gameSetting.scaleOnMapTile(Vector2(weaponParam['explosionSizeX'], weaponParam['explosionSizeY'])); 57 | tower = weaponTower; 58 | paths[0] = 'weapon/${weaponParam['barrelImg0']}.png'; 59 | paths[1] = 'weapon/${weaponParam['barrelImg1']}.png'; 60 | paths[2] = 'weapon/${weaponParam['barrelImg2']}.png'; 61 | barrel[0] = Sprite(await images.load(paths[0])); 62 | barrel[1] = Sprite(await images.load(paths[1])); 63 | barrel[2] = Sprite(await images.load(paths[2])); 64 | bullet = Sprite(await images.load('weapon/${weaponParam['bulletImg']}.png')); 65 | 66 | damageDelta = weaponParam['damageDelta']; 67 | rangeDelta = weaponParam['rangeDelta']; 68 | fireIntervalDelta = weaponParam['fireIntervalDelta']; 69 | rotateSpeedDelta = weaponParam['rotateSpeedDelta']; 70 | bulletSpeedDelta = weaponParam['bulletSpeedDelta']; 71 | } 72 | 73 | void createExpolosionAnimation(List frameLocation, double stepTime) { 74 | List sprites = []; 75 | frameLocation.forEach((v) => sprites.add(explosion.getSprite(v.x.toInt(), v.y.toInt()))); 76 | explosionSprites = sprites; 77 | // explosionAnimation = 78 | // SpriteAnimation.spriteList(sprites, stepTime: stepTime, loop: false); 79 | } 80 | } 81 | 82 | class WeaponSettingV1 { 83 | List weapon = []; 84 | 85 | WeaponSettingV1(); 86 | 87 | Future load(gameSetting) async { 88 | final images = Images(); 89 | Sprite weaponTower = Sprite(await images.load('weapon/Tower.png')); 90 | double tileSize = gameSetting.mapTileSize.length; 91 | 92 | String weaponParamsString = await loadAsset('assets/weaponParams.json'); 93 | final weaponParams = json.decode(weaponParamsString); 94 | 95 | // Preloading these fixes issue with GameBar not showing Missile_Launcher barrel 96 | for (var weaponParam in weaponParams) { 97 | await images.load('weapon/${weaponParam['barrelImg0']}.png'); 98 | } 99 | 100 | for (var weaponParam in weaponParams) { 101 | List expFrame = []; 102 | List vector2List = weaponParam['expFrame']; 103 | for (int i = 0; i < vector2List.length; i++) { 104 | List vector2 = vector2List[i]; 105 | expFrame.add(Vector2(vector2[0], vector2[1])); 106 | } 107 | 108 | WeaponSetting w = WeaponSetting.empty() 109 | ..explosion = SpriteSheet.fromColumnsAndRows( 110 | image: await images.load(weaponParam['explosionImage']), 111 | columns: weaponParam['columns'], 112 | rows: weaponParam['rows'], 113 | ); 114 | w.fill(gameSetting, weaponParam, tileSize, weaponTower, images); 115 | 116 | double explosionTimeStep = weaponParam['explosionTimeStep']; 117 | w.createExpolosionAnimation(expFrame, explosionTimeStep); 118 | weapon.add(w); 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /lib/spacescape/game/power_up_manager.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'package:flame/components.dart'; 4 | import 'package:flame/experimental.dart'; 5 | 6 | import 'game.dart'; 7 | import 'power_ups.dart'; 8 | 9 | typedef PowerUpMap 10 | = Map; 11 | 12 | // Represents the types of power up we have to offer. 13 | enum PowerUpTypes { health, freeze, nuke, multiFire } 14 | 15 | // This class/component is responsible for spawning random power ups 16 | // at random locations in the game world. 17 | class PowerUpManager extends Component with HasGameReference { 18 | // Controls the frequency of spawning power ups. 19 | late Timer _spawnTimer; 20 | 21 | // Controls the amount of time for which this component 22 | /// should be frozen when [Freeze] power is activated. 23 | late Timer _freezeTimer; 24 | 25 | // A random number generator. 26 | Random random = Random(); 27 | 28 | // Storing these static sprites so that 29 | // they stay alive across multiple restarts. 30 | static late Sprite nukeSprite; 31 | static late Sprite healthSprite; 32 | static late Sprite freezeSprite; 33 | static late Sprite multiFireSprite; 34 | 35 | // A private static map which stores a generator function for each power up. 36 | static final PowerUpMap _powerUpMap = { 37 | PowerUpTypes.health: (position, size) => Health( 38 | position: position, 39 | size: size, 40 | ), 41 | PowerUpTypes.freeze: (position, size) => Freeze( 42 | position: position, 43 | size: size, 44 | ), 45 | PowerUpTypes.nuke: (position, size) => Nuke( 46 | position: position, 47 | size: size, 48 | ), 49 | PowerUpTypes.multiFire: (position, size) => MultiFire( 50 | position: position, 51 | size: size, 52 | ), 53 | }; 54 | 55 | PowerUpManager() : super() { 56 | // Makes sure that a new power up is spawned every 5 seconds. 57 | _spawnTimer = Timer(5, onTick: _spawnPowerUp, repeat: true); 58 | 59 | // Restarts the spawn timer after 2 seconds are 60 | // elapsed from start of freeze timer. 61 | _freezeTimer = Timer(2, onTick: () { 62 | _spawnTimer.start(); 63 | }); 64 | } 65 | 66 | // This method is responsible for generating a 67 | // random power up at random location on the screen. 68 | void _spawnPowerUp() { 69 | Vector2 initialSize = Vector2(64, 64); 70 | Vector2 position = Vector2( 71 | random.nextDouble() * game.fixedResolution.x, 72 | random.nextDouble() * game.fixedResolution.y, 73 | ); 74 | 75 | // Clamp so that the power up does not 76 | // go outside the screen. 77 | position.clamp( 78 | Vector2.zero() + initialSize / 2, 79 | game.fixedResolution - initialSize / 2, 80 | ); 81 | 82 | // Returns a random integer from 0 to (PowerUpTypes.values.length - 1). 83 | int randomIndex = random.nextInt(PowerUpTypes.values.length); 84 | 85 | // Tried to get the generator function corresponding to selected random power. 86 | final fn = _powerUpMap[PowerUpTypes.values.elementAt(randomIndex)]; 87 | 88 | // If the generator function is valid call it and get the power up. 89 | var powerUp = fn?.call(position, initialSize); 90 | 91 | // If power up is valid, set anchor to center. 92 | powerUp?.anchor = Anchor.center; 93 | 94 | // If power up is valid, add it to game world. 95 | if (powerUp != null) { 96 | game.world.add(powerUp); 97 | } 98 | } 99 | 100 | @override 101 | void onMount() { 102 | // Start the spawn timer as soon as this component is mounted. 103 | _spawnTimer.start(); 104 | 105 | healthSprite = Sprite(game.images.fromCache('icon_plusSmall.png')); 106 | nukeSprite = Sprite(game.images.fromCache('nuke.png')); 107 | freezeSprite = Sprite(game.images.fromCache('freeze.png')); 108 | multiFireSprite = Sprite(game.images.fromCache('multi_fire.png')); 109 | 110 | super.onMount(); 111 | } 112 | 113 | @override 114 | void onRemove() { 115 | // Stop the spawn timer as soon as this component is removed. 116 | _spawnTimer.stop(); 117 | super.onRemove(); 118 | } 119 | 120 | @override 121 | void update(double dt) { 122 | _spawnTimer.update(dt); 123 | _freezeTimer.update(dt); 124 | super.update(dt); 125 | } 126 | 127 | // This method gets called when the game is being restarted. 128 | void reset() { 129 | // Stop all the timers. 130 | _spawnTimer.stop(); 131 | _spawnTimer.start(); 132 | } 133 | 134 | // This method gets called when freeze power is activated. 135 | void freeze() { 136 | // Stop the spawn timer. 137 | _spawnTimer.stop(); 138 | 139 | // Restart the freeze timer. 140 | _freezeTimer.stop(); 141 | _freezeTimer.start(); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /lib/spacescape/game/power_ups.dart: -------------------------------------------------------------------------------- 1 | import 'package:flame/collisions.dart'; 2 | import 'package:flame/components.dart'; 3 | import 'package:flame/experimental.dart'; 4 | 5 | import 'game.dart'; 6 | import 'enemy.dart'; 7 | import 'player.dart'; 8 | import 'command.dart'; 9 | import 'enemy_manager.dart'; 10 | import 'power_up_manager.dart'; 11 | import 'audio_player_component.dart'; 12 | 13 | // An abstract class which represents power ups in this game. 14 | /// See [Freeze], [Health], [MultiFire] and [Nuke] for example. 15 | abstract class PowerUp extends SpriteComponent 16 | with HasGameReference, CollisionCallbacks { 17 | // Controls how long the power up should be visible 18 | // before getting destroyed if not picked. 19 | late Timer _timer; 20 | 21 | // Abstract method which child classes should override 22 | /// and return a [Sprite] for the power up. 23 | Sprite getSprite(); 24 | 25 | // Abstract method which child classes should override 26 | // and perform any activation event necessary. 27 | void onActivated(); 28 | 29 | PowerUp({ 30 | Vector2? position, 31 | Vector2? size, 32 | Sprite? sprite, 33 | }) : super(position: position, size: size, sprite: sprite) { 34 | // Power ups will be displayed only for 3 seconds 35 | // before getting destroyed. 36 | _timer = Timer(3, onTick: removeFromParent); 37 | } 38 | 39 | @override 40 | void update(double dt) { 41 | _timer.update(dt); 42 | super.update(dt); 43 | } 44 | 45 | @override 46 | void onMount() { 47 | // Add a circular hit box for this power up. 48 | final shape = CircleHitbox.relative( 49 | 0.5, 50 | parentSize: size, 51 | position: size / 2, 52 | anchor: Anchor.center, 53 | ); 54 | add(shape); 55 | 56 | // Set the correct sprite by calling overriden getSprite method. 57 | sprite = getSprite(); 58 | 59 | // Start the timer. 60 | _timer.start(); 61 | super.onMount(); 62 | } 63 | 64 | @override 65 | void onCollision(Set intersectionPoints, PositionComponent other) { 66 | // If the other entity is Player, call the overriden 67 | // onActivated method and mark this component to be removed. 68 | if (other is Player) { 69 | // Ask audio player to play power up activation effect. 70 | game.addCommand(Command(action: (audioPlayer) { 71 | audioPlayer.playSfx('powerUp6.ogg'); 72 | })); 73 | onActivated(); 74 | removeFromParent(); 75 | } 76 | 77 | super.onCollision(intersectionPoints, other); 78 | } 79 | } 80 | 81 | // This power up nukes all the enemies. 82 | class Nuke extends PowerUp { 83 | Nuke({Vector2? position, Vector2? size}) 84 | : super(position: position, size: size); 85 | 86 | @override 87 | Sprite getSprite() { 88 | return PowerUpManager.nukeSprite; 89 | } 90 | 91 | @override 92 | void onActivated() { 93 | // Register a command to destory all enemies. 94 | final command = Command(action: (enemy) { 95 | enemy.destroy(); 96 | }); 97 | game.addCommand(command); 98 | } 99 | } 100 | 101 | // This power up increases player health by 10. 102 | class Health extends PowerUp { 103 | Health({Vector2? position, Vector2? size}) 104 | : super(position: position, size: size); 105 | 106 | @override 107 | Sprite getSprite() { 108 | return PowerUpManager.healthSprite; 109 | } 110 | 111 | @override 112 | void onActivated() { 113 | // Register a command to increase player health. 114 | final command = Command(action: (player) { 115 | player.increaseHealthBy(10); 116 | }); 117 | game.addCommand(command); 118 | } 119 | } 120 | 121 | // This power up freezes all enemies for some time. 122 | class Freeze extends PowerUp { 123 | Freeze({Vector2? position, Vector2? size}) 124 | : super(position: position, size: size); 125 | 126 | @override 127 | Sprite getSprite() { 128 | return PowerUpManager.freezeSprite; 129 | } 130 | 131 | @override 132 | void onActivated() { 133 | // Register a command to freeze all enemies. 134 | final command1 = Command(action: (enemy) { 135 | enemy.freeze(); 136 | }); 137 | game.addCommand(command1); 138 | 139 | /// Register a command to freeze [EnemyManager]. 140 | final command2 = Command(action: (enemyManager) { 141 | enemyManager.freeze(); 142 | }); 143 | game.addCommand(command2); 144 | 145 | /// Register a command to freeze [PowerUpManager]. 146 | final command3 = Command(action: (powerUpManager) { 147 | powerUpManager.freeze(); 148 | }); 149 | game.addCommand(command3); 150 | } 151 | } 152 | 153 | // This power up activate multi-fire for some time. 154 | class MultiFire extends PowerUp { 155 | MultiFire({Vector2? position, Vector2? size}) 156 | : super(position: position, size: size); 157 | 158 | @override 159 | Sprite getSprite() { 160 | return PowerUpManager.multiFireSprite; 161 | } 162 | 163 | @override 164 | void onActivated() { 165 | // Register a command to allow multiple bullets. 166 | final command = Command(action: (player) { 167 | player.shootMultipleBullets(); 168 | }); 169 | game.addCommand(command); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /linux/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Project-level configuration. 2 | cmake_minimum_required(VERSION 3.10) 3 | project(runner LANGUAGES CXX) 4 | 5 | # The name of the executable created for the application. Change this to change 6 | # the on-disk name of your application. 7 | set(BINARY_NAME "free_defense") 8 | # The unique GTK application identifier for this application. See: 9 | # https://wiki.gnome.org/HowDoI/ChooseApplicationID 10 | set(APPLICATION_ID "com.example.free_defense") 11 | 12 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent 13 | # versions of CMake. 14 | cmake_policy(SET CMP0063 NEW) 15 | 16 | # Load bundled libraries from the lib/ directory relative to the binary. 17 | set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") 18 | 19 | # Root filesystem for cross-building. 20 | if(FLUTTER_TARGET_PLATFORM_SYSROOT) 21 | set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) 22 | set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) 23 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 24 | set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) 25 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 26 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 27 | endif() 28 | 29 | # Define build configuration options. 30 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 31 | set(CMAKE_BUILD_TYPE "Debug" CACHE 32 | STRING "Flutter build mode" FORCE) 33 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 34 | "Debug" "Profile" "Release") 35 | endif() 36 | 37 | # Compilation settings that should be applied to most targets. 38 | # 39 | # Be cautious about adding new options here, as plugins use this function by 40 | # default. In most cases, you should add new options to specific targets instead 41 | # of modifying this function. 42 | function(APPLY_STANDARD_SETTINGS TARGET) 43 | target_compile_features(${TARGET} PUBLIC cxx_std_14) 44 | target_compile_options(${TARGET} PRIVATE -Wall -Werror) 45 | target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") 46 | target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") 47 | endfunction() 48 | 49 | # Flutter library and tool build rules. 50 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 51 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 52 | 53 | # System-level dependencies. 54 | find_package(PkgConfig REQUIRED) 55 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) 56 | 57 | add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") 58 | 59 | # Define the application target. To change its name, change BINARY_NAME above, 60 | # not the value here, or `flutter run` will no longer work. 61 | # 62 | # Any new source files that you add to the application should be added here. 63 | add_executable(${BINARY_NAME} 64 | "main.cc" 65 | "my_application.cc" 66 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 67 | ) 68 | 69 | # Apply the standard set of build settings. This can be removed for applications 70 | # that need different build settings. 71 | apply_standard_settings(${BINARY_NAME}) 72 | 73 | # Add dependency libraries. Add any application-specific dependencies here. 74 | target_link_libraries(${BINARY_NAME} PRIVATE flutter) 75 | target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) 76 | 77 | # Run the Flutter tool portions of the build. This must not be removed. 78 | add_dependencies(${BINARY_NAME} flutter_assemble) 79 | 80 | # Only the install-generated bundle's copy of the executable will launch 81 | # correctly, since the resources must in the right relative locations. To avoid 82 | # people trying to run the unbundled copy, put it in a subdirectory instead of 83 | # the default top-level location. 84 | set_target_properties(${BINARY_NAME} 85 | PROPERTIES 86 | RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" 87 | ) 88 | 89 | 90 | # Generated plugin build rules, which manage building the plugins and adding 91 | # them to the application. 92 | include(flutter/generated_plugins.cmake) 93 | 94 | 95 | # === Installation === 96 | # By default, "installing" just makes a relocatable bundle in the build 97 | # directory. 98 | set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") 99 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 100 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 101 | endif() 102 | 103 | # Start with a clean build bundle directory every time. 104 | install(CODE " 105 | file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") 106 | " COMPONENT Runtime) 107 | 108 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 109 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") 110 | 111 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 112 | COMPONENT Runtime) 113 | 114 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 115 | COMPONENT Runtime) 116 | 117 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 118 | COMPONENT Runtime) 119 | 120 | foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) 121 | install(FILES "${bundled_library}" 122 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 123 | COMPONENT Runtime) 124 | endforeach(bundled_library) 125 | 126 | # Copy the native assets provided by the build.dart from all packages. 127 | set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") 128 | install(DIRECTORY "${NATIVE_ASSETS_DIR}" 129 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 130 | COMPONENT Runtime) 131 | 132 | # Fully re-copy the assets directory on each build to avoid having stale files 133 | # from a previous install. 134 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 135 | install(CODE " 136 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 137 | " COMPONENT Runtime) 138 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 139 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 140 | 141 | # Install the AOT library on non-Debug builds only. 142 | if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") 143 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 144 | COMPONENT Runtime) 145 | endif() 146 | -------------------------------------------------------------------------------- /lib/astar/astarmap.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * canvas-astar.dart 3 | * MIT licensed 4 | * 5 | * Created by Daniel Imms, http://www.growingwiththeweb.com 6 | */ 7 | 8 | import 'dart:math' as math; 9 | import 'astarnode.dart'; 10 | import 'array2d.dart'; 11 | 12 | class AstarMap { 13 | final double costStraight = 1.0; 14 | final double costDiagnal = 1.414; // approximation of sqrt(2) 15 | 16 | late Array2d obstacleMap; 17 | int width; 18 | int height; 19 | 20 | AstarMap(this.width, this.height) { 21 | initObstacleMap(); 22 | } 23 | 24 | bool isOnMap(int x, int y) => x >= 0 && x < width && y >= 0 && y < height; 25 | 26 | void initObstacleMap() { 27 | obstacleMap = new Array2d(width, height, defaultValue: true); 28 | } 29 | 30 | void addObstacle(int x, int y) { 31 | obstacleMap[x][y] = false; 32 | } 33 | 34 | void removeObstacle(int x, int y) { 35 | obstacleMap[x][y] = true; 36 | } 37 | 38 | AstarNode? astar(AstarNode start, AstarNode goal) { 39 | List closed = []; 40 | List open = [start]; 41 | 42 | open.first.f = open.first.g + heuristic(open.first, goal); 43 | 44 | while (open.length > 0) { 45 | var lowestF = 0; 46 | for (var i = 1; i < open.length; i++) { 47 | if (open[i].f < open[lowestF].f) { 48 | lowestF = i; 49 | } 50 | } 51 | AstarNode current = open[lowestF]; 52 | 53 | if (current == goal) { 54 | // var info = 'Map size = ${width}x$height' + 55 | // 'Total number of nodes = ${width * height}' + 56 | // 'Number of nodes in open list = ${open.length}' + 57 | // 'Number of nodes in closed list = ${closed.length}'; 58 | // print(info); 59 | return current; 60 | } 61 | 62 | open.removeAt(lowestF); 63 | closed.add(current); 64 | 65 | List neighbors = neighborNodes(current); 66 | for (var i = 0; i < neighbors.length; i++) { 67 | if (indexOfNode(closed, neighbors[i]) == -1) { 68 | // Skip if in closed list 69 | var index = indexOfNode(open, neighbors[i]); 70 | if (index == -1) { 71 | neighbors[i].f = neighbors[i].g + heuristic(neighbors[i], goal); 72 | open.add(neighbors[i]); 73 | } else if (neighbors[i].g < open[index].g) { 74 | neighbors[i].f = neighbors[i].g + heuristic(neighbors[i], goal); 75 | open[index] = neighbors[i]; 76 | } 77 | } 78 | } 79 | } 80 | 81 | return null; 82 | } 83 | 84 | List neighborNodes(AstarNode n) { 85 | List neighbors = []; 86 | 87 | if (n.x > 0) { 88 | if (isOnMap(n.x - 1, n.y) && obstacleMap[n.x - 1][n.y]) 89 | neighbors 90 | .add(new AstarNode(n.x - 1, n.y, parent: n, cost: costStraight)); 91 | if (n.y > 0 && 92 | isOnMap(n.x - 1, n.y - 1) && 93 | obstacleMap[n.x - 1][n.y - 1]) { 94 | if (isOnMap(n.x - 1, n.y) && 95 | isOnMap(n.x, n.y - 1) && 96 | obstacleMap[n.x - 1][n.y] && 97 | obstacleMap[n.x][n.y - 1]) 98 | neighbors.add( 99 | new AstarNode(n.x - 1, n.y - 1, parent: n, cost: costDiagnal)); 100 | } 101 | if (n.y < height && 102 | isOnMap(n.x - 1, n.y + 1) && 103 | obstacleMap[n.x - 1][n.y + 1]) { 104 | if (isOnMap(n.x - 1, n.y) && 105 | isOnMap(n.x, n.y + 1) && 106 | obstacleMap[n.x - 1][n.y] && 107 | obstacleMap[n.x][n.y + 1]) 108 | neighbors.add( 109 | new AstarNode(n.x - 1, n.y + 1, parent: n, cost: costDiagnal)); 110 | } 111 | } 112 | if (n.x < width - 1) { 113 | if (isOnMap(n.x + 1, n.y) && obstacleMap[n.x + 1][n.y]) 114 | neighbors 115 | .add(new AstarNode(n.x + 1, n.y, parent: n, cost: costStraight)); 116 | if (n.y > 0 && 117 | isOnMap(n.x + 1, n.y - 1) && 118 | obstacleMap[n.x + 1][n.y - 1]) { 119 | if (isOnMap(n.x + 1, n.y) && 120 | isOnMap(n.x, n.y - 1) && 121 | obstacleMap[n.x + 1][n.y] && 122 | obstacleMap[n.x][n.y - 1]) 123 | neighbors.add( 124 | new AstarNode(n.x + 1, n.y - 1, parent: n, cost: costDiagnal)); 125 | } 126 | if (n.y < height && 127 | isOnMap(n.x + 1, n.y + 1) && 128 | obstacleMap[n.x + 1][n.y + 1]) { 129 | if (isOnMap(n.x + 1, n.y) && 130 | isOnMap(n.x, n.y + 1) && 131 | obstacleMap[n.x + 1][n.y] && 132 | obstacleMap[n.x][n.y + 1]) 133 | neighbors.add( 134 | new AstarNode(n.x + 1, n.y + 1, parent: n, cost: costDiagnal)); 135 | } 136 | } 137 | if (n.y > 0 && isOnMap(n.x, n.y - 1) && obstacleMap[n.x][n.y - 1]) 138 | neighbors.add(new AstarNode(n.x, n.y - 1, parent: n, cost: costStraight)); 139 | if (n.y < height - 1 && isOnMap(n.x, n.y + 1) && obstacleMap[n.x][n.y + 1]) 140 | neighbors.add(new AstarNode(n.x, n.y + 1, parent: n, cost: costStraight)); 141 | 142 | return neighbors; 143 | } 144 | 145 | int indexOfNode(List array, AstarNode node) { 146 | for (var i = 0; i < array.length; i++) { 147 | if (node == array[i]) return i; 148 | } 149 | return -1; 150 | } 151 | 152 | num heuristic(node, goal) { 153 | return diagonalDistance(node, goal); 154 | } 155 | 156 | num manhattanDistance(node, goal) { 157 | return (node.x - goal.x).abs() + (node.y - goal.y).abs(); 158 | } 159 | 160 | num diagonalUniformDistance(node, goal) { 161 | return math.max((node.x - goal.x).abs(), (node.y - goal.y).abs()); 162 | } 163 | 164 | num diagonalDistance(AstarNode node, AstarNode goal) { 165 | var dmin = math.min((node.x - goal.x).abs(), (node.y - goal.y).abs()); 166 | var dmax = math.max((node.x - goal.x).abs(), (node.y - goal.y).abs()); 167 | return costDiagnal * dmin + costStraight * (dmax - dmin); 168 | } 169 | 170 | num euclideanDistance(node, goal) { 171 | return math.sqrt((node.x - goal.x).abs() ^ 2 + (node.y - goal.y).abs() ^ 2); 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /lib/view/weapon_factory_view.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | 3 | import 'package:flame/components.dart'; 4 | import 'package:flame/events.dart'; 5 | import 'package:flame/input.dart'; 6 | import 'package:freedefense/base/game_component.dart'; 7 | import 'package:freedefense/game/game_controller.dart'; 8 | import 'package:freedefense/game/game_setting.dart'; 9 | import 'package:freedefense/view/mine_view.dart'; 10 | import 'package:freedefense/weapon/cannon.dart'; 11 | import 'package:freedefense/weapon/machine_gun.dart'; 12 | import 'package:freedefense/weapon/missile.dart'; 13 | import 'package:freedefense/weapon/weapon_component.dart'; 14 | 15 | GameSetting gameSetting = GameSetting(); 16 | 17 | class WeaponFactoryView extends GameComponent { 18 | late SingleWeaponView selectedWeapon; 19 | WeaponComponent? buildWeapon(Vector2 anchor) { 20 | if (selectedWeapon.mineEnough) 21 | return selectedWeapon.build(anchor); 22 | else { 23 | return null; 24 | } 25 | } 26 | 27 | WeaponFactoryView() 28 | : super( 29 | position: Vector2(gameSetting.viewSize.x * (1 / 3), gameSetting.viewPosition.y), 30 | size: Vector2( 31 | gameSetting.viewSize.x * (2 / 3) - gameSetting.mapTileSize.x, gameSetting.viewSize.y * (2 / 3))); 32 | 33 | List weapons = []; 34 | 35 | @override 36 | Future? onLoad() async { 37 | await super.onLoad(); 38 | weapons.add(_loadSingleView(0, WeaponType.CANNON)); 39 | weapons.add(_loadSingleView(1, WeaponType.MG)); 40 | weapons.add(_loadSingleView(2, WeaponType.MISSILE)); 41 | // weapons.add(_loadSingleView(3, WeaponType.MINNER)); 42 | select(weapons[0]); 43 | } 44 | 45 | SingleWeaponView _loadSingleView(int slot, WeaponType type) { 46 | SingleWeaponView view = SingleWeaponView( 47 | position: Vector2(size.x * (slot / 3 + 1 / 4), size.y / 3), 48 | size: Vector2(size.x / 4, size.y), 49 | weaponType: type); 50 | add(view); 51 | return view; 52 | } 53 | 54 | SingleWeaponView select(SingleWeaponView target) { 55 | selectedWeapon = target; 56 | weapons.forEach((e) { 57 | if (e == target) { 58 | e.selected = true; 59 | } else { 60 | e.selected = false; 61 | } 62 | }); 63 | return target; 64 | } 65 | 66 | int onBuildDone(WeaponComponent c) { 67 | weapons[c.weaponType.index].count++; 68 | gameRef.gamebarView.mineCollected -= weapons[c.weaponType.index].cost; 69 | 70 | return weapons[c.weaponType.index].count; 71 | } 72 | 73 | int onDestroy(WeaponComponent c) { 74 | weapons[c.weaponType.index].count--; 75 | return weapons[c.weaponType.index].count; 76 | } 77 | } 78 | 79 | class SingleWeaponView extends GameComponent with TapCallbacks { 80 | SingleWeaponView({required Vector2 position, required Vector2 size, required this.weaponType}) 81 | : super(position: position, size: size) { 82 | _baseCost = GameSetting().weapons.weapon[weaponType.index].cost; 83 | costDelta = _baseCost * 0.2; 84 | count = 0; 85 | } 86 | WeaponType weaponType; 87 | int _baseCost = 0; 88 | int cost = 0; 89 | int _count = 0; 90 | double costDelta = 0; 91 | bool mineEnough = false; 92 | 93 | int get count => _count; 94 | set count(int c) { 95 | _count = c; 96 | cost = _baseCost + (_count * costDelta).toInt(); 97 | } 98 | 99 | late WeaponComponent weapon; 100 | late MineView mine; 101 | @override 102 | FutureOr? onLoad() { 103 | Vector2 base = gameSetting.mapTileSize * 0.9; 104 | Vector2 center = size / 2, wp, ws, mp, ms; 105 | if (size.x >= size.y) { 106 | wp = Vector2(center.x - (base.x * 1.5 / 6), center.y); 107 | ws = base; 108 | mp = Vector2(center.x + (base.x * 3 / 6), center.y); 109 | ms = Vector2(base.x / 2, base.y); 110 | } else { 111 | wp = Vector2(center.x, center.y - (base.y * 1.5 / 6)); 112 | ws = base; 113 | mp = Vector2(center.x, center.y + (base.y * 3 / 6)); 114 | ms = Vector2(base.x, base.y / 2); 115 | } 116 | 117 | weapon = build(wp) 118 | ..size = ws 119 | ..buildDone = true 120 | ..dialogVisible = false 121 | ..active = false; 122 | mine = MineView(position: mp, size: ms); 123 | 124 | add(weapon); 125 | add(mine); 126 | return super.onLoad(); 127 | } 128 | 129 | bool _selected = false; 130 | bool get selected => _selected; 131 | set selected(bool b) { 132 | _selected = b; 133 | if (_selected) { 134 | _setOpacity(this, 1.0); 135 | } else { 136 | _setOpacity(this, 0.4); 137 | mine.maskGreen = null; 138 | } 139 | } 140 | 141 | void _setOpacity(GameComponent c, double o) { 142 | c.setOpacity(o); 143 | if (c.children.length > 0) { 144 | c.children.forEach((e) { 145 | if (e is GameComponent) _setOpacity(e, o); 146 | }); 147 | } 148 | } 149 | 150 | WeaponComponent build(Vector2 anchor) { 151 | late WeaponComponent weapon; 152 | switch (weaponType) { 153 | case WeaponType.CANNON: 154 | weapon = Cannon(position: anchor, weaponSetting: GameSetting().weapons.weapon[WeaponType.CANNON.index]); 155 | break; 156 | case WeaponType.MG: 157 | weapon = MachineGun(position: anchor, weaponSetting: GameSetting().weapons.weapon[WeaponType.MG.index]); 158 | break; 159 | case WeaponType.MISSILE: 160 | weapon = Missile(position: anchor, weaponSetting: GameSetting().weapons.weapon[WeaponType.MISSILE.index]); 161 | break; 162 | default: 163 | break; 164 | } 165 | return weapon; 166 | } 167 | 168 | @override 169 | bool onTapDown(TapDownEvent event) { 170 | if (selected) { 171 | gameRef.gameController.send(this, GameControl.WEAPON_SHOW_PROFILE); 172 | } else { 173 | gameRef.gameController.send(this, GameControl.WEAPON_SELECTED); 174 | } 175 | return false; 176 | } 177 | 178 | @override 179 | void update(double t) { 180 | int collectedMine = gameRef.gamebarView.mine.number; 181 | if (collectedMine >= cost) { 182 | mineEnough = true; 183 | } else { 184 | mineEnough = false; 185 | } 186 | 187 | mine.number = cost; 188 | 189 | if (selected) { 190 | mine.maskGreen = mineEnough; 191 | } 192 | super.update(t); 193 | } 194 | } 195 | --------------------------------------------------------------------------------