Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Text;
- class Program
- {
- internal static void Main()
- {
- var carService = new CarService(new Money(10000), new Warehouse(ProductFactory.Create()), CarFactory.Create());
- var menu = new Menu(carService);
- menu.Run();
- }
- }
- public interface IInsertActions
- {
- Dictionary<string, Action> GetCommands();
- Func<bool> ExitCommand { get; }
- }
- public class Menu
- {
- private const string HelpCommand = "help";
- private const string ExitCommand = "exit";
- private readonly Dictionary<string, Action> _actionCommands;
- private readonly Func<bool> _exitFunc;
- public Menu(IInsertActions insertActions)
- {
- _actionCommands = insertActions.GetCommands();
- _exitFunc = insertActions.ExitCommand;
- }
- public void Run()
- {
- bool isExit = false;
- while (isExit == false)
- {
- Console.Write($"Введите команду (список всех команд - '{HelpCommand}'): ");
- string command = Console.ReadLine();
- switch (command)
- {
- case ExitCommand:
- isExit = _exitFunc.Invoke();
- break;
- case HelpCommand:
- Console.WriteLine($"{ExitCommand}, {string.Join(", ", _actionCommands.Keys)}");
- break;
- default:
- ExecuteImportedMethod(command);
- break;
- }
- }
- }
- private void ExecuteImportedMethod(string command)
- {
- if (_actionCommands.ContainsKey(command))
- {
- _actionCommands[command].Invoke();
- }
- else
- {
- Console.WriteLine("Команда не найдена.");
- }
- }
- }
- public static class UserUtils
- {
- private static Random s_random = new Random();
- public static int GenerateRandomNumber(int min, int max)
- {
- return s_random.Next(min, max);
- }
- public static int GenerateRandomNumber(int length)
- {
- return s_random.Next(length);
- }
- public static int ReadNumberConsole(int min = int.MinValue, int max = int.MaxValue)
- {
- int resultNumber;
- while (int.TryParse(Console.ReadLine(), out resultNumber) == false || resultNumber < min || resultNumber > max)
- {
- Console.Write("Неверный номер. Введите еще.");
- }
- return resultNumber;
- }
- }
- public class Award
- {
- public Award(int earned, int fine)
- {
- Earned = earned;
- Fine = fine;
- }
- public int Earned { get; }
- public int Fine { get; }
- }
- public class Car
- {
- private readonly IPart[] _parts;
- public Car(string model, string serial, int yearProduction, IPart[] parts)
- {
- Model = model;
- Serial = serial;
- YearProduction = yearProduction;
- _parts = parts;
- }
- public int NumberDetails => _parts.Length;
- public string Model { get; }
- public string Serial { get; }
- public int YearProduction { get; }
- public string GetInfo()
- {
- var info = new StringBuilder();
- for (int i = 0; i < _parts.Length; i++)
- {
- info.AppendLine($"{i}. {_parts[i].GetInfo()}");
- }
- return info.ToString();
- }
- public bool TryReplacePart(int idPartCar, PartBase partWarehouse, out string message)
- {
- IPart carPart = _parts[idPartCar];
- if (carPart == null || partWarehouse == null)
- {
- message = "Отсутствует одна или несколько деталей";
- return false;
- }
- if (carPart.Name != partWarehouse.Name)
- {
- message = "Деталь не подходит для замены.";
- return false;
- }
- if (carPart.IsBroken == false)
- {
- message = "Деталь не сломана - вы не получите оплату за ремонт целой детали.";
- return false;
- }
- _parts[idPartCar] = partWarehouse;
- message = "Сломанная деталь успешно заменена на новую.";
- return true;
- }
- public PartBase[] GetCloneParts()
- {
- return _parts.Select(p => p.Clone()).ToArray();
- }
- }
- public class CarFactory
- {
- public static Car[] Create()
- {
- return new Car[]
- {
- new Car("Audi", "A4", 2010, PartFactory.CreateParts()),
- new Car("BMW", "X5", 2015, PartFactory.CreateParts()),
- new Car("Mercedes", "S500", 2020, PartFactory.CreateParts())
- };
- }
- }
- class CarService : IInsertActions
- {
- private readonly Money _money;
- private readonly Queue<Car> _cars;
- private readonly Warehouse _warehouse;
- private Repair _repair;
- public CarService(Money money, Warehouse warehouse, Car[] cars)
- {
- _money = money;
- _cars = new Queue<Car>(cars);
- _warehouse = warehouse;
- }
- public Func<bool> ExitCommand => () => true;
- public Dictionary<string, Action> GetCommands()
- {
- return new Dictionary<string, Action>()
- {
- {"nextcar", GetInfoNextCar},
- {"rejectcar", RejectCar},
- {"repaircar", RepairCar},
- {"parts", ShowMyParts},
- {"balance", () => Console.WriteLine($"Баланс: {_money.Amount} руб.")}
- };
- }
- private void ShowMyParts()
- {
- Console.WriteLine("Детали в складе:");
- Console.WriteLine(_warehouse.GetInfo());
- }
- private void GetInfoNextCar()
- {
- Console.WriteLine("Авто из очереди:");
- if (_cars.TryPeek(out Car car) == false)
- {
- Console.WriteLine("В очереди нет машин.");
- return;
- }
- Console.WriteLine(car.GetInfo());
- }
- private void RejectCar()
- {
- Order order = new Order();
- if (TryCalcMoney(order))
- {
- _cars.Dequeue();
- }
- }
- private void RepairCar()
- {
- if (_repair != null)
- {
- Console.WriteLine("Текущий ремонт еще не закончен.");
- return;
- }
- if (_cars.TryDequeue(out Car car) == false)
- {
- Console.WriteLine("В очереди нет машин.");
- return;
- }
- Order order = new Order(car.GetCloneParts());
- _repair = new Repair(car, _warehouse);
- Console.WriteLine("Авто отправлено на ремонт.");
- _repair.Work();
- if (TryCalcMoney(order, car.GetCloneParts()))
- {
- _repair = null;
- }
- else
- {
- Console.WriteLine("Автосервис разорен.");
- }
- }
- private bool TryCalcMoney(Order order, PartBase[] parts = null)
- {
- Award award = order.CalculateMoney(parts);
- _money.TryAdd(award.Earned);
- if (_money.TryRemove(award.Fine) == false)
- {
- Console.WriteLine("Автосервис не может оплатить штарф и поэтому разорен.");
- return false;
- }
- Console.WriteLine($"Штраф составил: {award.Fine} руб.");
- Console.WriteLine($"Вы заработали: {award.Earned} руб.");
- Console.WriteLine($"Баланс: {_money.Amount} руб.");
- return true;
- }
- }
- public class Engine : PartBase
- {
- public Engine(bool isBroken) : base(isBroken)
- {
- }
- public override string Name => "Двигатель";
- public override int Price => 100000;
- public override int PriceRepair => 10000;
- public override int Fine => 2000;
- public override PartBase Clone()
- {
- return new Engine(IsBroken);
- }
- }
- public class Filter : PartBase
- {
- public Filter(bool isBroken) : base(isBroken)
- {
- }
- public override string Name => "Фильтр";
- public override int Price => 1000;
- public override int PriceRepair => 100;
- public override int Fine => 20;
- public override PartBase Clone()
- {
- return new Filter(IsBroken);
- }
- }
- public class Gearbox : PartBase
- {
- public Gearbox(bool isBroken) : base(isBroken)
- {
- }
- public override string Name => "Коробка передач";
- public override int Price => 10000;
- public override int PriceRepair => 1000;
- public override int Fine => 200;
- public override PartBase Clone()
- {
- return new Gearbox(IsBroken);
- }
- }
- public interface IPart
- {
- string Name { get; }
- bool IsBroken { get; }
- PartBase Clone();
- string GetInfo();
- }
- public interface IPrice : IPart
- {
- int Price { get; }
- int PriceRepair { get; }
- int Fine { get; }
- }
- class Money
- {
- public Money(int amount)
- {
- Amount = amount;
- }
- public int Amount { get; private set; }
- public bool TryAdd(int amount)
- {
- if (amount < 0)
- {
- return false;
- }
- Amount += amount;
- return true;
- }
- public bool TryRemove(int amount)
- {
- if (amount > Amount)
- {
- return false;
- }
- Amount -= amount;
- return true;
- }
- }
- public class Muffler : PartBase
- {
- public Muffler(bool isBroken) : base(isBroken)
- {
- }
- public override string Name => "Глушитель";
- public override int Price => 1000;
- public override int PriceRepair => 100;
- public override int Fine => 20;
- public override PartBase Clone()
- {
- return new Muffler(IsBroken);
- }
- }
- public class Order
- {
- private const int FixFine = 1000;
- private readonly Dictionary<int, Product> _brokenParts = new();
- public Order(IPrice[] parts)
- {
- for (int i = 0; i < parts.Length; i++)
- {
- var part = parts[i];
- if (part.IsBroken == false)
- {
- continue;
- }
- _brokenParts.Add(i, new Product((PartBase)part));
- }
- }
- public Order()
- {
- }
- public bool IsRepair => _brokenParts.Count > 0;
- public Award CalculateMoney(PartBase[] carParts = null)
- {
- int earned = 0;
- int fine = 0;
- if (IsRepair == false)
- {
- return new Award (0, FixFine);
- }
- foreach (var product in _brokenParts)
- {
- if (carParts[product.Key].IsBroken)
- {
- fine += product.Value.Fine;
- }
- else
- {
- earned += product.Value.Price;
- }
- }
- return new Award(earned, fine);
- }
- }
- public abstract class PartBase : IPart, IPrice
- {
- public PartBase(bool isBroken)
- {
- IsBroken = isBroken;
- }
- public abstract string Name { get; }
- public bool IsBroken { get; }
- public abstract PartBase Clone();
- public abstract int Price { get; }
- public abstract int PriceRepair { get; }
- public abstract int Fine { get; }
- public string GetInfo()
- {
- string status = IsBroken ? "сломана" : "работает";
- return $"{Name}, состояние - {status}.";
- }
- }
- public class PartFactory
- {
- public static IPart[] CreateParts()
- {
- const int minRange = 0;
- const int maxRange = 2;
- IPart[] parts = new PartBase[]
- {
- new Wheel(UserUtils.GenerateRandomNumber(minRange, maxRange) > 0),
- new Suspension(UserUtils.GenerateRandomNumber(minRange, maxRange) > 0),
- new Muffler(UserUtils.GenerateRandomNumber(minRange, maxRange) > 0),
- new Gearbox(UserUtils.GenerateRandomNumber(minRange, maxRange) > 0),
- new Filter(UserUtils.GenerateRandomNumber(minRange, maxRange) > 0),
- new Engine(UserUtils.GenerateRandomNumber(minRange, maxRange) > 0)
- };
- if (parts.Where(p => p.IsBroken == true).Count() == 0)
- {
- parts[UserUtils.GenerateRandomNumber(0, parts.Length)] = new Wheel(true);
- }
- return parts;
- }
- }
- public class Product
- {
- private readonly PartBase _part;
- public Product(PartBase part, int count = 1)
- {
- _part = part;
- Count = count;
- }
- public int Count { get; private set; }
- public int Price => _part.Price;
- public int PriceRepair => _part.PriceRepair;
- public int Fine => _part.Fine;
- public string Name => _part.Name;
- public bool TryGetPart(out PartBase part)
- {
- if (Count == 0)
- {
- part = null;
- return false;
- }
- part = _part.Clone();
- Count--;
- return true;
- }
- }
- public class ProductFactory
- {
- public static Product[] Create(int minRange = 1, int maxRange = 5)
- {
- return new Product[]
- {
- new Product(new Engine(false), UserUtils.GenerateRandomNumber(minRange, maxRange)),
- new Product(new Filter(false), UserUtils.GenerateRandomNumber(minRange, maxRange)),
- new Product(new Gearbox(false), UserUtils.GenerateRandomNumber(minRange, maxRange)),
- new Product(new Muffler(false), UserUtils.GenerateRandomNumber(minRange, maxRange)),
- new Product(new SparkPlug(false), UserUtils.GenerateRandomNumber(minRange, maxRange)),
- new Product(new Suspension(false), UserUtils.GenerateRandomNumber(minRange, maxRange)),
- new Product(new Wheel(false), UserUtils.GenerateRandomNumber(minRange, maxRange)),
- };
- }
- }
- public class Repair
- {
- private readonly Car _car;
- private readonly Warehouse _warehouse;
- public Repair(Car car, Warehouse warehouse)
- {
- _car = car;
- _warehouse = warehouse;
- }
- public void Work()
- {
- const string ExitCommand = "exit";
- const string PartCommand = "part";
- bool isExit = false;
- string command = "";
- while (isExit == false)
- {
- Console.WriteLine($"{ExitCommand} - прекратить ремонт, {PartCommand} - заменить деталь.");
- command = Console.ReadLine();
- switch (command)
- {
- case PartCommand:
- ReplacPart();
- break;
- case ExitCommand:
- isExit = true;
- break;
- default:
- Console.WriteLine($"Неизвестная команда - \"{command}\".");
- break;
- }
- }
- }
- private void ReplacPart()
- {
- Console.WriteLine("Детали авто:");
- Console.WriteLine(_car.GetInfo());
- Console.Write("Введите номер детали авто: ");
- int idPartCar = UserUtils.ReadNumberConsole(0, _car.NumberDetails);
- Console.WriteLine();
- Console.WriteLine("Детали склада:");
- Console.WriteLine();
- Console.WriteLine(_warehouse.GetInfo());
- Console.WriteLine();
- Console.Write("Введите номер детали склада: ");
- int idPartWarehouse = UserUtils.ReadNumberConsole(0, _warehouse.CountDetails);
- if (_warehouse.TryGetProduct(idPartWarehouse, out PartBase partWarehouse, out string errorGetPart) == false)
- {
- Console.WriteLine(errorGetPart);
- return;
- }
- if (_car.TryReplacePart(idPartCar, partWarehouse, out string messageReplacePart) == false)
- {
- Console.WriteLine($"Ошибка при замене детали: {messageReplacePart}");
- return;
- }
- Console.WriteLine(messageReplacePart);
- }
- }
- public class SparkPlug : PartBase
- {
- public SparkPlug(bool isBroken) : base(isBroken)
- {
- }
- public override string Name => "Свеча зажигания";
- public override int Price => 100;
- public override int PriceRepair => 10;
- public override int Fine => 2;
- public override PartBase Clone()
- {
- return new SparkPlug(IsBroken);
- }
- }
- public class Suspension : PartBase
- {
- public Suspension(bool isBroken) : base(isBroken)
- {
- }
- public override string Name => "Подвеска";
- public override int Price => 1000;
- public override int PriceRepair => 100;
- public override int Fine => 20;
- public override PartBase Clone()
- {
- return new Suspension(IsBroken);
- }
- }
- public class Warehouse
- {
- private readonly Product[] _products;
- public Warehouse(Product[] products)
- {
- _products = products;
- }
- public int CountDetails => _products.Sum(p => p.Count);
- public string GetInfo()
- {
- var info = new StringBuilder();
- for (int i = 0; i < _products.Length; i++)
- {
- info.AppendLine($"{i}. {_products[i].Name}, цена - {_products[i].Price}, цена замены - {_products[i].PriceRepair}, количество - {_products[i].Count} шт.");
- }
- return info.ToString();
- }
- public bool TryGetProduct(int idProduct, out PartBase part, out string errorMessage)
- {
- if (idProduct < 0 || idProduct >= _products.Length)
- {
- part = null;
- errorMessage = $"Неверный номер детали: {idProduct}";
- return false;
- }
- if (_products[idProduct].TryGetPart(out part) == false)
- {
- errorMessage = "Детали закончились";
- return false;
- }
- errorMessage = string.Empty;
- return true;
- }
- }
- public class Wheel : PartBase
- {
- public Wheel(bool isBroken) : base(isBroken)
- {
- }
- public override string Name => "Колесо";
- public override int Price => 5000;
- public override int PriceRepair => 500;
- public override int Fine => 100;
- public override PartBase Clone()
- {
- return new Wheel(IsBroken);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment