你的游戏代码何时会感觉到“合适”的?你的代码何时会足够好,以至于你可以实际做点什么,并且不再经常遇到它会阻碍你?我是指,很容易只是用胶水把一些东西粘起来,但是要做到长期和生产级别的东西,这是挑战。

很多时候,我不知道我是写出了聪明的代码,还是对一个简单的功能进行了过度设计。例如,我将展示我如何在我的持续性回合型迷宫游戏(Godot 4.6 .NET)中处理“丢弃物品”的方式。这个游戏我已经在开发了大约6个月了,除了全职工作之外。

public class DropItemCommand(int entityId, int itemId, int tuCost) : IActorCommand
{
    public int CostTu { get; } = tuCost;
    private InventoryTrait _inventory;
    private Vector2I _entityPosition;
    private string _entityName;
    private string _itemName;

    public bool Prepare(IWorldQuery world, out string reason)
    {
        if (!world.TryGetEntity(entityId, out var entity))
        {
            reason = $"Entity {entityId} must exist";
            return false;
        }
        _entityName = entity.DisplayName;

        if (!world.TryGetEntityCell(entityId, out _entityPosition))
        {
            reason = $"Entity {entityId} must exist";
            return false;
        }
        if (!entity.TryGetTrait(out _inventory))
        {
            reason = $"Entity {entityId} must have inventory trait";
            return false;
        }
        if (!world.TryGetEntity(itemId, out var item))
        {
            reason = $"Item {itemId} must exist";
            return false;
        }

        _itemName = item.DisplayName;

        if (!_inventory.Contains(itemId))
        {
            reason = $"Entity {entityId} does not have item {itemId}";
            return false;
        }

        reason = string.Empty;
        return true;

    }

    public IEnumerable<IPlayableEvent> Execute<TWorld>(TWorld world) where TWorld : IWorldQuery, IWorldMutator
    {
        _inventory.Remove(itemId);
        world.TryDropToGround(itemId, _entityPosition);
        yield return new RenderEntityEvent(itemId);
        yield return new MessageLogEvent($"{_entityName} dropped {_itemName} at {_entityPosition}");
    }
}

看起来似乎是一个很长的代码片段来完成一个简单的任务,当然一些检查可能是多余的,但我感觉这里每一行代码都有一个目的,确保我的游戏不会爆炸,而且所有事情都发生在正确的时间。目前我感觉我的游戏正在逐渐地变得完整,架构也开始变得合理和功能良好。但是,我还是无法帮助自己怀疑我正在做的事情会变成垃圾。

总之,我会感激任何关于这个话题的故事或想法。