0

Я пиши небольшую консольую игру на c#. У меня есть структура инвентарь

namespace FightGame.Structs
{
    public struct Inventory
    {
        private int _totalProtection = 0;
        private int _totalProtectionQuality = 0;
        private List<Item> _items;
    public int TotalProtection =&gt; _totalProtection;
    public int TotalProtectionQuality =&gt; _totalProtectionQuality; 
    public List&lt;Item&gt; Items =&gt; _items;

    #region Costructors
    public Inventory()
    {
        _items = new();
    }
    public Inventory(List&lt;Item&gt; items)
    {
        _items = items;
        foreach (var item in items)
        {
            _totalProtection += item.Protection;
            _totalProtectionQuality += item.ProtectionQuality;
        }
    }
    #endregion

    public static Inventory GenerateInventory(int countItem)
    {
        Inventory inventory = new();
        for (int i = 0; i &lt; countItem; i++)
        {
            inventory.AddItemInInventory(Item.GenerateItem($&quot;Item {i + 1}&quot;, 100, 100, 100, 3));
        }
        return inventory;
    }

    public void AddItemInInventory(Item item)
    {
        _items.Add(item);

        _totalProtection += item.Protection;
        _totalProtectionQuality += item.ProtectionQuality;
    }
    public void AddItemsInInvntory(List&lt;Item&gt; items)
    {
        foreach (var item in items)
        {
            AddItemInInventory(item);
        }
    }
    public void PrintInventory()
    {
        if (_items.Count == 0)
            Console.WriteLine(&quot;Инвентарь пуст&quot;);
        else
            foreach (Item item in _items)
                item.PrintItemInfo();
    }
    public static void PrintInventory(Inventory inventory)
    {
        if (inventory.Items.Count == 0)
            Console.WriteLine(&quot;Инвентарь пуст&quot;);
        else
            foreach (Item item in inventory.Items)
                item.PrintItemInfo();
    }
}

}

При добавлении в список предметов общая защита и общее качество защиты должны увеличиться. Самое интерестное что в списке появляется предмет, но общая защита и общее качество защиты не изменяются. Я отслеживаю это с помощью точек останова. Вот скриншоты введите сюда описание изображения

введите сюда описание изображения

using FightGame.Scripts;
using FightGame.Structs;

namespace FightGame { public static class Game { private static Player _player;

    public static Player Player =&gt; _player;

    static Game()
    {
        _player = new Player(&quot;Stepa&quot;);

        // Shop.OpenShop();

        Item item = new(&quot;Новый предмет&quot;, 10000, 456, 987, ItemType.Weapon, ItemSize.Large);


        _player.Inventory.PrintInventory();
        Console.WriteLine();

        _player.Inventory.AddItemInInventory(item);

        _player.Inventory.PrintInventory();
        Console.WriteLine();

        Console.WriteLine($&quot;Protection { _player.Inventory.TotalProtection}&quot;);
        Console.WriteLine($&quot;ProtectionQuality { _player.Inventory.TotalProtectionQuality}&quot;);

        Init();
    }
    private static void Init()
    {
        Console.WriteLine(&quot;Game Init&quot;);
        Console.WriteLine();

        //Shop.OpenShop();

    }

    public static void GameProcess()
    {
    Batlle:
        Battle.BattlePVE(World.CurrentLvl.TakeFighter());
        if (_player.Params.Health &lt;= 0 &amp;&amp; _player.Lifes &lt;= 0)
            goto GameOver;
        else
        {
            if (_player.Params.Health &lt;= 0)
                _player.Respawn();

            Console.WriteLine(&quot;Нажмите ENTER для продолжения игры&quot;);
            Console.ReadLine();
            Console.Clear();
            goto EveryStep;
        }

    EveryStep:
        _player.Gold += 5;
        _player.Regeneration();
        goto Batlle;

    GameOver:
        Console.WriteLine(&quot;Game over&quot;);
        Console.ReadLine();
    }
}

}

