Skip to content
English

组织进阶 Godot 项目 ​

运行示例 ​

bash
bash scripts/prepare-dodge-advanced-mods.sh
dotnet build Samples/DodgeTheCreeps.Advanced/DodgeTheCreeps.Advanced.csproj -c Debug
godot --headless --editor --path Samples/DodgeTheCreeps.Advanced --import
godot --path Samples/DodgeTheCreeps.Advanced

组织功能 ​

工程职责
DodgeTheCreeps.Advanced.Core游戏规则、进度快照和应用端口
DodgeTheCreeps.AdvancedUI、原生玩法适配、设置和内容管理
DodgeTheCreeps.Advanced.Tests对规则和用例的测试

从规则和快照开始,为真实的宿主边界定义端口。用例处理保存、恢复与计分顺序,再把结果交给原生视图。

csharp
// Copyright (c) 2025-2026 GeWuYou
// SPDX-License-Identifier: Apache-2.0

using System;
using System.Threading;
using System.Threading.Tasks;
using DodgeTheCreeps.Advanced.Core.Progress;

namespace DodgeTheCreeps.Advanced.Core.Gameplay;

/// <summary>
/// Coordinates run effects through explicit ports. One operation gate serializes board and
/// save mutations; UI dialog replies stay outside this boundary and can complete independently.
/// </summary>
/// <param name="session">The run's policy state.</param>
/// <param name="board">The engine boundary.</param>
/// <param name="store">The persistent document boundary.</param>
public sealed class RunUseCases(GameSession session, IRunBoard board, IRunStore store) : IDisposable
{
    private readonly SemaphoreSlim _operations = new(1, 1);

    /// <summary>Releases operation serialization after the host has stopped and awaited accepted work.</summary>
    public void Dispose() => _operations.Dispose();

    /// <summary>Loads before replacing a board, then starts only after scene preparation succeeds.</summary>
    /// <param name="restore">Whether the player requested continuation.</param>
    /// <param name="contentReady">Whether current content was accepted.</param>
    /// <param name="arenaId">Default arena for a new run.</param>
    /// <param name="cancellationToken">The application lifetime token.</param>
    /// <returns>False only when document recovery was cancelled.</returns>
    public async Task<bool> StartAsync(bool restore, bool contentReady, string arenaId, CancellationToken cancellationToken = default)
    {
        await _operations.WaitAsync(cancellationToken).ConfigureAwait(true);
        try
        {
            session.RequireStartAllowed(contentReady, restore);
            var saved = restore ? await store.LoadAsync(cancellationToken).ConfigureAwait(true) : null;
            if (restore && saved is null)
                return false;
            cancellationToken.ThrowIfCancellationRequested();
            if (!restore)
                store.BeginNewRun();
            await board.PrepareAsync(saved?.ArenaId ?? arenaId, cancellationToken).ConfigureAwait(true);
            if (saved is null)
                board.StartNew();
            else
                board.Restore(saved);
            session.Begin(restore, saved);
            return true;

        }
        finally { _operations.Release(); }
    }

    /// <summary>Changes the checkpoint policy only after persistent commit has succeeded.</summary>
    /// <param name="cancellationToken">The application lifetime token.</param>
    public async Task SaveAsync(CancellationToken cancellationToken = default)
    {
        var expectedGeneration = session.Generation;
        await _operations.WaitAsync(cancellationToken).ConfigureAwait(true);
        try
        {
            RequireGeneration(expectedGeneration);
            if (!board.IsRunning)
                throw new InvalidOperationException("Only a live run can be saved.");
            var observedVersion = session.ChangeVersion;
            var snapshot = board.Capture();
            RunRules.ValidateSnapshot(snapshot);
            await store.SaveAsync(snapshot, cancellationToken).ConfigureAwait(true);
            session.MarkSaved(snapshot, observedVersion);

        }
        finally { _operations.Release(); }
    }

    /// <summary>Retires before deletion; even a failed delete cannot revive an ended run in this process.</summary>
    /// <param name="cancellationToken">The cleanup token; normal death uses a non-cancelled token.</param>
    public async Task RetireAsync(CancellationToken cancellationToken = default)
    {
        var expectedGeneration = session.Generation;
        await _operations.WaitAsync(cancellationToken).ConfigureAwait(true);
        try
        {
            RequireGeneration(expectedGeneration);
            session.Retire();
            await store.RetireAsync(cancellationToken).ConfigureAwait(true);
            session.MarkCheckpointDeleted();

        }
        finally { _operations.Release(); }
    }

    /// <summary>Serializes discarding a board with saving, starting and retiring it.</summary>
    /// <param name="cancellationToken">The application's navigation lifetime.</param>
    public async Task LeaveAsync(CancellationToken cancellationToken = default)
    {
        var expectedGeneration = session.Generation;
        await _operations.WaitAsync(cancellationToken).ConfigureAwait(true);
        try
        {
            RequireGeneration(expectedGeneration);
            await board.ClearAsync(cancellationToken).ConfigureAwait(true);
            session.MarkClean();
        }
        finally { _operations.Release(); }
    }

    /// <summary>Rejects queued effects belonging to a board replaced while they waited for the operation gate.</summary>
    private void RequireGeneration(long expectedGeneration)
    {
        if (session.Generation != expectedGeneration)
            throw new InvalidOperationException("The run changed while this operation was waiting.");
    }
}

组合依赖 ​

在组合根统一注册依赖。用启动组件预载资源,退出时等待内容、UI 与存储结束后再释放原生对象。

csharp
/// <inheritdoc />
protected override void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(host);
    services.AddSingleton(launch);
    services.AddSingleton(dispatcher);
    services.AddSingleton<GameLifetime>();
    services.AddSingleton<WorldState>();
    services.AddSingleton<GameSession>();
    services.AddSingleton(_ => new DodgeLocalization(dispatcher));
    services.AddSingleton(provider => new GamePresentationState(provider.GetRequiredService<DodgeLocalization>()));
    services.AddSingleton(static _ => new GodotFileStorage(new JsonSerializer()));
    services.AddSingleton(static _ => new PauseStackManager());
    services.AddSingleton(provider => new ModService(dispatcher, provider.GetRequiredService<WorldState>()));
    services.AddSingleton(provider =>
    {
        var mods = provider.GetRequiredService<ModService>();
        var content = new DodgeContent(provider.GetRequiredService<GodotFileStorage>(), launch.DataRoot, mods.CreateOptions());
        mods.SetContent(content);
        return content;
    });
    services.AddSingleton(static _ => new GodotUiRoot { Name = "Ui" });
    services.AddSingleton(provider =>
    {
        // UiService snapshots registrations during construction. Register every typed route now,
        // but defer the menu instance so its application dependency cannot form a constructor cycle.
        var registry = new UiRegistry();
        DodgeMenus.Register(registry, () => provider.GetRequiredService<DodgeMenus>());
        return registry;
    });
    services.AddSingleton(provider => new UiService(provider.GetRequiredService<UiRegistry>(),
        provider.GetRequiredService<GodotUiRoot>(), dispatcher, provider.GetRequiredService<PauseStackManager>()));
    services.AddSingleton(provider => new GameSceneFactory(provider.GetRequiredService<WorldState>(),
        provider.GetRequiredService<DodgeContent>(), provider.GetRequiredService<ModService>(),
        provider.GetRequiredService<GameSession>(), provider.GetRequiredService<GamePresentationState>()));
    services.AddSingleton(provider => new SceneRouter(provider.GetRequiredService<GameSceneFactory>(), host, dispatcher));
    services.AddSingleton(provider => new SettingsService(host, provider.GetRequiredService<GodotFileStorage>(), launch,
        provider.GetRequiredService<DodgeLocalization>(), provider.GetRequiredService<GamePresentationState>(), provider.GetRequiredService<GameLifetime>()));
    services.AddSingleton(provider => new SaveService(provider.GetRequiredService<GodotFileStorage>(),
        provider.GetRequiredService<DodgeContent>(), provider.GetRequiredService<UiService>(),
        provider.GetRequiredService<GamePresentationState>(), provider.GetRequiredService<ModService>(), launch, provider.GetRequiredService<GameLifetime>()));
    services.AddSingleton(provider => new ContentSelectionService(provider.GetRequiredService<DodgeContent>(),
        provider.GetRequiredService<UiService>(), provider.GetRequiredService<DodgeLocalization>(), provider.GetRequiredService<GameLifetime>()));
    services.AddSingleton(provider => new GameBoardAdapter(provider.GetRequiredService<WorldState>(),
        provider.GetRequiredService<SceneRouter>(), provider.GetRequiredService<UiService>()));
    services.AddSingleton(provider => new RunUseCases(provider.GetRequiredService<GameSession>(),
        provider.GetRequiredService<GameBoardAdapter>(), provider.GetRequiredService<SaveService>()));
    services.AddSingleton(provider => new RunServices(provider.GetRequiredService<GameSession>(),
        provider.GetRequiredService<RunUseCases>(), provider.GetRequiredService<WorldState>()));
    services.AddSingleton(provider => new GameRuntimeServices(provider.GetRequiredService<PauseStackManager>(),
        provider.GetRequiredService<GodotFileStorage>(), provider.GetRequiredService<SceneRouter>(),
        provider.GetRequiredService<UiService>(), dispatcher));
    services.AddSingleton(provider => new GameFeatureServices(provider.GetRequiredService<DodgeContent>(),
        provider.GetRequiredService<SaveService>(), provider.GetRequiredService<SettingsService>(),
        provider.GetRequiredService<ModService>(), provider.GetRequiredService<ContentSelectionService>(),
        provider.GetRequiredService<RunServices>(), provider.GetRequiredService<GamePresentationState>()));
    services.AddSingleton(provider => new GameApplication(host, launch, provider.GetRequiredService<GameLifetime>(),
        provider.GetRequiredService<GameRuntimeServices>(), provider.GetRequiredService<GameFeatureServices>()));
    services.AddSingleton(provider => new DodgeMenus(provider.GetRequiredService<GameApplication>(),
        provider.GetRequiredService<GamePresentationState>(), dispatcher));
    services.AddComponent(provider => new ContentStartup(provider.GetRequiredService<DodgeContent>(), dispatcher), order: -100);
}

复核行为 ​

用 dotnet test Samples/DodgeTheCreeps.Advanced.Tests -c Release 检查业务用例。通过 godot --headless --path Samples/DodgeTheCreeps.Advanced -- --smoke 检查原生流程,并用输出标识继续跨进程检查。

Apache 2.0 许可证