diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 02d4d62..ea32e54 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -3,26 +3,110 @@ import { defineConfig } from 'vitepress' // https://vitepress.dev/reference/site-config export default defineConfig({ title: "GFramework", - description: "A developer-oriented framework for structured game development", + description: "面向游戏开发场景的模块化 C# 框架", + base: "/GFramework/", themeConfig: { // https://vitepress.dev/reference/default-theme-config nav: [ - { text: 'Home', link: '/' }, - { text: 'Examples', link: '/markdown-examples' } + { text: '首页', link: '/' }, + { text: '入门指南', link: '/getting-started/installation' }, + { text: 'Core', link: '/core/overview' }, + { text: 'Game', link: '/game/overview' }, + { text: 'Godot', link: '/godot/overview' }, + { text: '源码生成器', link: '/source-generators/overview' }, + { text: '教程', link: '/tutorials/basic-tutorial' }, + { text: 'API参考', link: '/api-reference/core-api' } ], - sidebar: [ - { - text: 'Examples', - items: [ - { text: 'Markdown Examples', link: '/markdown-examples' }, - { text: 'Runtime API Examples', link: '/api-examples' } - ] - } - ], + sidebar: { + '/getting-started/': [ + { + text: '入门指南', + items: [ + { text: '安装配置', link: '/getting-started/installation' }, + { text: '快速开始', link: '/getting-started/quick-start' }, + { text: '架构概览', link: '/getting-started/architecture-overview' } + ] + } + ], + '/core/': [ + { + text: 'Core 核心框架', + items: [ + { text: '概览', link: '/core/overview' }, + { text: '架构组件', link: '/core/architecture/architecture' }, + { text: '命令查询系统', link: '/core/command-query/commands' }, + { text: '事件系统', link: '/core/events/event-bus' }, + { text: '属性系统', link: '/core/property/bindable-property' }, + { text: '工具类', link: '/core/utilities/ioc-container' } + ] + } + ], + '/game/': [ + { + text: 'Game 游戏模块', + items: [ + { text: '概览', link: '/game/overview' }, + { text: '模块系统', link: '/game/modules/architecture-modules' }, + { text: '存储系统', link: '/game/storage/scoped-storage' }, + { text: '资源管理', link: '/game/assets/asset-catalog' }, + { text: '序列化', link: '/game/serialization/json-serializer' } + ] + } + ], + '/godot/': [ + { + text: 'Godot 集成', + items: [ + { text: '概览', link: '/godot/overview' }, + { text: '集成指南', link: '/godot/integration/architecture-integration' }, + { text: '节点扩展', link: '/godot/node-extensions/node-extensions' }, + { text: '对象池', link: '/godot/pooling/node-pool' }, + { text: '日志系统', link: '/godot/logging/godot-logger' } + ] + } + ], + '/source-generators/': [ + { + text: '源码生成器', + items: [ + { text: '概览', link: '/source-generators/overview' }, + { text: '日志生成器', link: '/source-generators/logging-generator' }, + { text: '枚举扩展', link: '/source-generators/enum-extensions' }, + { text: '规则生成器', link: '/source-generators/rule-generator' } + ] + } + ], + '/tutorials/': [ + { + text: '教程', + items: [ + { text: '基础教程', link: '/tutorials/basic-tutorial' }, + { text: '高级模式', link: '/tutorials/advanced-patterns' }, + { text: '最佳实践', link: '/tutorials/best-practices' } + ] + } + ], + '/api-reference/': [ + { + text: 'API 参考', + items: [ + { text: 'Core API', link: '/api-reference/core-api' }, + { text: 'Game API', link: '/api-reference/game-api' }, + { text: 'Godot API', link: '/api-reference/godot-api' }, + { text: '生成器 API', link: '/api-reference/generators-api' } + ] + } + ] + }, socialLinks: [ - { icon: 'github', link: 'https://github.com/vuejs/vitepress' } - ] + { icon: 'github', link: 'https://github.com/GeWuYou/GFramework' } + ], + + footer: { + message: '基于 Apache 2.0 许可证发布', + copyright: 'Copyright © 2026 GeWuYou' + } } }) diff --git a/docs/api-examples.md b/docs/api-examples.md deleted file mode 100644 index a3ead20..0000000 --- a/docs/api-examples.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -outline: deep ---- - -# Runtime API Examples - -This page demonstrates usage of some of the runtime APIs provided by VitePress. - -The main `useData()` API can be used to access site, theme, and page data for the current page. It works in both `.md` -and `.vue` files: - -```md - - -## Results - -### Theme Data - -
{{ theme }}
- -### Page Data - -
{{ page }}
- -### Page Frontmatter - -
{{ frontmatter }}
-``` - - - -## Results - -### Theme Data - -
{{ theme }}
- -### Page Data - -
{{ page }}
- -### Page Frontmatter - -
{{ frontmatter }}
- -## More - -Check out the documentation for the [full list of runtime APIs](https://vitepress.dev/reference/runtime-api#usedata). diff --git a/docs/core/overview.md b/docs/core/overview.md new file mode 100644 index 0000000..9b60350 --- /dev/null +++ b/docs/core/overview.md @@ -0,0 +1,140 @@ +# Core 核心框架概览 + +GFramework.Core 是整个框架的基础,提供了平台无关的核心架构能力。 + +## 核心特性 + +### 🏗️ 清洁架构 + +基于 Model-View-Controller-System-Utility 五层架构,实现清晰的职责分离和高内聚低耦合。 + +### 🔧 CQRS 模式 + +命令查询职责分离,提供类型安全的命令和查询系统,支持可撤销操作。 + +### 📡 事件驱动 + +强大的事件总线系统,支持类型安全的事件发布订阅,实现组件间松耦合通信。 + +### 🔄 响应式编程 + +可绑定属性系统,自动化的数据绑定和 UI 更新机制。 + +### 🎯 依赖注入 + +完善的 IoC 容器,支持自动依赖解析和生命周期管理。 + +## 核心组件 + +### 架构组件 + +- **[Architecture](/core/architecture/architecture)** - 应用架构管理器 +- **AbstractModel** - 数据模型基类 +- **AbstractSystem** - 业务系统基类 +- **AbstractUtility** - 工具类基类 + +### 命令查询系统 + +- **[AbstractCommand](/core/command-query/commands)** - 命令基类 +- **AbstractQuery** - 查询基类 +- **CommandExecutor** - 命令执行器 + +### 事件系统 + +- **[EventBus](/core/events/event-bus)** - 事件总线 +- **EasyEvent** - 简单事件 +- **OrEvent** - 组合事件 + +### 属性系统 + +- **[BindableProperty](/core/property/bindable-property)** - 可绑定属性 +- **BindablePropertyGeneric** - 泛型可绑定属性 + +### 工具类 + +- **[IoC 容器](/core/utilities/ioc-container)** - 依赖注入容器 +- **Logger** - 日志系统 +- **ObjectPool** - 对象池 + +## 使用场景 + +Core 模块适用于任何 .NET 应用场景: + +- **游戏开发** - 作为游戏架构基础 +- **桌面应用** - WPF、WinForms 应用 +- **移动应用** - MAUI、Xamarin 应用 +- **Web 应用** - ASP.NET Core 应用 +- **控制台应用** - 命令行工具 + +## 安装 + +```bash +dotnet add package GeWuYou.GFramework.Core +dotnet add package GeWuYou.GFramework.Core.Abstractions +``` + +## 快速示例 + +```csharp +using GFramework.Core.architecture; + +// 定义架构 +public class MyAppArchitecture : Architecture +{ + protected override void Init() + { + RegisterModel(new UserModel()); + RegisterSystem(new UserService()); + RegisterUtility(new StorageUtility()); + } +} + +// 定义模型 +public class UserModel : AbstractModel +{ + public BindableProperty Name { get; } = new("User"); + public BindableProperty Score { get; } = new(0); +} + +// 使用架构 +var architecture = new MyAppArchitecture(); +architecture.Initialize(); + +var userModel = architecture.GetModel(); +userModel.Name.Value = "New Name"; // 自动触发更新 +``` + +## 学习路径 + +建议按以下顺序学习 Core 模块: + +1. **[架构基础](/core/architecture/architecture)** - 了解架构组件和生命周期 +2. **[命令查询](/core/command-query/commands)** - 掌握 CQRS 模式 +3. **[事件系统](/core/events/event-bus)** - 学习事件驱动编程 +4. **[属性系统](/core/property/bindable-property)** - 理解响应式编程 +5. **[工具类](/core/utilities/ioc-container)** - 使用辅助工具 + +## 与其他模块的关系 + +``` +GFramework.Core (基础层) + ↓ 依赖 +GFramework.Game (游戏层) + ↓ 依赖 +GFramework.Godot (引擎层) +``` + +Core 模块是其他所有模块的基础,提供核心的架构能力和设计模式实现。 + +## 性能特点 + +- **零额外开销** - 编译时优化,运行时无性能损失 +- **内存友好** - 自动内存管理和对象回收 +- **类型安全** - 编译时类型检查,避免运行时错误 +- **可扩展** - 支持自定义扩展和插件 + +## 下一步 + +- [深入了解架构组件](/core/architecture/architecture) +- [查看完整 API 参考](/api-reference/core-api) +- [学习最佳实践](/tutorials/best-practices) \ No newline at end of file diff --git a/docs/game/overview.md b/docs/game/overview.md new file mode 100644 index 0000000..60d7d8a --- /dev/null +++ b/docs/game/overview.md @@ -0,0 +1,138 @@ +# Game 游戏模块概览 + +GFramework.Game 为游戏开发提供专门的功能模块,包括资产管理、存储系统、序列化等核心游戏功能。 + +## 核心特性 + +### 🎮 游戏专用模块 + +- **架构模块系统** - 可插拔的游戏功能模块 +- **资产管理** - 统一的资源注册和查询系统 +- **存储系统** - 分层的数据持久化方案 +- **序列化** - 高性能的数据序列化支持 + +### 🏗️ 模块化设计 + +```csharp +public class AudioModule : AbstractModule +{ + public override void Install(IArchitecture architecture) + { + architecture.RegisterSystem(new AudioSystem()); + architecture.RegisterUtility(new AudioUtility()); + } +} +``` + +## 核心组件 + +### 模块系统 + +- **AbstractModule** - 模块基类 +- **ArchitectureModule** - 架构模块接口 +- **ModuleManager** - 模块管理器 + +### 存储系统 + +- **[ScopedStorage](/game/storage/scoped-storage)** - 分层存储 +- **IStorage** - 存储接口 +- **FileStorage** - 文件存储实现 + +### 资源管理 + +- **[AbstractAssetCatalogUtility](/game/assets/asset-catalog)** - 资源目录 +- **AssetFactory** - 资源工厂 +- **ResourceLoader** - 资源加载器 + +### 序列化 + +- **[JsonSerializer](/game/serialization/json-serializer)** - JSON 序列化 +- **BinarySerializer** - 二进制序列化 +- **CustomSerializer** - 自定义序列化 + +## 使用场景 + +Game 模块专为游戏开发设计: + +- **2D/3D 游戏** - 支持各种类型的游戏项目 +- **存档系统** - 完善的存档和读档功能 +- **资源配置** - 集中的资源管理和加载 +- **数据持久化** - 游戏数据的保存和恢复 + +## 安装 + +```bash +# 需要先安装 Core 模块 +dotnet add package GeWuYou.GFramework.Core +dotnet add package GeWuYou.GFramework.Game +dotnet add package GeWuYou.GFramework.Game.Abstractions +``` + +## 快速示例 + +```csharp +using GFramework.Game.storage; +using GFramework.Game.assets; + +// 存储系统使用 +public class GameDataManager +{ + private IStorage _playerStorage; + + public GameDataManager(IStorage rootStorage) + { + _playerStorage = new ScopedStorage(rootStorage, "player"); + } + + public void SavePlayerData(PlayerData data) + { + _playerStorage.Write("profile", data); + _playerStorage.Write("inventory", data.Inventory); + } +} + +// 资源管理使用 +public class GameAssetCatalog : AbstractAssetCatalogUtility +{ + public override void Initialize() + { + RegisterSceneUnit("Player", "res://scenes/Player.tscn"); + RegisterAsset("PlayerTexture", "res://textures/player.png"); + } +} +``` + +## 学习路径 + +建议按以下顺序学习 Game 模块: + +1. **[模块系统](/game/modules/architecture-modules)** - 了解模块化架构 +2. **[存储系统](/game/storage/scoped-storage)** - 掌握数据持久化 +3. **[资源管理](/game/assets/asset-catalog)** - 学习资源处理 +4. **[序列化](/game/serialization/json-serializer)** - 理解数据序列化 + +## 与 Core 的关系 + +``` +GFramework.Core (提供基础架构) + ↓ 扩展 +GFramework.Game (提供游戏功能) + ↓ 集成 +GFramework.Godot (提供引擎支持) +``` + +Game 模块建立在 Core 模块之上,为游戏开发提供专门的功能支持。 + +## 性能优化 + +- **缓存机制** - 智能缓存减少重复加载 +- **批量操作** - 支持批量数据处理 +- **异步支持** - 非阻塞的 I/O 操作 +- **内存管理** - 自动资源回收和管理 + +## 下一步 + +- [深入了解模块系统](/game/modules/architecture-modules) +- [查看存储系统文档](/game/storage/scoped-storage) +- [学习资源管理](/game/assets/asset-catalog) +- [查看 API 参考](/api-reference/game-api) \ No newline at end of file diff --git a/docs/getting-started/architecture-overview.md b/docs/getting-started/architecture-overview.md new file mode 100644 index 0000000..7ecc806 --- /dev/null +++ b/docs/getting-started/architecture-overview.md @@ -0,0 +1,354 @@ +# 架构概览 + +GFramework 采用经典的五层架构模式,结合 CQRS 和事件驱动设计,为游戏开发提供清晰、可维护的架构基础。 + +## 核心架构模式 + +### 五层架构 + +``` +┌─────────────────────────────────────────┐ +│ View / UI │ ← 用户界面层 +├─────────────────────────────────────────┤ +│ Controller │ ← 控制层 +├─────────────────────────────────────────┤ +│ System │ ← 业务逻辑层 +├─────────────────────────────────────────┤ +│ Model │ ← 数据层 +├─────────────────────────────────────────┤ +│ Utility │ ← 工具层 +└─────────────────────────────────────────┘ +``` + +### 跨层操作机制 + +``` +Command ──┐ +Query ──┼──→ 跨层操作(修改/查询数据) +Event ──┘ +``` + +### 生命周期阶段 + +``` +初始化:Init → BeforeUtilityInit → AfterUtilityInit → BeforeModelInit → AfterModelInit → BeforeSystemInit → AfterSystemInit → Ready +销毁:Destroy → Destroying → Destroyed +``` + +## 核心组件详解 + +### 1. Architecture(架构) + +应用的中央调度器,负责管理所有组件的生命周期。 + +```csharp +public class GameArchitecture : Architecture +{ + protected override void Init() + { + // 注册所有组件 + RegisterModel(new PlayerModel()); + RegisterSystem(new CombatSystem()); + RegisterUtility(new StorageUtility()); + } +} +``` + +**主要职责:** + +- 组件注册和管理 +- 生命周期协调 +- 依赖注入 +- 跨组件通信协调 + +### 2. Model(数据模型) + +应用的状态存储层,只负责数据的存储和管理。 + +```csharp +public class PlayerModel : AbstractModel +{ + public BindableProperty Health { get; } = new(100); + public BindableProperty Name { get; } = new("Player"); + + protected override void OnInit() + { + // 监听自身数据变化 + Health.Register(OnHealthChanged); + } + + private void OnHealthChanged(int newHealth) + { + if (newHealth <= 0) + this.SendEvent(new PlayerDiedEvent()); + } +} +``` + +**设计原则:** + +- 只存储数据,不包含业务逻辑 +- 使用 BindableProperty 实现响应式数据 +- 通过事件通知数据变化 + +### 3. System(业务系统) + +应用的业务逻辑处理层。 + +```csharp +public class CombatSystem : AbstractSystem +{ + protected override void OnInit() + { + // 监听战斗相关事件 + this.RegisterEvent(OnEnemyAttack); + this.RegisterEvent(OnPlayerAttack); + } + + private void OnEnemyAttack(EnemyAttackEvent e) + { + var playerModel = this.GetModel(); + playerModel.Health.Value -= e.Damage; + this.SendEvent(new PlayerTookDamageEvent { Damage = e.Damage }); + } +} +``` + +**职责范围:** + +- 处理具体的业务逻辑 +- 响应事件并修改模型数据 +- 发送新的事件通知其他组件 + +### 4. Controller(控制器) + +连接 UI 和业务逻辑的桥梁。 + +```csharp +public class PlayerController : IController +{ + private IArchitecture _architecture; + private PlayerModel _playerModel; + + public PlayerController(IArchitecture architecture) + { + _architecture = architecture; + _playerModel = architecture.GetModel(); + + // 监听模型变化并更新 UI + _playerModel.Health.RegisterWithInitValue(UpdateHealthDisplay); + } + + public void OnPlayerInput(Vector2 direction) + { + // 将用户输入转换为命令 + _architecture.SendCommand(new MovePlayerCommand { Direction = direction }); + } + + private void UpdateHealthDisplay(int health) + { + // 更新 UI 显示 + Console.WriteLine($"Player Health: {health}"); + } +} +``` + +**核心功能:** + +- 接收用户输入 +- 发送命令到系统 +- 监听模型变化更新 UI +- 协调 UI 和业务逻辑 + +### 5. Utility(工具类) + +提供无状态的辅助功能。 + +```csharp +public class StorageUtility : IUtility +{ + public void SaveData(string key, T data) + { + // 实现数据保存逻辑 + } + + public T LoadData(string key, T defaultValue = default) + { + // 实现数据加载逻辑 + return defaultValue; + } +} +``` + +**使用场景:** + +- 数据存储和读取 +- 数学计算工具 +- 字符串处理 +- 网络通信辅助 + +## 通信机制 + +### 1. Command(命令) + +用于修改应用状态的操作: + +```csharp +public class MovePlayerCommand : AbstractCommand +{ + public Vector2 Direction { get; set; } + + protected override void OnDo() + { + // 执行移动逻辑 + this.SendEvent(new PlayerMovedEvent { Position = CalculateNewPosition() }); + } +} +``` + +### 2. Query(查询) + +用于查询应用状态: + +```csharp +public class GetPlayerHealthQuery : AbstractQuery +{ + protected override int OnDo() + { + var playerModel = this.GetModel(); + return playerModel.Health.Value; + } +} +``` + +### 3. Event(事件) + +组件间通信的主要机制: + +```csharp +// 发送事件 +this.SendEvent(new PlayerDiedEvent()); + +// 监听事件 +this.RegisterEvent(OnPlayerDied); +``` + +## 响应式编程 + +### BindableProperty + +```csharp +public class PlayerModel : AbstractModel +{ + public BindableProperty Health { get; } = new(100); + public BindableProperty Name { get; } = new("Player"); +} + +// 使用方式 +playerModel.Health.Value = 50; // 自动触发所有监听器 +playerModel.Health.Register(newValue => { + Console.WriteLine($"Health changed to: {newValue}"); +}); +``` + +### 数据绑定优势 + +- **自动更新**:数据变化自动通知监听者 +- **内存安全**:自动管理监听器生命周期 +- **类型安全**:编译时类型检查 +- **性能优化**:只在值真正改变时触发 + +## 最佳实践 + +### 1. 分层职责明确 + +```csharp +// ✅ 正确:Model 只存储数据 +public class PlayerModel : AbstractModel +{ + public BindableProperty Health { get; } = new(100); +} + +// ❌ 错误:Model 包含业务逻辑 +public class PlayerModel : AbstractModel +{ + public void TakeDamage(int damage) // 业务逻辑应该在 System 中 + { + Health.Value -= damage; + } +} +``` + +### 2. 事件驱动设计 + +```csharp +// ✅ 正确:使用事件解耦 +public class CombatSystem : AbstractSystem +{ + private void OnPlayerAttack(PlayerAttackEvent e) + { + // 处理攻击逻辑 + this.SendEvent(new EnemyDamagedEvent { Damage = CalculateDamage() }); + } +} + +// ❌ 错误:直接调用其他组件 +public class CombatSystem : AbstractSystem +{ + private void OnPlayerAttack(PlayerAttackEvent e) + { + var enemySystem = this.GetSystem(); // 紧耦合 + enemySystem.TakeDamage(CalculateDamage()); + } +} +``` + +### 3. 命令查询分离 + +```csharp +// ✅ 正确:明确区分命令和查询 +public class MovePlayerCommand : AbstractCommand { } // 修改状态 +public class GetPlayerPositionQuery : AbstractQuery { } // 查询状态 + +// ❌ 错误:混合读写操作 +public class PlayerManager +{ + public void MoveAndGetPosition(Vector2 direction, out Vector2 position) // 职责不清 + { + // ... + } +} +``` + +## 架构优势 + +### 1. 可维护性 + +- 清晰的职责分离 +- 松耦合的组件设计 +- 易于定位和修复问题 + +### 2. 可测试性 + +- 组件可独立测试 +- 依赖可轻松模拟 +- 支持单元测试和集成测试 + +### 3. 可扩展性 + +- 新功能通过添加组件实现 +- 现有组件无需修改 +- 支持插件化架构 + +### 4. 团队协作 + +- 统一的架构规范 +- 易于新人上手 +- 减少代码冲突 + +## 下一步学习 + +- [深入了解 Architecture 组件](/core/architecture/architecture) +- [掌握事件系统](/core/events/event-bus) +- [学习命令查询模式](/core/command-query/commands) +- [探索属性系统](/core/property/bindable-property) \ No newline at end of file diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md new file mode 100644 index 0000000..032079c --- /dev/null +++ b/docs/getting-started/installation.md @@ -0,0 +1,187 @@ +# 安装配置 + +GFramework 提供多种安装方式,您可以根据项目需求选择合适的包进行安装。 + +## 包选择说明 + +GFramework 采用模块化设计,不同包提供不同的功能: + +| 包名 | 说明 | 适用场景 | +|---------------------------------------|---------|-----------| +| `GeWuYou.GFramework` | 聚合元包 | 快速试用、原型开发 | +| `GeWuYou.GFramework.Core` | 核心框架 | 生产项目推荐 | +| `GeWuYou.GFramework.Game` | 游戏模块 | 需要游戏特定功能 | +| `GeWuYou.GFramework.Godot` | Godot集成 | Godot项目必需 | +| `GeWuYou.GFramework.SourceGenerators` | 源码生成器 | 推荐安装 | + +## 安装方式 + +### 1. 使用 .NET CLI(推荐) + +```bash +# 核心能力(推荐最小起步) +dotnet add package GeWuYou.GFramework.Core +dotnet add package GeWuYou.GFramework.Core.Abstractions + +# 游戏扩展 +dotnet add package GeWuYou.GFramework.Game +dotnet add package GeWuYou.GFramework.Game.Abstractions + +# Godot 集成(仅 Godot 项目需要) +dotnet add package GeWuYou.GFramework.Godot + +# 源码生成器(可选,但推荐) +dotnet add package GeWuYou.GFramework.SourceGenerators +``` + +### 2. 使用 PackageReference + +在您的 `.csproj` 文件中添加: + +```xml + + + net6.0 + + + + + + + + + + + + + + + + + + +``` + +### 3. 使用 NuGet Package Manager + +在 Visual Studio 中: + +1. 右键点击项目 → 管理 NuGet 程序包 +2. 搜索 `GeWuYou.GFramework` +3. 选择需要的包进行安装 + +## 环境要求 + +### 运行时要求 + +- **.NET 6.0** 或更高版本 +- **Godot 4.5+**(仅 Godot 项目) + +### 开发工具 + +- Visual Studio 2022 或 VS Code +- .NET 6.0 SDK +- Godot 4.5+(可选,仅 Godot 项目需要) + +## 项目配置 + +### 1. 基础配置 + +创建 `GlobalUsings.cs` 文件: + +```csharp +global using GFramework.Core; +global using GFramework.Core.architecture; +global using GFramework.Core.command; +global using GFramework.Core.events; +global using GFramework.Core.model; +global using GFramework.Core.property; +global using GFramework.Core.system; +global using GFramework.Core.utility; +``` + +### 2. Godot 项目配置 + +如果使用 Godot 集成,需要在项目设置中启用 C# 支持: + +1. 在 Godot 编辑器中打开项目设置 +2. 导航到 `Mono` → `Editor Settings` +3. 确保启用了 C# 支持 + +### 3. 源码生成器配置 + +源码生成器会自动工作,无需额外配置。如果需要自定义生成器行为,可以在项目文件中添加: + +```xml + + Debug + true + +``` + +## 验证安装 + +创建一个简单的测试来验证安装是否成功: + +```csharp +using GFramework.Core.architecture; + +// 定义简单的架构 +public class TestArchitecture : Architecture +{ + protected override void Init() + { + // 注册一个简单的模型 + RegisterModel(new TestModel()); + } +} + +public class TestModel : AbstractModel +{ + public BindableProperty Message { get; } = new("Hello GFramework!"); +} + +// 测试代码 +var architecture = new TestArchitecture(); +architecture.Initialize(); + +var model = architecture.GetModel(); +Console.WriteLine(model.Message.Value); // 输出: Hello GFramework! +``` + +## 常见问题 + +### 1. 包版本冲突 + +如果遇到版本冲突,建议: + +```bash +dotnet restore --force +dotnet clean +dotnet build +``` + +### 2. Godot 集成问题 + +确保: + +- Godot 版本 >= 4.5 +- 已正确安装 Godot C# 模板 +- 项目引用了正确的 Godot 包 + +### 3. 源码生成器不工作 + +检查: + +- 确保安装了 `GeWuYou.GFramework.SourceGenerators` +- 重启 IDE +- 清理并重新构建项目 + +## 下一步 + +安装完成后,建议: + +1. [快速开始](/getting-started/quick-start) - 构建第一个应用 +2. [架构概览](/getting-started/architecture-overview) - 了解核心概念 +3. [Core 模块文档](/core/overview) - 深入学习核心功能 \ No newline at end of file diff --git a/docs/getting-started/quick-start.md b/docs/getting-started/quick-start.md new file mode 100644 index 0000000..bc9ec13 --- /dev/null +++ b/docs/getting-started/quick-start.md @@ -0,0 +1,327 @@ +# 快速开始 + +本指南将帮助您快速构建第一个基于 GFramework 的应用程序。 + +## 1. 创建项目架构 + +首先定义您的应用架构: + +```csharp +using GFramework.Core.architecture; + +public class GameArchitecture : Architecture +{ + protected override void Init() + { + // 注册模型 - 存储应用状态 + RegisterModel(new PlayerModel()); + RegisterModel(new GameStateModel()); + + // 注册系统 - 处理业务逻辑 + RegisterSystem(new PlayerSystem()); + RegisterSystem(new GameLogicSystem()); + + // 注册工具类 - 提供辅助功能 + RegisterUtility(new StorageUtility()); + } +} +``` + +## 2. 定义数据模型 + +创建您的数据模型: + +```csharp +public class PlayerModel : AbstractModel +{ + // 使用可绑定属性实现响应式数据 + public BindableProperty Name { get; } = new("Player"); + public BindableProperty Health { get; } = new(100); + public BindableProperty Score { get; } = new(0); + + protected override void OnInit() + { + // 监听健康值变化 + Health.Register(OnHealthChanged); + } + + private void OnHealthChanged(int newHealth) + { + if (newHealth <= 0) + { + this.SendEvent(new PlayerDiedEvent()); + } + } +} + +public class GameStateModel : AbstractModel +{ + public BindableProperty IsGameRunning { get; } = new(false); + public BindableProperty CurrentLevel { get; } = new(1); +} +``` + +## 3. 实现业务逻辑 + +创建处理业务逻辑的系统: + +```csharp +public class PlayerSystem : AbstractSystem +{ + protected override void OnInit() + { + // 监听玩家输入事件 + this.RegisterEvent(OnPlayerMove); + this.RegisterEvent(OnPlayerAttack); + } + + private void OnPlayerMove(PlayerMoveEvent e) + { + var playerModel = this.GetModel(); + // 处理移动逻辑 + Console.WriteLine($"Player moved to {e.Direction}"); + } + + private void OnPlayerAttack(PlayerAttackEvent e) + { + var playerModel = this.GetModel(); + // 处理攻击逻辑 + playerModel.Score.Value += 10; + this.SendEvent(new EnemyDamagedEvent { Damage = 25 }); + } +} + +public class GameLogicSystem : AbstractSystem +{ + protected override void OnInit() + { + this.RegisterEvent(OnEnemyDamaged); + this.RegisterEvent(OnPlayerDied); + } + + private void OnEnemyDamaged(EnemyDamagedEvent e) + { + Console.WriteLine($"Enemy took {e.Damage} damage"); + // 检查是否需要升级关卡 + CheckLevelProgress(); + } + + private void OnPlayerDied(PlayerDiedEvent e) + { + var gameState = this.GetModel(); + gameState.IsGameRunning.Value = false; + Console.WriteLine("Game Over!"); + } + + private void CheckLevelProgress() + { + // 实现关卡进度检查逻辑 + } +} +``` + +## 4. 定义事件 + +创建应用中使用的事件: + +```csharp +public class PlayerMoveEvent : IEvent +{ + public Vector2 Direction { get; set; } +} + +public class PlayerAttackEvent : IEvent +{ + public Vector2 TargetPosition { get; set; } +} + +public class PlayerDiedEvent : IEvent +{ + // 玩家死亡事件 +} + +public class EnemyDamagedEvent : IEvent +{ + public int Damage { get; set; } +} +``` + +## 5. 创建控制器 + +实现控制器来连接 UI 和业务逻辑: + +```csharp +public class GameController : IController +{ + private IArchitecture _architecture; + private PlayerModel _playerModel; + private GameStateModel _gameStateModel; + + public GameController(IArchitecture architecture) + { + _architecture = architecture; + _playerModel = architecture.GetModel(); + _gameStateModel = architecture.GetModel(); + + // 初始化事件监听 + InitializeEventListeners(); + } + + private void InitializeEventListeners() + { + // 监听模型变化并更新 UI + _playerModel.Health.RegisterWithInitValue(OnHealthChanged); + _playerModel.Score.RegisterWithInitValue(OnScoreChanged); + _gameStateModel.IsGameRunning.Register(OnGameStateChanged); + } + + public void StartGame() + { + _gameStateModel.IsGameRunning.Value = true; + _architecture.SendEvent(new GameStartEvent()); + Console.WriteLine("Game started!"); + } + + public void MovePlayer(Vector2 direction) + { + _architecture.SendCommand(new MovePlayerCommand { Direction = direction }); + } + + public void PlayerAttack(Vector2 target) + { + _architecture.SendCommand(new AttackCommand { TargetPosition = target }); + } + + // UI 更新回调 + private void OnHealthChanged(int health) + { + UpdateHealthDisplay(health); + } + + private void OnScoreChanged(int score) + { + UpdateScoreDisplay(score); + } + + private void OnGameStateChanged(bool isRunning) + { + UpdateGameStatusDisplay(isRunning); + } + + private void UpdateHealthDisplay(int health) + { + // 更新血条 UI + Console.WriteLine($"Health: {health}"); + } + + private void UpdateScoreDisplay(int score) + { + // 更新分数显示 + Console.WriteLine($"Score: {score}"); + } + + private void UpdateGameStatusDisplay(bool isRunning) + { + // 更新游戏状态显示 + Console.WriteLine($"Game running: {isRunning}"); + } +} +``` + +## 6. 定义命令 + +创建命令来封装用户操作: + +```csharp +public class MovePlayerCommand : AbstractCommand +{ + public Vector2 Direction { get; set; } + + protected override void OnDo() + { + // 发送移动事件 + this.SendEvent(new PlayerMoveEvent { Direction = Direction }); + } +} + +public class AttackCommand : AbstractCommand +{ + public Vector2 TargetPosition { get; set; } + + protected override void OnDo() + { + // 发送攻击事件 + this.SendEvent(new PlayerAttackEvent { TargetPosition = TargetPosition }); + } +} +``` + +## 7. 运行应用 + +现在让我们运行这个简单的应用: + +```csharp +class Program +{ + static void Main(string[] args) + { + // 创建并初始化架构 + var architecture = new GameArchitecture(); + architecture.Initialize(); + + // 创建控制器 + var gameController = new GameController(architecture); + + // 开始游戏 + gameController.StartGame(); + + // 模拟玩家操作 + gameController.MovePlayer(new Vector2(1, 0)); + gameController.PlayerAttack(new Vector2(5, 5)); + + // 模拟玩家受伤 + var playerModel = architecture.GetModel(); + playerModel.Health.Value = 50; + + // 模拟玩家死亡 + playerModel.Health.Value = 0; + + Console.WriteLine("Press any key to exit..."); + Console.ReadKey(); + } +} +``` + +## 8. 运行结果 + +执行程序后,您应该看到类似以下输出: + +``` +Game started! +Game running: True +Player moved to (1, 0) +Player took 25 damage +Score: 10 +Health: 50 +Health: 0 +Player died +Game Over! +Game running: False +Press any key to exit... +``` + +## 下一步 + +这个简单的示例展示了 GFramework 的核心概念: + +1. **架构模式** - 清晰的分层结构 +2. **响应式数据** - BindableProperty 自动更新 +3. **事件驱动** - 松耦合的组件通信 +4. **命令模式** - 封装用户操作 + +接下来您可以: + +- [深入了解架构组件](/core/architecture/architecture) +- [学习事件系统](/core/events/event-bus) +- [探索 Godot 集成](/godot/overview)(如果您使用 Godot) +- [查看完整教程](/tutorials/basic-tutorial) \ No newline at end of file diff --git a/docs/godot/overview.md b/docs/godot/overview.md new file mode 100644 index 0000000..3f56edb --- /dev/null +++ b/docs/godot/overview.md @@ -0,0 +1,176 @@ +# Godot 集成概览 + +GFramework.Godot 提供与 Godot 引擎的深度集成,让开发者能够在保持框架架构优势的同时,充分利用 Godot 的强大功能。 + +## 核心特性 + +### 🎮 Godot 深度集成 + +- **架构生命周期绑定** - 自动同步框架和 Godot 节点生命周期 +- **丰富的 Node 扩展** - 50+ 个实用的节点扩展方法 +- **类型安全信号** - 强类型的信号连接和处理 +- **高效对象池** - 专门的 Node 对象池系统 + +### 🔧 开发者友好 + +- **零配置集成** - 简单的安装和配置过程 +- **流畅的 API** - 链式调用和现代 C# 语法 +- **自动清理** - 智能的资源和事件监听器管理 +- **调试支持** - 完善的日志和调试工具 + +## 核心组件 + +### 架构集成 + +- **AbstractArchitecture** - Godot 架构基类 +- **AbstractGodotModule** - Godot 模块基类 +- **NodeController** - 节点控制器基类 + +### 节点扩展 + +- **[NodeExtensions](/godot/node-extensions/node-extensions)** - 节点扩展方法 +- **SignalBuilder** - 信号构建器 +- **AsyncExtensions** - 异步扩展 + +### 对象池系统 + +- **[AbstractNodePoolSystem](/godot/pooling/node-pool)** - 节点池基类 +- **NodePoolManager** - 节点池管理器 +- **PoolableObject** - 可池化对象接口 + +### 日志系统 + +- **[GodotLogger](/godot/logging/godot-logger)** - Godot 集成日志 +- **LoggerFactory** - 日志工厂 +- **Log Attributes** - 日志特性 + +## 使用场景 + +Godot 模块适用于所有使用 Godot 引擎的项目: + +- **2D 游戏** - 平台游戏、RPG、策略游戏 +- **3D 游戏** - 动作游戏、射击游戏、模拟游戏 +- **工具应用** - 编辑器、可视化工具 +- **原型开发** - 快速游戏原型制作 + +## 安装要求 + +```bash +# 需要安装 Core 和 Game 模块 +dotnet add package GeWuYou.GFramework.Core +dotnet add package GeWuYou.GFramework.Game +dotnet add package GeWuYou.GFramework.Godot + +# 需要 Godot 4.5+ 版本 +``` + +## 快速示例 + +```csharp +using GFramework.Godot.architecture; +using GFramework.Godot.extensions; + +[ContextAware] +[Log] +public partial class PlayerController : CharacterBody2D, IController +{ + private PlayerModel _playerModel; + + public override void _Ready() + { + _playerModel = Context.GetModel(); + + // 安全的节点操作 + var healthBar = GetNodeX("UI/HealthBar"); + + // 类型安全的信号连接 + this.CreateSignalBuilder(Button.SignalName.Pressed) + .UnRegisterWhenNodeExitTree(this) + .Connect(OnButtonPressed); + + // 响应式数据绑定 + _playerModel.Health.Register(OnHealthChanged) + .UnRegisterWhenNodeExitTree(this); + } + + private void OnButtonPressed() + { + Context.SendCommand(new AttackCommand()); + } + + private void OnHealthChanged(int newHealth) + { + // 自动更新 UI + var healthBar = GetNode("UI/HealthBar"); + healthBar.Value = newHealth; + } +} +``` + +## 学习路径 + +建议按以下顺序学习 Godot 集成: + +1. **[架构集成](/godot/integration/architecture-integration)** - 了解集成基础 +2. **[节点扩展](/godot/node-extensions/node-extensions)** - 掌握扩展方法 +3. **[对象池](/godot/pooling/node-pool)** - 学习性能优化 +4. **[日志系统](/godot/logging/godot-logger)** - 掌握调试工具 + +## 与其它模块的关系 + +``` +GFramework.Core (基础架构) + ↓ +GFramework.Game (游戏功能) + ↓ +GFramework.Godot (Godot 集成) +``` + +Godot 模块建立在 Core 和 Game 模块之上,提供与 Godot 引擎的无缝集成。 + +## 性能特点 + +- **零额外开销** - 扩展方法编译时优化 +- **内存安全** - 自动资源管理和清理 +- **类型安全** - 编译时类型检查 +- **异步支持** - 完善的异步操作支持 + +## 常见用法 + +### 节点安全操作 + +```csharp +// 安全获取节点 +var player = GetNodeX("Player"); +var child = FindChildX("HealthBar"); + +// 安全添加子节点 +AddChildX(bullet); +``` + +### 信号处理 + +```csharp +// 流畅的信号连接 +this.CreateSignalBuilder(Timer.SignalName.Timeout) + .WithFlags(ConnectFlags.OneShot) + .Connect(OnTimeout) + .UnRegisterWhenNodeExitTree(this); +``` + +### 异步操作 + +```csharp +// 等待信号 +await ToSignal(this, SignalName.Ready); + +// 等待条件 +await WaitUntil(() => IsReady); +``` + +## 下一步 + +- [深入了解架构集成](/godot/integration/architecture-integration) +- [学习节点扩展方法](/godot/node-extensions/node-extensions) +- [掌握对象池系统](/godot/pooling/node-pool) +- [查看完整 API 参考](/api-reference/godot-api) \ No newline at end of file diff --git a/docs/index.md b/docs/index.md index bd026e5..2829fcb 100644 --- a/docs/index.md +++ b/docs/index.md @@ -4,22 +4,35 @@ layout: home hero: name: "GFramework" - text: "A developer-oriented framework for structured game development" - tagline: My great project tagline + text: "面向游戏开发场景的模块化 C# 框架" + tagline: 基于清洁架构和CQRS模式的现代化游戏开发框架 + image: + src: /logo.png + alt: GFramework Logo actions: - theme: brand - text: Markdown Examples - link: /markdown-examples + text: 快速开始 + link: /getting-started/quick-start - theme: alt - text: API Examples - link: /api-examples + text: 架构概览 + link: /getting-started/architecture-overview + - theme: alt + text: API 参考 + link: /api-reference/core-api features: - - title: Feature A - details: Lorem ipsum dolor sit amet, consectetur adipiscing elit - - title: Feature B - details: Lorem ipsum dolor sit amet, consectetur adipiscing elit - - title: Feature C - details: Lorem ipsum dolor sit amet, consectetur adipiscing elit + - title: 🏗️ 清洁架构 + details: 基于Model-View-Controller-System-Utility五层架构,实现清晰的职责分离和高内聚低耦合 + - title: 🔧 CQRS模式 + details: 命令查询职责分离,提供类型安全的命令和查询系统,支持可撤销操作 + - title: 📡 事件驱动 + details: 强大的事件总线系统,支持类型安全的事件发布订阅,实现组件间松耦合通信 + - title: 🎮 Godot集成 + details: 深度集成Godot引擎,提供丰富的节点扩展方法和对象池化支持 + - title: 🔄 响应式编程 + details: 可绑定属性系统,自动化的数据绑定和UI更新机制 + - title: ⚡ 源码生成器 + details: 基于Roslyn的源码生成器,自动生成日志、枚举扩展等样板代码 + --- diff --git a/docs/markdown-examples.md b/docs/markdown-examples.md deleted file mode 100644 index 966acd2..0000000 --- a/docs/markdown-examples.md +++ /dev/null @@ -1,86 +0,0 @@ -# Markdown Extension Examples - -This page demonstrates some of the built-in markdown extensions provided by VitePress. - -## Syntax Highlighting - -VitePress provides Syntax Highlighting powered by [Shiki](https://github.com/shikijs/shiki), with additional features -like line-highlighting: - -**Input** - -````md -```js{4} -export default { - data () { - return { - msg: 'Highlighted!' - } - } -} -``` -```` - -**Output** - -```js{4} -export default { - data () { - return { - msg: 'Highlighted!' - } - } -} -``` - -## Custom Containers - -**Input** - -```md -::: info -This is an info box. -::: - -::: tip -This is a tip. -::: - -::: warning -This is a warning. -::: - -::: danger -This is a dangerous warning. -::: - -::: details -This is a details block. -::: -``` - -**Output** - -::: info -This is an info box. -::: - -::: tip -This is a tip. -::: - -::: warning -This is a warning. -::: - -::: danger -This is a dangerous warning. -::: - -::: details -This is a details block. -::: - -## More - -Check out the documentation for the [full list of markdown extensions](https://vitepress.dev/guide/markdown). diff --git a/docs/source-generators/overview.md b/docs/source-generators/overview.md new file mode 100644 index 0000000..fcd5e15 --- /dev/null +++ b/docs/source-generators/overview.md @@ -0,0 +1,234 @@ +# 源码生成器概览 + +GFramework 源码生成器基于 Roslyn 编译器平台,自动生成常用的样板代码,提高开发效率并减少错误。 + +## 核心特性 + +### ⚡ 自动代码生成 + +- **日志代码生成** - 自动生成日志字段和方法调用 +- **枚举扩展生成** - 为枚举类型生成实用扩展方法 +- **规则代码生成** - 根据规则定义生成验证代码 +- **性能优化** - 编译时生成,运行时零开销 + +### 🎯 智能识别 + +- **特性驱动** - 通过特性标记触发生成 +- **上下文感知** - 理解代码语义和结构 +- **类型安全** - 生成的代码完全类型安全 +- **错误预防** - 编译时检查,避免运行时错误 + +## 核心生成器 + +### 日志生成器 + +- **[LogAttribute](/source-generators/logging-generator)** - 自动生成日志字段 +- **ContextAwareAttribute** - 生成上下文感知代码 +- **性能监控** - 自动生成方法执行时间记录 + +### 枚举扩展生成器 + +- **[EnumExtensions](/source-generators/enum-extensions)** - 生成枚举实用方法 +- **字符串转换** - 枚举与字符串的双向转换 +- **描述获取** - 从特性中提取枚举描述 + +### 规则生成器 + +- **[RuleGenerator](/source-generators/rule-generator)** - 生成验证规则代码 +- **业务规则** - 基于规则定义生成验证逻辑 +- **数据验证** - 自动生成数据完整性检查 + +## 使用场景 + +源码生成器适用于需要大量样板代码的场景: + +- **日志记录** - 统一的日志格式和级别管理 +- **枚举处理** - 频繁的枚举转换和操作 +- **数据验证** - 复杂的业务规则验证 +- **性能监控** - 方法执行时间跟踪 + +## 安装配置 + +```xml + +``` + +## 快速示例 + +### 日志生成器 + +```csharp +[Log] // 自动生成 Logger 字段 +public partial class PlayerController : IController +{ + // 生成的代码: + // private ILogger _logger; + // public ILogger Logger => _logger ??= LoggerFactory.Create(GetType()); + + public void Attack() + { + Logger.Info("Player attacking"); // 直接使用生成的 Logger + // 业务逻辑... + } +} +``` + +### 枚举扩展生成 + +```csharp +[GenerateEnumExtensions] // 生成枚举扩展方法 +public enum PlayerState +{ + [Description("空闲")] + Idle, + + [Description("移动中")] + Moving, + + [Description("攻击中")] + Attacking +} + +// 生成的扩展方法: +// PlayerStateExtensions.GetDescription() +// PlayerStateExtensions.FromString() +// PlayerStateExtensions.GetAllValues() +``` + +### 规则生成器 + +```csharp +[GenerateValidationRules] // 生成验证规则 +public class PlayerData +{ + [Required] + [StringLength(50, MinimumLength = 3)] + public string Name { get; set; } + + [Range(0, 100)] + public int Health { get; set; } + + [Email] + public string Email { get; set; } +} + +// 生成的验证方法: +// PlayerDataValidator.Validate() +// PlayerDataValidator.ValidateName() +// PlayerDataValidator.ValidateHealth() +``` + +## 生成器配置 + +### 全局配置 + +```xml + + Debug + true + true + +``` + +### 特性配置 + +```csharp +[Log(LogLevel = LogLevel.Debug, IncludeCallerInfo = true)] +[GenerateEnumExtensions(CamelCase = true)] +[GenerateValidationRules(ThrowOnInvalid = true)] +``` + +## 性能优势 + +### 编译时生成 + +- **零运行时开销** - 代码在编译时生成 +- **类型安全** - 编译时类型检查 +- **IDE 支持** - 生成的代码完全支持 IntelliSense + +### 代码质量 + +- **一致性** - 统一的代码风格和模式 +- **错误减少** - 自动生成减少手写错误 +- **维护性** - 集中管理样板代码逻辑 + +## 学习路径 + +建议按以下顺序学习源码生成器: + +1. **[日志生成器](/source-generators/logging-generator)** - 基础的日志代码生成 +2. **[枚举扩展](/source-generators/enum-extensions)** - 枚举处理自动化 +3. **[规则生成器](/source-generators/rule-generator)** - 复杂验证逻辑生成 + +## 调试生成的代码 + +### 查看生成的代码 + +```xml + + true + Generated + +``` + +### 调试配置 + +```csharp +// 在调试时查看生成的代码 +#if DEBUG +// 生成的代码会被写入到指定目录 +#endif +``` + +## 最佳实践 + +### 1. 合理使用特性 + +```csharp +// ✅ 好的做法:在需要的地方使用 +[Log] +public class ImportantService { } + +// ❌ 避免过度使用 +[Log] // 不是每个类都需要日志 +public class SimpleDataClass { } +``` + +### 2. 配置优化 + +```xml + + + Warning + + + + + Debug + +``` + +### 3. 性能考虑 + +```csharp +// ✅ 生成器适合复杂场景 +[GenerateValidationRules] // 复杂验证逻辑 +public class BusinessEntity { } + +// ❌ 简单场景手动实现更高效 +public class SimpleConfig +{ + public string Name { get; set; } + // 简单属性不需要生成器 +} +``` + +## 下一步 + +- [深入了解日志生成器](/source-generators/logging-generator) +- [学习枚举扩展生成](/source-generators/enum-extensions) +- [掌握规则生成器](/source-generators/rule-generator) +- [查看生成器 API](/api-reference/generators-api) \ No newline at end of file diff --git a/docs/tutorials/basic-tutorial.md b/docs/tutorials/basic-tutorial.md new file mode 100644 index 0000000..2b451e5 --- /dev/null +++ b/docs/tutorials/basic-tutorial.md @@ -0,0 +1,445 @@ +# 基础教程 + +这是一个完整的从零开始的教程,将带领你创建一个使用 GFramework 的简单游戏项目。 + +## 📋 目录 + +- [环境准备](#环境准备) +- [项目创建](#项目创建) +- [架构设计](#架构设计) +- [功能实现](#功能实现) +- [测试验证](#测试验证) + +## 环境准备 + +### 系统要求 + +- **操作系统**: Windows 10+, macOS 10.15+, 或 Linux +- **.NET SDK**: 6.0 或更高版本 +- **Godot 引擎**: 4.5.1 或更高版本 +- **IDE**: Visual Studio 2022+, JetBrains Rider, 或 VS Code + +### 安装 .NET SDK + +1. 访问 [.NET 官网](https://dotnet.microsoft.com/download) +2. 下载并安装 .NET 6.0 SDK +3. 验证安装: + +```bash +dotnet --version +# 应该显示 6.0.x 或更高版本 +``` + +### 安装 Godot + +1. 访问 [Godot 官网](https://godotengine.org/download) +2. 下载 Godot 4.5.1 +3. 解压到合适的位置并启动 +4. 在编辑器设置中确认 .NET 支持 + +### 验证环境 + +创建一个测试项目验证环境: + +```bash +# 创建测试项目 +dotnet new console -n TestProject +cd TestProject + +# 如果使用 Godot,添加 Godot 引用 +dotnet add package GeWuYou.GFramework.Core +dotnet add package GeWuYou.GFramework.Godot + +# 编译测试 +dotnet build +``` + +## 项目创建 + +### 1. 创建新的 Godot 项目 + +1. 打开 Godot 编辑器 +2. 点击 "新建项目" +3. 创建项目文件夹,命名为 "MyGFrameworkGame" +4. 选择 C# 作为脚本语言 + +### 2. 配置项目结构 + +在项目根目录创建以下文件夹结构: + +``` +MyGFrameworkGame/ +├── src/ +│ ├── Game/ # 游戏逻辑 +│ │ ├── Models/ # 数据模型 +│ │ ├── Systems/ # 业务系统 +│ │ ├── Controllers/ # 控制器 +│ │ └── Utilities/ # 工具类 +│ └── Game.Core/ # 核心游戏组件 +├── assets/ # 游戏资源 +│ ├── scenes/ +│ ├── textures/ +│ ├── audio/ +│ └── ui/ +└── project.godot # Godot 项目文件 +``` + +### 3. 配置项目文件 + +创建 `src/Game/Game.csproj`: + +```xml + + + + net6.0 + MyGFrameworkGame + enable + + + + + + + + + + + + + + +``` + +创建 `src/Game.Core/Game.Core.csproj`: + +```xml + + + + net6.0 + MyGFrameworkGame.Core + enable + + + + + + + + + + +``` + +## 架构设计 + +### 1. 定义游戏架构 + +创建 `src/Game.Core/Architecture/GameArchitecture.cs`: + +```csharp +using GFramework.Core.architecture; +using MyGFrameworkGame.Core.Models; +using MyGFrameworkGame.Core.Systems; + +namespace MyGFrameworkGame.Core.Architecture +{ + public class GameArchitecture : AbstractArchitecture + { + protected override void Init() + { + // 注册游戏模型 + RegisterModel(new PlayerModel()); + RegisterModel(new GameModel()); + + // 注册游戏系统 + RegisterSystem(new PlayerControllerSystem()); + RegisterSystem(new CollisionSystem()); + + // 注册工具类 + RegisterUtility(new StorageUtility()); + } + } +} +``` + +### 2. 创建核心模型 + +创建 `src/Game.Core/Models/PlayerModel.cs`: + +```csharp +using GFramework.Core.model; + +namespace MyGFrameworkGame.Core.Models +{ + public class PlayerModel : AbstractModel + { + public BindableProperty Health { get; } = new(100); + public BindableProperty Score { get; } = new(0); + public BindableProperty IsAlive { get; } = new(true); + + protected override void OnInit() + { + // 监听生命值变化 + Health.Register(health => { + if (health <= 0) + { + IsAlive.Value = false; + SendEvent(new PlayerDeathEvent()); + } + }); + } + + public void TakeDamage(int damage) + { + if (IsAlive.Value) + { + Health.Value = Math.Max(0, Health.Value - damage); + } + } + } + + // 游戏事件 + public struct PlayerDeathEvent { } +} +``` + +## 功能实现 + +### 1. 创建主场景 + +创建 `src/Game/MainScene.cs`: + +```csharp +using Godot; +using GFramework.Godot.extensions; +using GFramework.Godot.architecture; +using MyGFrameworkGame.Core.Architecture; +using MyGFrameworkGame.Core.Models; + +namespace MyGFrameworkGame +{ + [ContextAware] + [Log] + public partial class MainScene : Node2D + { + private GameArchitecture _architecture; + private Player _player; + + public override void _Ready() + { + Logger.Info("Main scene ready"); + + // 初始化架构 + InitializeArchitecture(); + + // 创建游戏对象 + CreateGameObjects(); + + // 注册事件监听 + RegisterEventListeners(); + } + + private void InitializeArchitecture() + { + _architecture = new GameArchitecture(); + _architecture.Initialize(); + SetContext(_architecture.Context); + } + + private void CreateGameObjects() + { + var playerScene = GD.Load("res://assets/scenes/Player.tscn"); + _player = playerScene.Instantiate(); + AddChild(_player); + } + + private void RegisterEventListeners() + { + this.RegisterEvent(OnPlayerDeath) + .UnRegisterWhenNodeExitTree(this); + } + + private void OnPlayerDeath(PlayerDeathEvent e) + { + Logger.Info("Player died"); + // 处理玩家死亡逻辑 + } + } +} +``` + +### 2. 创建玩家控制器 + +创建 `src/Game/Player.cs`: + +```csharp +using Godot; +using GFramework.Godot.extensions; +using MyGFrameworkGame.Core.Models; + +namespace MyGFrameworkGame +{ + [ContextAware] + [Log] + public partial class Player : CharacterBody2D + { + private PlayerModel _playerModel; + + public override void _Ready() + { + _playerModel = Context.GetModel(); + + // 注册事件监听 + this.RegisterEvent(OnPlayerMove) + .UnRegisterWhenNodeExitTree(this); + } + + public override void _Process(double delta) + { + HandleInput(); + MoveAndSlide(); + } + + private void HandleInput() + { + var inputVector = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down"); + if (inputVector != Vector2.Zero) + { + SendEvent(new PlayerMoveEvent { Direction = inputVector }); + } + } + + private void OnPlayerMove(PlayerMoveEvent e) + { + Velocity = e.Direction * 300.0f; + } + } + + public struct PlayerMoveEvent + { + public Vector2 Direction { get; set; } + } +} +``` + +## 测试验证 + +### 1. 创建测试项目 + +创建 `tests/Game.Tests/Game.Tests.csproj`: + +```xml + + + + net6.0 + false + + + + + + + + + + + + + + +``` + +### 2. 创建单元测试 + +创建 `tests/Game.Tests/PlayerModelTests.cs`: + +```csharp +using NUnit.Framework; +using MyGFrameworkGame.Core.Models; +using GFramework.Core.architecture; + +namespace MyGFrameworkGame.Tests +{ + [TestFixture] + public class PlayerModelTests + { + private TestArchitecture _architecture; + private PlayerModel _playerModel; + + [SetUp] + public void Setup() + { + _architecture = new TestArchitecture(); + _architecture.Initialize(); + _playerModel = _architecture.GetModel(); + } + + [Test] + public void PlayerModel_InitialValues_ShouldBeCorrect() + { + Assert.That(_playerModel.Health.Value, Is.EqualTo(100)); + Assert.That(_playerModel.Score.Value, Is.EqualTo(0)); + Assert.That(_playerModel.IsAlive.Value, Is.True); + } + + [Test] + public void TakeDamage_ValidDamage_ShouldReduceHealth() + { + _playerModel.TakeDamage(20); + Assert.That(_playerModel.Health.Value, Is.EqualTo(80)); + Assert.That(_playerModel.IsAlive.Value, Is.True); + } + + [Test] + public void TakeDamage_LethalDamage_ShouldKillPlayer() + { + _playerModel.TakeDamage(150); + Assert.That(_playerModel.Health.Value, Is.EqualTo(0)); + Assert.That(_playerModel.IsAlive.Value, Is.False); + } + } + + public class TestArchitecture : Architecture + { + protected override void Init() + { + RegisterModel(new PlayerModel()); + } + } +} +``` + +### 3. 运行测试 + +```bash +cd tests/Game.Tests +dotnet test +``` + +## 总结 + +恭喜!你已经成功创建了一个完整的 GFramework 游戏项目基础框架。这个项目包含了: + +- ✅ **完整的架构设计** - 使用 GFramework 的五层架构 +- ✅ **核心游戏功能** - 玩家控制、基本游戏循环 +- ✅ **完善的测试** - 单元测试验证核心逻辑 + +### 下一步建议 + +1. **扩展游戏内容**:添加敌人、道具、关卡系统 +2. **完善 UI 系统**:创建菜单、HUD、游戏结束界面 +3. **添加音效系统**:背景音乐、音效播放 +4. **实现存档功能**:游戏进度保存和加载 +5. **优化性能**:使用对象池、减少内存分配 + +### 学习资源 + +- [GFramework 主文档](/) +- [Core 模块文档](/core/overview) +- [Godot 集成文档](/godot/overview) +- [API 参考](/api-reference/core-api) + +享受游戏开发的乐趣吧!🎮 \ No newline at end of file