-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLesson49.cs
More file actions
292 lines (225 loc) · 7.62 KB
/
Lesson49.cs
File metadata and controls
292 lines (225 loc) · 7.62 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
using System;
using System.Collections;
using System.Collections.Generic;
namespace Tired
{
public delegate void IUpdatableHandler(IUpdatable updatable);
public class Program
{
static void Main(string[] args)
{
Aquarium aquarium = new Aquarium();
aquarium.Update();
}
}
public sealed class Aquarium
{
private const int SecondFactor = 1000;
private const ConsoleKey KeyToRemove = ConsoleKey.Spacebar;
private const ConsoleKey KeyToAdd = ConsoleKey.Enter;
private readonly int _updatePerSecond = 2;
private UpdatablePool<Fish> _updatablePool = new UpdatablePool<Fish>();
public int MaxFishCount { get; private set; } = 16;
public Aquarium()
{
_updatablePool.GetEnumeratedPool().SetCapacity(MaxFishCount);
_updatablePool.GetEnumeratedPool().CreateInstance(new Fish("Золотая рыбка",15));
_updatablePool.GetEnumeratedPool().CreateInstance(new Fish("Синия рыбка", 7));
_updatablePool.GetEnumeratedPool().CreateInstance(new Fish("Черная рыбка", 30));
_updatablePool.GetEnumeratedPool().CreateInstance(new Fish("Лиловая рыбка", 3));
_updatablePool.GetEnumeratedPool().CreateInstance(new Fish("Красная рыбка", 12));
}
public void Update()
{
while (_updatablePool != null)
{
ShowInfo();
if(IsCapturedKey(out ConsoleKey key) == true)
{
if(key == KeyToAdd)
{
AddFishByUserInput();
}
else if(key == KeyToRemove)
{
RemoveFishByUserInput();
}
}
_updatablePool.Update();
System.Threading.Thread.Sleep(_updatePerSecond * SecondFactor);
Console.Clear();
}
}
public bool IsCapturedKey(out ConsoleKey outKey)
{
if(Console.KeyAvailable == true)
{
outKey = Console.ReadKey(true).Key;
return true;
}
outKey = default;
return false;
}
public void AddFishByUserInput()
{
string name;
if (_updatablePool.GetEnumeratedPool().Amount < MaxFishCount-1)
{
Console.Write("Новая рыбка\nВведите имя новой рыбки:");
name = Console.ReadLine();
Console.Write("\nВведите ее максимальный возраст:");
if(int.TryParse(Console.ReadLine(),out int maxAge) == true)
{
_updatablePool.Create( new Fish(name,maxAge) );
WriteSleepingLine("Рыбка добавлена!");
return;
}
}
WriteSleepingLine("Произошла ошибка!");
}
public void RemoveFishByUserInput()
{
string name;
Console.Write("Вытащить рыбку из аквариума\nВведите имя рыбки:");
name = Console.ReadLine();
Fish fish = _updatablePool.GetEnumeratedPool().FindUpdatableObject(fish => fish.Name == name);
if(fish != null)
{
fish.Destroy();
WriteSleepingLine("Рыбка удалена с аквириума!");
}
else
{
WriteSleepingLine("Такой рыбки нет!");
}
}
public void WriteSleepingLine(string text)
{
Console.WriteLine(text);
System.Threading.Thread.Sleep(_updatePerSecond * SecondFactor);
}
public void ShowInfo()
{
Console.WriteLine("----------Рыбки стареют раз в "+_updatePerSecond+" секунды!------------\n");
Console.WriteLine("Введите "+KeyToAdd+" чтобы добавить рыбку\nВведите "+KeyToRemove+" чтобы вытащить рыбку\n");
}
}
public sealed class Fish : IUpdatable
{
private static string[] _actionnames = {"плавает","спит","кушает","пялится в стенку аквариума","какает","мертва"};
private int _currentActionID = 0;
private int _deathActionID = 5;
public int MaxAge { get; private set; } = 10;
public int CurrentAge { get; private set; } = 0;
public bool IsDropped { get; private set; } = false;
public bool IsDestroyed => IsDropped;
public string Name { get; private set; } = "Безымянная рыбка";
public Fish(string name,int maxAge)
{
Name = name;
MaxAge = maxAge;
}
public void Destroy() => IsDropped = true;
public void ChooseRandomAction() => _currentActionID = Helper.GetRandomValue(0, _actionnames.Length - 1);
public string GetCurrentAction() => _actionnames[_currentActionID];
public void Draw()
{
string lineInfo = "Рыбка " + Name + ", " + CurrentAge + " лет, ";
Console.WriteLine(lineInfo + GetCurrentAction());
}
public void Update()
{
if (CurrentAge >= MaxAge)
{
_currentActionID = _deathActionID;
}
if (_currentActionID != _deathActionID)
{
CurrentAge++;
ChooseRandomAction();
}
}
}
public class EnumeratedPool<T> : IEnumerable where T : IUpdatable
{
private readonly List<T> _updateablesList = null;
public int Capacity { get; private set; } = 256;
public int Amount
{
get
{
return _updateablesList.Count;
}
}
public EnumeratedPool(List<T> updatables) => _updateablesList = updatables;
public int SetCapacity(int capacity) => Capacity = capacity;
public void CreateInstance(T instance)
{
if (_updateablesList.Count < Capacity)
{
_updateablesList.Add(instance);
}
}
public List<T> FindAllUpdatableObject(Predicate<T> predicate) => _updateablesList.FindAll(predicate);
public T FindUpdatableObject(Predicate<T> predicate) => _updateablesList.Find(predicate);
public T GetUpdatableObjectByIndex(int index)
{
if (_updateablesList == null || _updateablesList.Count == 0
|| (index<0 && index>=_updateablesList.Count) ) return default(T);
return _updateablesList[index];
}
public IEnumerator GetEnumerator()=> _updateablesList.GetEnumerator();
}
public class UpdatablePool<T> where T : IUpdatable
{
private readonly EnumeratedPool<T> _protectedPool = null;
private readonly List<T> _updatablesList = new List<T>();
private readonly List<int> _garbageIndexList = new List<int>();
private event IUpdatableHandler _onDestroyEvent;
public UpdatablePool()
{
_protectedPool = new EnumeratedPool<T>(_updatablesList);
}
public EnumeratedPool<T> GetEnumeratedPool() => _protectedPool;
private void CollectGarbage()
{
for(int i = _garbageIndexList.Count-1; i >=0; i--)
{
_updatablesList.RemoveAt(_garbageIndexList[i]);
}
_garbageIndexList.Clear();
}
public void Update()
{
for (int i = 0; i < _updatablesList.Count; i++)
{
T updatable = _updatablesList[i];
if(updatable.IsDestroyed == false)
{
updatable.Update();
updatable.Draw();
}
else
{
_onDestroyEvent?.Invoke(updatable);
_garbageIndexList.Add(i);
}
}
CollectGarbage();
}
public void Create(T entity) => _updatablesList.Add(entity);
public void AddListenerOnDestroyEvent(IUpdatableHandler updatableHandler) => _onDestroyEvent += updatableHandler;
public void RemoveListenerOnDestroyEvent(IUpdatableHandler updatableHandler) => _onDestroyEvent -= updatableHandler;
}
public interface IUpdatable
{
public bool IsDestroyed { get; }
public void Destroy();
public void Update();
public void Draw();
}
public static class Helper
{
public static int GetRandomValue(int minValue = 0, int maxValue = 1) => new Random().Next(minValue,maxValue);
}
}