Skip to content
简体中文

Structure an advanced Godot project ​

Run the example ​

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

Organize features ​

ProjectResponsibility
DodgeTheCreeps.Advanced.CoreGame rules, progress snapshots, and application ports
DodgeTheCreeps.AdvancedUI, native gameplay adapters, settings, and content
DodgeTheCreeps.Advanced.TestsTests for rules and use cases

Start with rules and snapshots. Define ports where the use case crosses a host boundary. The use case coordinates saving, restoring, and scoring, then reports the result to the native view.

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.");
    }
}

Compose dependencies ​

Register dependencies in the composition root. Give startup components responsibility for loading and wait for content, UI, and storage to stop before releasing native objects.

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);
}

Verify behavior ​

Run use case tests with dotnet test Samples/DodgeTheCreeps.Advanced.Tests -c Release. Run godot --headless --path Samples/DodgeTheCreeps.Advanced -- --smoke for the native flow and use its output ID to continue in a new process.

Apache License 2.0