Tohir5258

OOP_13

Nov 15th, 2025 (edited)
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.85 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace OOP_13
  5. {
  6.     internal class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             Simulation simulation = new Simulation();
  11.             simulation.Run();
  12.         }
  13.     }
  14.  
  15.     public class Part
  16.     {
  17.         public Part(string name, decimal price, decimal workPrice)
  18.         {
  19.             Name = name;
  20.             Price = price;
  21.             WorkPrice = workPrice;
  22.         }
  23.  
  24.         public string Name { get; }
  25.         public decimal Price { get; }
  26.         public decimal WorkPrice { get; }
  27.  
  28.         public override bool Equals(object obj)
  29.         {
  30.             return obj is Part part && Name == part.Name;
  31.         }
  32.  
  33.         public override int GetHashCode()
  34.         {
  35.             return Name.GetHashCode();
  36.         }
  37.  
  38.         public override string ToString()
  39.         {
  40.             return $"{Name} (Цена: {Price}р, Работа: {WorkPrice}р)";
  41.         }
  42.     }
  43.  
  44.     public class CarPart
  45.     {
  46.         public CarPart(Part partDefinition, bool isBroken = false)
  47.         {
  48.             PartDefinition = partDefinition;
  49.             IsBroken = isBroken;
  50.         }
  51.  
  52.         public Part PartDefinition { get; }
  53.         public bool IsBroken { get; set; }
  54.  
  55.         public override string ToString()
  56.         {
  57.             string status = IsBroken ? "СЛОМАНА" : "ЦЕЛАЯ";
  58.             return $"{PartDefinition.Name} [{status}]";
  59.         }
  60.     }
  61.  
  62.     public class Car
  63.     {
  64.         public Car(string model)
  65.         {
  66.             Model = model;
  67.         }
  68.  
  69.         public string Model { get; }
  70.         public List<CarPart> Parts { get; } = new List<CarPart>();
  71.  
  72.         public void AddPart(CarPart part)
  73.         {
  74.             Parts.Add(part);
  75.         }
  76.  
  77.         public List<CarPart> GetBrokenParts()
  78.         {
  79.             List<CarPart> brokenParts = new List<CarPart>();
  80.  
  81.             foreach (CarPart part in Parts)
  82.             {
  83.                 if (part.IsBroken)
  84.                 {
  85.                     brokenParts.Add(part);
  86.                 }
  87.             }
  88.  
  89.             return brokenParts;
  90.         }
  91.  
  92.         public bool IsFullyRepaired()
  93.         {
  94.             foreach (CarPart part in Parts)
  95.             {
  96.                 if (part.IsBroken)
  97.                 {
  98.                     return false;
  99.                 }
  100.             }
  101.  
  102.             return true;
  103.         }
  104.  
  105.         public void PrintStatus()
  106.         {
  107.             const int LineWidth = 20;
  108.  
  109.             Console.WriteLine($"\n--- Машина: {Model} ---");
  110.             Console.WriteLine("Состояние деталей:");
  111.  
  112.             for (int i = 0; i < Parts.Count; i++)
  113.             {
  114.                 Console.WriteLine($"  {i + 1}. {Parts[i]}");
  115.             }
  116.  
  117.             Console.WriteLine(new string('-', LineWidth));
  118.         }
  119.     }
  120.  
  121.     public class Warehouse
  122.     {
  123.         private Dictionary<Part, int> _stock = new Dictionary<Part, int>();
  124.  
  125.         public void AddStock(Part part, int quantity)
  126.         {
  127.             if (_stock.ContainsKey(part))
  128.             {
  129.                 _stock[part] += quantity;
  130.             }
  131.             else
  132.             {
  133.                 _stock[part] = quantity;
  134.             }
  135.  
  136.             Console.WriteLine($"[Склад] Добавлено: {part.Name} (x{quantity}). Всего на складе: {_stock[part]}");
  137.         }
  138.  
  139.         public bool HasPart(Part part)
  140.         {
  141.             return _stock.ContainsKey(part) && _stock[part] > 0;
  142.         }
  143.  
  144.         public bool TryTakePart(Part part)
  145.         {
  146.             if (HasPart(part))
  147.             {
  148.                 _stock[part]--;
  149.                 Console.WriteLine($"[Склад] Взята деталь: {part.Name}. Осталось: {_stock[part]}");
  150.                 return true;
  151.             }
  152.  
  153.             Console.WriteLine($"[Склад] ОШИБКА: Детали '{part.Name}' нет на складе.");
  154.             return false;
  155.         }
  156.  
  157.         public void PrintStock()
  158.         {
  159.             const int LineWidth = 20;
  160.  
  161.             Console.WriteLine("--- Состояние склада ---");
  162.  
  163.             if (_stock.Count == 0)
  164.             {
  165.                 Console.WriteLine("Склад пуст.");
  166.                 return;
  167.             }
  168.  
  169.             foreach (var entry in _stock)
  170.             {
  171.                 Console.WriteLine($"{entry.Key.Name}: {entry.Value} шт.");
  172.             }
  173.  
  174.             Console.WriteLine(new string('-', LineWidth));
  175.         }
  176.     }
  177.  
  178.     public class AutoService
  179.     {
  180.         private const decimal RefusalFineBefore = 500m;
  181.         private const decimal RefusalFinePerPart = 150m;
  182.  
  183.         private readonly Queue<Car> _carsInQueue = new Queue<Car>();
  184.         private readonly Warehouse _warehouse = new Warehouse();
  185.  
  186.         public AutoService(decimal initialBalance)
  187.         {
  188.             Balance = initialBalance;
  189.             Console.WriteLine($"Автосервис открыт! Начальный баланс: {Balance}р.");
  190.         }
  191.  
  192.         public decimal Balance { get; private set; }
  193.        
  194.         public void AddPartToStock(Part part, int quantity)
  195.         {
  196.             _warehouse.AddStock(part, quantity);
  197.         }
  198.  
  199.         public void AddToQueue(Car car)
  200.         {
  201.             _carsInQueue.Enqueue(car);
  202.             Console.WriteLine($"[Очередь] Машина '{car.Model}' добавлена в очередь.");
  203.         }
  204.  
  205.         public void ServeNext()
  206.         {
  207.             const string AgreeRepairCommand = "1";
  208.             const string RefuseRepairsCommand = "2";
  209.  
  210.             if (_carsInQueue.Count == 0)
  211.             {
  212.                 Console.WriteLine("В очереди нет машин. Сервис отдыхает.");
  213.                 return;
  214.             }
  215.  
  216.             Car currentCar = _carsInQueue.Dequeue();
  217.             Console.WriteLine($"\n======= Начинаем обслуживание машины: {currentCar.Model} =======");
  218.             currentCar.PrintStatus();
  219.  
  220.             Console.WriteLine("Что делаем с машиной?");
  221.             Console.WriteLine($"{AgreeRepairCommand}. Начать ремонт");
  222.             Console.WriteLine($"{RefuseRepairsCommand}. Отказаться от ремонта (Штраф: " + RefusalFineBefore + "р)");
  223.  
  224.             string choice = Console.ReadLine();
  225.  
  226.             if (choice == RefuseRepairsCommand)
  227.             {
  228.                 HandleRefusal(currentCar, true);
  229.                 return;
  230.             }
  231.  
  232.             ProcessRepair(currentCar);
  233.         }
  234.  
  235.         public void PrintStatus()
  236.         {
  237.             const int LineWidth = 30;
  238.  
  239.             Console.WriteLine("\n===== СТАТУС АВТОСЕРВИСА =====");
  240.             Console.WriteLine($"Текущий баланс: {Balance}р.");
  241.             Console.WriteLine($"Машин в очереди: {_carsInQueue.Count}");
  242.             _warehouse.PrintStock();
  243.             Console.WriteLine(new string('=', LineWidth));
  244.         }
  245.  
  246.         private void ProcessRepair(Car car)
  247.         {
  248.             const int RefuseRepairsCommand = 0;
  249.             const int ErrorCommand = -1;
  250.  
  251.             while (car.IsFullyRepaired() == false)
  252.             {
  253.                 int chosenIndex = ShowRepairMenuAndGetInput(car);
  254.  
  255.                 switch (chosenIndex)
  256.                 {
  257.                     case ErrorCommand:
  258.                         Console.WriteLine("Неверный ввод. Попробуйте снова.");
  259.                         continue;
  260.  
  261.                     case RefuseRepairsCommand:
  262.                         HandleRefusal(car, false);
  263.                         return;
  264.  
  265.                     default:
  266.                         PerformPartReplacement(car, chosenIndex - 1);
  267.                         break;
  268.                 }
  269.             }
  270.  
  271.             if (car.IsFullyRepaired())
  272.             {
  273.                 Console.WriteLine($"\n======= РЕМОНТ ЗАВЕРШЕН: {car.Model} =======");
  274.                 Console.WriteLine("Все детали исправны. Машина готова!");
  275.             }
  276.  
  277.             Console.WriteLine($"Итоговый баланс сервиса: {Balance}р.");
  278.         }
  279.  
  280.         private int ShowRepairMenuAndGetInput(Car car)
  281.         {
  282.             const int RefuseRepairsCommand = 0;
  283.  
  284.             Console.WriteLine("\n--- Процесс ремонта ---");
  285.             car.PrintStatus();
  286.  
  287.             Console.WriteLine("Доступные детали для замены (введите номер):");
  288.  
  289.             for (int i = 0; i < car.Parts.Count; i++)
  290.             {
  291.                 Console.WriteLine($"  {i + 1}. {car.Parts[i]}");
  292.             }
  293.  
  294.             Console.WriteLine($"{RefuseRepairsCommand}. Отказаться от ремонта (Штраф за непочиненные детали)");
  295.  
  296.             if (int.TryParse(Console.ReadLine(), out int partIndex) == false || partIndex < 0 || partIndex > car.Parts.Count)
  297.             {
  298.                 return -1;
  299.             }
  300.  
  301.             return partIndex;
  302.         }
  303.  
  304.         private void PerformPartReplacement(Car car, int partIndex)
  305.         {
  306.             CarPart selectedPart = car.Parts[partIndex];
  307.             Part partTypeToReplace = selectedPart.PartDefinition;
  308.  
  309.             if (_warehouse.TryTakePart(partTypeToReplace) == false)
  310.             {
  311.                 Console.WriteLine($"ОШИБКА: Детали '{partTypeToReplace.Name}' нет на складе! Выберите другую деталь.");
  312.                 return;
  313.             }
  314.  
  315.             if (selectedPart.IsBroken)
  316.             {
  317.                 decimal payment = partTypeToReplace.Price + partTypeToReplace.WorkPrice;
  318.                 Balance += payment;
  319.                 selectedPart.IsBroken = false;
  320.  
  321.                 Console.WriteLine($"УСПЕХ: Деталь '{partTypeToReplace.Name}' заменена.");
  322.                 Console.WriteLine($"Получено {payment}р. (Деталь: {partTypeToReplace.Price}р, Работа: {partTypeToReplace.WorkPrice}р)");
  323.                 Console.WriteLine($"Новый баланс сервиса: {Balance}р.");
  324.             }
  325.             else
  326.             {
  327.                 Console.WriteLine($"ВНИМАНИЕ: Заменена целая деталь '{partTypeToReplace.Name}'. Оплата не взимается.");
  328.             }
  329.         }
  330.  
  331.         private void HandleRefusal(Car car, bool beforeRepair)
  332.         {
  333.             if (beforeRepair)
  334.             {
  335.                 Balance += RefusalFineBefore;
  336.                 Console.WriteLine($"[Отказ] Клиент отказался до ремонта. Штраф {RefusalFineBefore}р. Баланс: {Balance}р.");
  337.             }
  338.             else
  339.             {
  340.                 int brokenPartsCount = car.GetBrokenParts().Count;
  341.                 decimal fine = brokenPartsCount * RefusalFinePerPart;
  342.                 Balance += fine;
  343.  
  344.                 Console.WriteLine($"[Отказ] Клиент отказался во время ремонта. Непочиненных деталей: {brokenPartsCount}.");
  345.                 Console.WriteLine($"Штраф {fine}р. Баланс: {Balance}р.");
  346.             }
  347.  
  348.             Console.WriteLine($"Машина '{car.Model}' покидает сервис.");
  349.         }
  350.     }
  351.  
  352.     public class Simulation
  353.     {
  354.         private readonly AutoService _service;
  355.         private readonly Part _engine;
  356.         private readonly Part _wheel;
  357.         private readonly Part _sparkPlug;
  358.  
  359.         public Simulation()
  360.         {
  361.             _engine = new Part("Двигатель", 50000m, 10000m);
  362.             _wheel = new Part("Колесо", 5000m, 500m);
  363.             _sparkPlug = new Part("Свеча зажигания", 500m, 200m);
  364.             _service = new AutoService(100000m);
  365.         }
  366.  
  367.         public void Run()
  368.         {
  369.             SetupWarehouse();
  370.             SetupQueue();
  371.  
  372.             _service.PrintStatus();
  373.  
  374.             Console.WriteLine("\n>>> Начинаем обслуживание 1-й машины <<<");
  375.             _service.ServeNext();
  376.  
  377.             Console.WriteLine("\n>>> Начинаем обслуживание 2-й машины <<<");
  378.             _service.ServeNext();
  379.  
  380.             Console.WriteLine("\n>>> Начинаем обслуживание 3-й машины <<<");
  381.             _service.ServeNext();
  382.  
  383.             Console.WriteLine("\n\n--- СИМУЛЯЦИЯ ЗАВЕРШЕНА ---");
  384.             _service.PrintStatus();
  385.  
  386.             Console.WriteLine("\nНажмите Enter для выхода.");
  387.             Console.ReadLine();
  388.         }
  389.  
  390.         private void SetupWarehouse()
  391.         {
  392.             _service.AddPartToStock(_engine, 2);
  393.             _service.AddPartToStock(_wheel, 10);
  394.             _service.AddPartToStock(_sparkPlug, 50);
  395.         }
  396.  
  397.         private void SetupQueue()
  398.         {
  399.             Car carFirst = CreateCar("Volvo XC90",
  400.                 (_engine, true),
  401.                 (_wheel, false),
  402.                 (_wheel, true),
  403.                 (_wheel, false),
  404.                 (_wheel, false),
  405.                 (_sparkPlug, false)
  406.             );
  407.  
  408.             Car carSecond = CreateCar("Lada Granta",
  409.                 (_engine, false),
  410.                 (_wheel, false),
  411.                 (_sparkPlug, true),
  412.                 (_sparkPlug, true)
  413.             );
  414.  
  415.             Car carThird = CreateCar("BMW X5",
  416.                 (_engine, true)
  417.             );
  418.  
  419.             _service.AddToQueue(carFirst);
  420.             _service.AddToQueue(carSecond);
  421.             _service.AddToQueue(carThird);
  422.         }
  423.  
  424.         private Car CreateCar(string model, params (Part part, bool isBroken)[] parts)
  425.         {
  426.             Car car = new Car(model);
  427.  
  428.             foreach (var (part, isBroken) in parts)
  429.             {
  430.                 car.AddPart(new CarPart(part, isBroken));
  431.             }
  432.  
  433.             return car;
  434.         }
  435.     }
  436. }
  437.  
Tags: OOP_13
Advertisement
Add Comment
Please, Sign In to add comment