-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLesson44.cs
More file actions
678 lines (524 loc) · 20 KB
/
Lesson44.cs
File metadata and controls
678 lines (524 loc) · 20 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
using System;
using System.Collections.Generic;
namespace Tired
{
class Program
{
static void Main(string[] args)
{
DirectionPathOrganizer directionPathHandler = new DirectionPathOrganizer(3);
UserInputMenu menu = new UserInputMenu(directionPathHandler);
menu.Update();
}
}
class UserInputMenu
{
private const string WordToExit = "выход";
private const string WordToCreateDirection = "создать_направление";
private const string WordToSellTicket = "продать_билеты";
private const string WordToCreateTrain = "создать_поезд";
private const string WordToCreateCarriages = "создать_вагоны";
private const string WordToDepart = "отправить_поезд";
private const string WordToClear = "очистить";
private string _wordToRead;
private DirectionPathOrganizer _directionPathHandler;
public UserInputMenu(DirectionPathOrganizer directionPathHandler)
{
_directionPathHandler = directionPathHandler;
}
public void Update()
{
while (_directionPathHandler != null && _wordToRead != WordToExit)
{
ShowMenu();
Console.Write("\nВвод:");
_wordToRead = Console.ReadLine();
Console.WriteLine();
switch (_wordToRead)
{
case WordToExit:
break;
case WordToClear:
Console.Clear();
break;
case WordToCreateDirection:
CreateDirectionPathByUser();
break;
case WordToCreateTrain:
CreateTrainByUser();
break;
case WordToCreateCarriages:
CreateCarriageByUser();
break;
case WordToSellTicket:
SellTicketsByUser();
break;
case WordToDepart:
DepartDirectionByUser();
break;
}
}
}
private void CreateDirectionPathByUser()
{
DirectionPath direction;
if(TryReadDirectionPathByUser(out string arrivalName, out string departName) == true)
{
direction = new DirectionPath(departName, arrivalName);
_directionPathHandler.Add(direction);
Console.WriteLine(direction.ToString() + " создано!");
}
}
private bool TryReadDirectionPathByUser(out string arrivalPoint, out string departurePoint)
{
Console.Write("Введите точку прибытия:");
arrivalPoint = Console.ReadLine();
Console.Write("Введите точку посадки:");
departurePoint = Console.ReadLine();
if (arrivalPoint == "" || departurePoint == "")
{
Console.WriteLine("Ошибка ввода");
return false;
}
return true;
}
private DirectionPath GetDirectionPathByReadLine()
{
if (TryReadDirectionPathByUser(out string arrivalName, out string departName) == true)
{
return _directionPathHandler.FindDirectionPathByPoints(arrivalName, departName);
}
return null;
}
private void CreateTrainByUser()
{
string trainNumber;
DirectionPath direction;
Train train;
Console.WriteLine("Организация поезда");
Console.WriteLine("Введите данные направления, к которому будет присоединен поезд");
direction = GetDirectionPathByReadLine();
if (direction != null)
{
Console.Write("\nВведите номер поезда:");
trainNumber = Console.ReadLine();
if (trainNumber != "")
{
train = new Train(trainNumber);
if (direction.TryJoinTrain(train) == true)
{
Console.WriteLine(train.ToString() + " создан и прикреплен к направлению!");
}
}
return;
}
Console.WriteLine("Произошла ошибка при создании поезда...");
}
private void CreateCarriageByUser()
{
DirectionPath direction;
Console.WriteLine("Присоединение вагона к поезду");
Console.WriteLine("Осуществите поиск направления:");
direction = GetDirectionPathByReadLine();
if (direction != null && direction.HasTrain() == true && direction.IsTrainDeparted() == false)
{
Console.WriteLine(direction.ToAdvancedString());
Console.Write("Введите размер вагона(короткий,средний, длинный):");
switch (Console.ReadLine())
{
case "короткий":
direction.JoinCarriageToTrain(new Carriage(СarriageСapacityTypes.Short));
break;
case "средний":
direction.JoinCarriageToTrain(new Carriage(СarriageСapacityTypes.Medium));
break;
case "длинный":
direction.JoinCarriageToTrain(new Carriage(СarriageСapacityTypes.Long));
break;
}
return;
}
Console.WriteLine("Ошибка в создании вагона...");
}
private void SellTicketsByUser()
{
DirectionPath direction;
Console.WriteLine("\nПродажа билетов\nОсуществите поиск направления:");
direction = GetDirectionPathByReadLine();
if (direction != null)
{
direction.ShowWaitingList();
Console.Write("\nВведите номер пассажира для резерва пассажирского места:");
if ((int.TryParse(Console.ReadLine(), out int index) == true) && (direction.TryAddPassengerFromWaitingList(index) == true))
{
Console.WriteLine("Билет продан!");
}
return;
}
Console.WriteLine("Ошибка продажи билета...");
}
private void DepartDirectionByUser()
{
DirectionPath direction;
Console.WriteLine("Присоединение вагона к поезду");
Console.WriteLine("Осуществите поиск направления:");
direction = GetDirectionPathByReadLine();
if(direction.HasTrain() == true && direction.IsTrainDeparted() == true)
{
direction.DepartTrain();
}
else
{
Console.WriteLine("У данного направления нет поезда или он отправлен!");
}
}
private void ShowMenu()
{
Console.WriteLine("\n---Меню управление отправкой поездов дальнего следования---");
Console.WriteLine("Введите <" + WordToExit + "> для выхода из программы");
Console.WriteLine("Введите <" + WordToClear + "> для очистки консоли");
Console.WriteLine("Введите <" + WordToCreateDirection + "> чтобы создать направление следования");
Console.WriteLine("Введите <" + WordToSellTicket + "> чтобы продать билеты");
Console.WriteLine("Введите <" + WordToCreateTrain + "> чтобы создать поезд");
Console.WriteLine("Введите <" + WordToCreateCarriages + "> чтобы прицепить вагон");
Console.WriteLine("Введите <" + WordToDepart + "> чтобы отправить поезд");
Console.WriteLine();
_directionPathHandler.ShowDirections();
}
}
class DirectionPathOrganizer
{
private List<DirectionPath> _directions = new List<DirectionPath>();
public readonly int maxDirectionsCount;
public int CurrentDirectionPathCount
{
get
{
return _directions.Count;
}
}
public DirectionPathOrganizer(int maxCount)
{
maxDirectionsCount = maxCount;
}
public void Add(DirectionPath direction)
{
if (_directions.Count < maxDirectionsCount)
{
_directions.Add(direction);
}
}
public void ShowDirections()
{
Console.WriteLine("---Организованные направления---");
for (int i = 0; i < _directions.Count; i++)
{
Console.Write(" [" + i + "] " + _directions[i].ToAdvancedString());
}
}
public DirectionPath FindDirectionPathByPoints(string arrivalPoint,string departurePoint)
{
return _directions.Find(direction => direction.ArrivalPoint.Equals(arrivalPoint) && direction.DeparturePoint.Equals(departurePoint));
}
}
class DirectionPath
{
private List<PassengerPlace> _waitingPassengerList = new List<PassengerPlace>();
private Train _currentTrain;
public string DeparturePoint { get; private set; }
public string ArrivalPoint { get; private set; }
public int WaitingPassengerCount
{
get
{
return _waitingPassengerList.Count;
}
}
public DirectionPath(string departurePoint, string arrivalPoint)
{
DeparturePoint = departurePoint;
ArrivalPoint = arrivalPoint;
_waitingPassengerList.AddRange(PassengerRandomizer.CreatePassengerArray());
}
public bool TryJoinTrain(Train train)
{
if (train == null || (_currentTrain != null && _currentTrain.IsDeparted == true) )
{
return false;
}
_currentTrain = train;
return true;
}
public bool TryAddPassengerFromWaitingList(int index)
{
if (_currentTrain == null)
{
return false;
}
if ( (index >= 0 && index < WaitingPassengerCount) && _currentTrain.TryAddPassenger(_waitingPassengerList[index]) == true )
{
_waitingPassengerList.RemoveAt(index);
return true;
}
return false;
}
public void ShowWaitingList()
{
Console.WriteLine("Список пассажиров ждущих поезда:");
for(int i = 0; i < WaitingPassengerCount; i++)
{
Console.WriteLine("[" + i + "] " + _waitingPassengerList[i].ToString());
}
Console.WriteLine();
}
public override string ToString()
{
return "Направление " + DeparturePoint + " - " + ArrivalPoint;
}
public string ToAdvancedString()
{
return (_currentTrain != null) ? (ToString() + ":" + _currentTrain?.ToAdvancedString() + ", ждущие пассажиры:" + WaitingPassengerCount) : ToString();
}
public bool HasTrain() => (_currentTrain != null);
public bool IsTrainDeparted() => (_currentTrain != null) ? _currentTrain.IsDeparted : false;
public void JoinCarriageToTrain(Carriage carriage) => _currentTrain?.JoinCarriage(carriage);
public void DepartTrain() => _currentTrain?.Depart();
}
class Train
{
private List<Carriage> _carriages = new List<Carriage>();
public int CarriageCount
{
get
{
return _carriages.Count;
}
}
public string Number { get; private set; }
public bool IsDeparted { get; private set; } = false;
public Train(string number) => Number = number;
public void JoinCarriage(Carriage carriage)
{
if (IsDeparted == true)
{
Console.WriteLine("Поезд отправлен, сцепка вагона запрещена!");
return;
}
_carriages.Add(carriage);
Console.WriteLine("Вагон сцеплен!");
}
public void ShowFullPassengerList()
{
Console.WriteLine("Список пассажиров поезда " + Number);
foreach (Carriage car in _carriages)
{
car.ShowPassengerList();
}
}
public void ShowCarriageInfoByIndex(int index)
{
if (index >= 0 && index < _carriages.Count)
{
_carriages[index].ShowPassengerList();
}
}
public int GetPlacesCount()
{
int count = 0;
foreach (Carriage car in _carriages)
{
count += car.GetPlaceCount();
}
return count;
}
public int GetOccupiedPlaces() => (GetPlacesCount() - GetFreePlaces());
public int GetFreePlaces()
{
int count = 0;
foreach (Carriage car in _carriages)
{
count += car.GetFreePlaceCount();
}
return count;
}
public override string ToString()
{
return "Поезд #" + Number;
}
public string ToAdvancedString()
{
return ToString() + " [Всего мест:" + GetPlacesCount() + ", занятых:" + GetOccupiedPlaces() + ", свободных:" + GetFreePlaces() + "]";
}
public bool TryAddPassenger(PassengerPlace place)
{
if (IsDeparted == true)
{
return false;
}
foreach (Carriage car in _carriages)
{
if (car.TryAddPassenger(place) == true)
{
return true;
}
}
return false;
}
public void Depart() => IsDeparted = true;
}
enum СarriageСapacityTypes
{
Short = 16,
Medium = 32,
Long = 64,
}
class Carriage
{
private const int BadIndex = -1;
private PassengerPlace[] _passengerPlaces;
public Carriage(СarriageСapacityTypes type)
{
_passengerPlaces = new PassengerPlace[(int)type];
ClearPassengerPlaces();
}
public void ShowPassengerList()
{
Console.WriteLine("Список пассажиров вагона:");
for (int i = 0; i < _passengerPlaces.Length; i++)
{
PassengerPlace place = _passengerPlaces[i];
if (place.IsFree() == false)
{
Console.WriteLine("Место #" + i + " занято " + _passengerPlaces[i].ToString());
}
else
{
Console.WriteLine("Место #" + i + " свободно");
}
}
Console.WriteLine();
}
public void ClearPassengerPlaces()
{
for (int i = 0; i < _passengerPlaces.Length; i++)
{
_passengerPlaces[i].Clear();
}
}
public int GetPlaceCount() => _passengerPlaces.Length;
public int GetOccupiedPlaceCount() => (GetPlaceCount() - GetFreePlaceCount());
public int GetFreePlaceCount()
{
int count = 0;
for (int i = 0; i < _passengerPlaces.Length; i++)
{
if (_passengerPlaces[i].IsFree() == true)
{
count++;
}
}
return count;
}
public bool TryAddPassenger(PassengerPlace place)
{
for (int i = 0; i < _passengerPlaces.Length; i++)
{
if (_passengerPlaces[i].IsFree() == true)
{
_passengerPlaces[i] = place;
return true;
}
}
return false;
}
public bool TryRemovePassenger(PassengerPlace place)
{
int index = FindIndexByPassengerPlace(place);
if (index != BadIndex)
{
_passengerPlaces[index].Clear();
return true;
}
return false;
}
private int FindIndexByPassengerPlace(PassengerPlace place)
{
for (int i = 0; i < _passengerPlaces.Length; i++)
{
if (_passengerPlaces[i].Equals(place) == true)
{
return i;
}
}
return BadIndex;
}
}
struct PassengerPlace
{
public string FullName { get; private set; }
public string Passport { get; private set; }
public PassengerPlace(string fullname, string passport)
{
FullName = fullname;
Passport = passport;
}
public void SetFullName(string name) => FullName = name;
public void SetPassport(string passport) => Passport = passport;
public void Clear()
{
FullName = "";
Passport = "";
}
public bool IsFree() => (FullName == "" && Passport == "");
public override string ToString()
{
return FullName + " " + Passport;
}
}
static class PassengerRandomizer
{
public const int MinRandomBound = 10;
public const int MaxRandomBound = 256;
private static string[] _names = {
"Иван",
"Анатолий",
"Сергей",
"Александр",
"Наталья",
"Александра",
"Яна",
"Алена"
};
private static string[] _surnames = {
"Прививко",
"Копилко",
"Монетко",
"Буренко",
"Бобовко",
"Чубайко",
"Креветко",
"Деревко"
};
public static PassengerPlace[] CreatePassengerArray()
{
int randomCount = new Random().Next(MinRandomBound, MaxRandomBound);
PassengerPlace[] passengerPlaces = new PassengerPlace[randomCount];
for (int i = 0; i < randomCount; i++)
{
passengerPlaces[i] = CreatePassenger();
}
return passengerPlaces;
}
public static PassengerPlace CreatePassenger() => new PassengerPlace(CreateFullname(), CreatePassport());
private static string CreateFullname()
{
Random random = new Random();
return _names[random.Next(0, _names.Length)] + " " + _surnames[random.Next(0, _surnames.Length)];
}
private static string CreatePassport()
{
Random random = new Random();
return random.Next(1000, 10000).ToString() + " " + random.Next(100000, 1000000).ToString();
}
}
}