-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
265 lines (219 loc) · 8.98 KB
/
Program.cs
File metadata and controls
265 lines (219 loc) · 8.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
using System;
using System.Collections.Generic;
using System.Linq;
namespace Exceptions
{
internal class Program
{
static void Main(string[] args)
{
try
{
Inventory inventory = new Inventory();
CraftingSystem craftingSystem = new CraftingSystem();
EventHandler eventHandler = new EventHandler();
eventHandler.SubscribeToCraftingSystem(craftingSystem);
Item woodStick = new Item("Палка", ItemRarity.Common);
Item stone = new Item("Камень", ItemRarity.Common);
Item rope = new Item("Верёвка", ItemRarity.Common);
Item diamond = new Item("Алмаз", ItemRarity.Epic);
inventory.AddItem(woodStick);
inventory.AddItem(woodStick);
inventory.AddItem(woodStick);
inventory.AddItem(stone);
inventory.AddItem(stone);
inventory.AddItem(rope);
inventory.AddItem(diamond);
Dictionary<Item, int> axeIngredients = new Dictionary<Item, int>();
axeIngredients.Add(woodStick, 2);
axeIngredients.Add(stone, 1);
axeIngredients.Add(rope, 1);
Dictionary<Item, int> diamondPendant = new Dictionary<Item, int>();
diamondPendant.Add(rope, 1);
diamondPendant.Add(diamond, 1);
Recipe stoneAxeRecipe = new Recipe(new Item("Каменный топор", ItemRarity.Common), axeIngredients);
Recipe diamondRecipe = new Recipe(new Item("Бриллиантовый кулон", ItemRarity.Epic), diamondPendant);
craftingSystem.AddRecipe(stoneAxeRecipe);
craftingSystem.AddRecipe(diamondRecipe);
while (true)
{
Console.WriteLine("\nВаш инвентарь:");
foreach (var item in inventory.Items)
Console.WriteLine($"- {item.Name}");
Console.Write("\nЧто крафтим? (или 'exit' для выхода): ");
string input = Console.ReadLine();
if (input?.ToLower() == "exit")
break;
if (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("Введите название предмета!");
continue;
}
Recipe recipe = craftingSystem.FindRecipeByName(input);
if (recipe == null)
{
Console.WriteLine($"Рецепт '{input}' не найден!");
continue;
}
craftingSystem.Craft(inventory, recipe);
}
}
catch (Exception ex)
{
Console.WriteLine($"Критическая ошибка в игре: {ex.Message}");
}
}
}
public enum ItemRarity
{
Common,
Rare,
Epic,
Legendary
}
public class EventHandler
{
public void SubscribeToCraftingSystem(CraftingSystem craftingSystem)
{
craftingSystem.OnItemCrafted += (item) => Console.WriteLine($"Вы скрафтили {item.Name}!");
}
}
public class Item
{
public int Id { get; }
public string Name { get; }
public ItemRarity Rarity { get; }
private static int _nextId = 0;
public Item(string name, ItemRarity rarity)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("Имя предмета не может быть пустым");
Id = _nextId++;
Name = name;
Rarity = rarity;
}
}
public class Recipe
{
public Item Result { get; }
public Dictionary<Item, int> Ingredients { get; }
public Recipe(Item result, Dictionary<Item, int> ingredients)
{
if (result == null)
{
throw new ArgumentNullException("Результат не может быть Null");
}
if (ingredients.Count <= 0)
{
throw new ArgumentNullException("Список ингредиентов не может быть пустым");
}
foreach (Item item in ingredients.Keys)
{
if (item == null)
{
throw new ArgumentNullException("Ингредиент не может быть Null");
}
}
Result = result;
Ingredients = ingredients;
}
}
public class Inventory
{
public List<Item> Items { get; } = new List<Item>();
public void AddItem(Item item)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
Items.Add(item);
}
public void RemoveItem(Item item, int count)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
if (count <= 0)
throw new ArgumentException("Количество должно быть положительным");
for (int i = 0; i < count; i++)
{
if (!Items.Remove(item))
throw new InvalidOperationException("Недостаточно предметов для удаления");
}
}
public bool HasItems(Dictionary<Item, int> requiredItems)
{
var inventoryCounts = Items.GroupBy(item => item.Id).ToDictionary(g => g.Key, g => g.Count());
foreach (var reqItem in requiredItems)
{
int requiredId = reqItem.Key.Id;
int requiredCount = reqItem.Value;
inventoryCounts.TryGetValue(requiredId, out int availableCount);
if (availableCount < requiredCount)
return false;
}
return true;
}
}
public class CraftingSystem
{
public event Action<Item> OnItemCrafted;
private List<Recipe> _availableRecipes = new List<Recipe>();
public void AddRecipe(Recipe recipe)
{
_availableRecipes.Add(recipe);
}
public Recipe FindRecipeByName(string name)
{
return _availableRecipes.FirstOrDefault(r =>
r.Result.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
}
public void Craft(Inventory inventory, Recipe recipe)
{
try
{
if (recipe == null)
throw new ArgumentNullException(nameof(recipe));
if (inventory == null)
throw new ArgumentNullException(nameof(inventory));
if (!inventory.HasItems(recipe.Ingredients))
{
var missingItems = GetMissingItems(inventory, recipe);
throw new InvalidOperationException($"Не хватает: {string.Join(", ", missingItems)}");
}
foreach (var item in recipe.Ingredients)
{
inventory.RemoveItem(item.Key, item.Value);
}
inventory.AddItem(recipe.Result);
OnItemCrafted?.Invoke(recipe.Result);
}
catch (ArgumentNullException ex)
{
Console.WriteLine($"Ошибка данных: {ex.Message}");
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Нельзя скрафтить: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Критическая ошибка: {ex.Message}");
}
}
public List<string> GetMissingItems(Inventory inventory, Recipe recipe)
{
List<string> missingItems = new List<string>();
var inventoryCounts = inventory.Items.GroupBy(i => i.Id).ToDictionary(g => g.Key, g => g.Count());
foreach (var ingredient in recipe.Ingredients)
{
int requiredId = ingredient.Key.Id;
int requiredCount = ingredient.Value;
inventoryCounts.TryGetValue(requiredId, out int availableCount);
if (availableCount < requiredCount)
{
missingItems.Add($"{ingredient.Key.Name} (нужно {requiredCount}, есть {availableCount})");
}
}
return missingItems;
}
}
}