Это скрип в котором я вызываю метод, который добавляет предмет в инвентарь. Это структура Item.


namespace FightGame.Structs
{
    public struct Item
    {
        private string _name;
        private int _cost;
        private int _protection;
        private int _protectionQuality;
        private bool _onEquiped = false;
        private ItemType _type;
        private ItemSize _size;
    public string Name =&gt; _name;
    public int Cost =&gt; _cost;
    public int Protection
    {
        get =&gt; _protection;
        set =&gt; _protection = value;
    }

    public int ProtectionQuality
    {
        get =&gt; _protectionQuality;
        set =&gt; _protectionQuality = value;
    }
    public bool OnEquiped =&gt; _onEquiped;
    public ItemType Type =&gt; _type;
    public ItemSize Size =&gt; _size;

    public Item(string name, int cost, int protection, int protectionQuality, ItemType type, ItemSize size)
    {
        _name = name;
        _cost = cost;
        _protection = protection;
        _protectionQuality = protectionQuality;
        _type = type;
        _size = size;
    }

    public static Item GenerateItem(string name, int cost, int protection, int protectionQuality, int spread)
    {
        Random rand = new();
        //* Генерация числа 
        int GenerateNumber(int number)
        {
            if (spread == 0 &amp;&amp; spread &lt; 0)
                return number;

            int minNum = cost - (int)(cost * 0.2);
            int maxNum = cost + (int)(cost * 0.2);
            return rand.Next(minNum, maxNum);
        }

        //* Генерация случайного типа
        ItemType GenerateItemType()
        {
            switch (rand.Next(Enum.GetNames(typeof(ItemType)).Length))
            {
                case 0:
                    return ItemType.Weapon;
                case 1:
                    return ItemType.Shield;
                case 2:
                    return ItemType.Accessories;
                default:
                    return ItemType.Weapon;
            }
        }

        //* Генерация случайного размера
        ItemSize GenerateItemSize()
        {
            switch (rand.Next(Enum.GetNames(typeof(ItemSize)).Length))
            {
                case 0:
                    return ItemSize.Small;
                case 1:
                    return ItemSize.Medium;
                case 2:
                    return ItemSize.Large;
                default:
                    return ItemSize.Small;
            }
        }

        return new Item(name, GenerateNumber(cost), GenerateNumber(protection),
        GenerateNumber(protectionQuality), GenerateItemType(), GenerateItemSize());
    }

    public void PrintItemInfo()
    {
        Console.WriteLine(&quot;Name &quot; + _name);
        Console.WriteLine(&quot;Cost &quot; + _cost);
        Console.WriteLine(&quot;Protection &quot; + _protection);
        Console.WriteLine(&quot;Protection Quality &quot; + _protectionQuality);
        Console.WriteLine(&quot;Size &quot; + _size);
        Console.WriteLine(&quot;Type &quot; + _type);
        Console.WriteLine();
    }
}

public enum ItemType
{
    Weapon,
    Shield,
    Accessories
}

public enum ItemSize
{
    Small,
    Medium,
    Large
}

}

Точка входа программы

static void Main()
        {
            //Настройка UI
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.ForegroundColor = ConsoleColor.White;
            Console.Clear();
        World.SetLevels(GenerateLevels());

        Game.GameProcess();


        // World.PrintLevels();
    }

  • 2
    Вангую: Вы делаете постоянно Inventory inventory = new(); где-то и как-то (например вызываете повторно GenerateInventory(), ну а новый инвентарь == новые значения. Показывайте весь код, если не найдете причину сами. – EvgeniyZ Dec 31 '23 at 15:53
  • 1
    struct Inventory - вот причина проблем. Замените на class. – Alexander Petrov Jan 02 '24 at 15:40
  • @peter Почему так происходит? Можно ли обойти это используя структуру? – Степа Дресвянников Jan 02 '24 at 16:01

0 Answers0