JohnJuly

Homework46

Jul 25th, 2025 (edited)
830
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.20 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace Homework46
  5. {
  6.     internal class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             Supermarket supermarket = new Supermarket();
  11.             supermarket.Run();
  12.         }
  13.     }
  14.  
  15.     class Supermarket
  16.     {
  17.         private Queue<Customer> _queue;
  18.         private List<Product> _products;
  19.  
  20.         public Supermarket()
  21.         {
  22.             _products = new List<Product>()
  23.             {
  24.                 new Product("Молоко", 50),
  25.                 new Product("Кефир", 60),
  26.                 new Product("Колбаса", 300),
  27.                 new Product("Сосиски", 200),
  28.                 new Product("Сыр", 400),
  29.                 new Product("Пиво", 100),
  30.                 new Product("Сок", 80),
  31.                 new Product("Газировка", 70),
  32.                 new Product("Печенье", 150),
  33.                 new Product("Хлеб", 40),
  34.                 new Product("Йогурт", 75),
  35.                 new Product("Сметана", 90),
  36.                 new Product("Пельмени", 250)
  37.             };
  38.  
  39.             int minimalQueueSize = 10;
  40.             int maximalQueueSize = 50;
  41.  
  42.             Money = 0;
  43.             _queue = new Queue<Customer>();
  44.  
  45.             int queueSize = Utility.GetRandomNumber(maximalQueueSize, minimalQueueSize);
  46.  
  47.             for (int i = 0; i < queueSize; i++)
  48.             {
  49.                 _queue.Enqueue(new Customer(_products));
  50.             }
  51.         }
  52.  
  53.         public int Money { get; private set; }
  54.         public int QueueSize => _queue.Count;  
  55.  
  56.         public void Run()
  57.         {
  58.             const string CommandServeClient = "serve";
  59.             const string CommandAddClientInQueue = "add";
  60.             const string CommandShowMoney = "money";
  61.             const string CommandExit = "exit";
  62.  
  63.             bool continueAdministering = true;
  64.  
  65.             while (continueAdministering)
  66.             {
  67.                 Console.Clear();
  68.                 Console.WriteLine("=== Панель управления супермаркетом ===");
  69.                 Console.WriteLine($"1.Введите `{CommandServeClient}` чтобы обслужить следующего клиента (в очереди {QueueSize} человек)");
  70.                 Console.WriteLine($"2.Введите `{CommandAddClientInQueue}` чтобы добавить нового клиента в очередь");
  71.                 Console.WriteLine($"3.Введите `{CommandShowMoney}` чтобы показать состояние кассы (в кассе {Money} рублей)");
  72.                 Console.WriteLine($"4.Введите `{CommandExit}` чтобы выйти из программы");
  73.  
  74.                 Console.Write("Выберите действие: ");
  75.  
  76.                 string choice = Console.ReadLine();
  77.  
  78.                 switch (choice)
  79.                 {
  80.                     case CommandServeClient:
  81.                         HandleServeClient();
  82.                         break;
  83.  
  84.                     case CommandAddClientInQueue:
  85.                         HandleAddClient();
  86.                         break;
  87.  
  88.                     case CommandShowMoney:
  89.                         HandleShowMoney();
  90.                         break;
  91.  
  92.                     case CommandExit:
  93.                         Console.WriteLine("Завершение работы...");
  94.                         continueAdministering = false;
  95.                         break;
  96.  
  97.                     default:
  98.                         HandleInvalidInput();
  99.                         break;
  100.                 }
  101.             }
  102.         }
  103.  
  104.         private void HandleServeClient()
  105.         {
  106.             if (QueueSize > 0)
  107.             {
  108.                 Customer nextCustomer = GetNextCustomer();
  109.  
  110.                 if (nextCustomer != null)
  111.                 {
  112.                     Console.WriteLine($"Обслуживается клиент номер {nextCustomer.Number}, у него {nextCustomer.Money} рублей.");
  113.                     ServeCustomer(nextCustomer);
  114.                 }
  115.                 else
  116.                 {
  117.                     Console.WriteLine("Произошла ошибка при получении следующего клиента.");
  118.                 }
  119.             }
  120.             else
  121.             {
  122.                 Console.WriteLine("Очередь пуста!");
  123.             }
  124.  
  125.             Utility.PressAnyKeyToContinue();
  126.         }
  127.  
  128.         private void HandleAddClient()
  129.         {
  130.             AddCustomer(new Customer(_products));
  131.             Console.WriteLine("Новый клиент добавлен в очередь.");
  132.             Utility.PressAnyKeyToContinue();
  133.         }
  134.  
  135.         private void HandleShowMoney()
  136.         {
  137.             Console.WriteLine($"В кассе {Money} рублей.");
  138.             Utility.PressAnyKeyToContinue();
  139.         }
  140.  
  141.         private void HandleInvalidInput()
  142.         {
  143.             Console.WriteLine("Некорректный ввод. Попробуйте еще раз.");
  144.             Utility.PressAnyKeyToContinue();
  145.         }
  146.  
  147.         private void ServeCustomer(Customer customer)
  148.         {
  149.             if (customer == null)
  150.                 return;
  151.  
  152.             Console.WriteLine($"Клиент номер {customer.Number}, у него {customer.Money} рублей.");
  153.             Console.WriteLine("Корзина клиента:");
  154.  
  155.             foreach (var product in customer.Cart)
  156.             {
  157.                 Console.WriteLine($"  - {product.Name}, Цена: {product.Price} рублей");
  158.             }
  159.  
  160.             int totalSum = customer.CalculateCartTotal();
  161.             Console.WriteLine($"Итоговая сумма: {totalSum} рублей");
  162.  
  163.             if (customer.TryBuy(out int amountToPay))
  164.             {
  165.                 Money += amountToPay;
  166.                 Console.WriteLine($"Клиент успешно оплатил покупки.");
  167.             }
  168.             else
  169.             {
  170.                 Console.WriteLine($"Клиент не смог оплатить все товары.");
  171.             }
  172.  
  173.             Console.WriteLine($"Клиент купил:");
  174.  
  175.             foreach (var product in customer.ShoppingBag)
  176.             {
  177.                 Console.WriteLine($"  - {product.Name}, Цена: {product.Price} рублей");
  178.             }
  179.  
  180.             Console.WriteLine($"У клиента осталось {customer.Money} рублей.");
  181.         }
  182.  
  183.         private Customer GetNextCustomer()
  184.         {
  185.             if (_queue.Count == 0)
  186.             {
  187.                 return null;
  188.             }
  189.  
  190.             return _queue.Dequeue();
  191.         }
  192.  
  193.         private void AddCustomer(Customer customer)
  194.         {
  195.             _queue.Enqueue(customer);
  196.         }
  197.     }
  198.  
  199.     class Customer
  200.     {
  201.         private static int s_number = 0;
  202.         private List<Product> _cart;
  203.         private List<Product> _shoppingBag;
  204.  
  205.         public Customer(List<Product> availableProducts)
  206.         {
  207.             int minimalMoney = 200;
  208.             int maximalMoney = 6000;
  209.  
  210.             Money = Utility.GetRandomNumber(maximalMoney, minimalMoney);
  211.             Number = ++s_number;
  212.             _cart = new List<Product>();
  213.             _shoppingBag = new List<Product>();
  214.  
  215.             FillCart(availableProducts);
  216.         }
  217.  
  218.         public int Money { get; private set; }
  219.         public int Number { get; private set; }
  220.  
  221.         public List<Product> Cart => new List<Product>(_cart);
  222.         public List<Product> ShoppingBag => new List<Product>(_shoppingBag);
  223.  
  224.         public int CalculateCartTotal()
  225.         {
  226.             int total = 0;
  227.  
  228.             foreach (Product product in _cart)
  229.             {
  230.                 total += product.Price;
  231.             }
  232.  
  233.             return total;
  234.         }
  235.  
  236.         public bool TryBuy(out int amountToPay)
  237.         {
  238.             amountToPay = 0;
  239.             int sum = CalculateCartTotal();
  240.  
  241.             if (!CanPurchase(sum))
  242.             {
  243.                 return false;
  244.             }
  245.  
  246.             amountToPay = sum;
  247.             PayForProducts(sum);
  248.  
  249.             return true;
  250.         }
  251.  
  252.         private bool CanPurchase(int sum)
  253.         {
  254.             if (Money < sum)
  255.             {
  256.                 List<Product> productsToRemove = new List<Product>();
  257.  
  258.                 while (Money < sum && _cart.Count > 0)
  259.                 {
  260.                     int deletedProductIndex = Utility.GetRandomNumber(_cart.Count - 1, 0);
  261.                     Product productToRemove = _cart[deletedProductIndex];
  262.                     Console.WriteLine($"У клиента недостаточно средств." +
  263.                         $" Он откладывает {productToRemove.Name} по цене {productToRemove.Price} рублей.");
  264.  
  265.                     sum -= productToRemove.Price;
  266.                     productsToRemove.Add(productToRemove);
  267.                 }
  268.  
  269.                 foreach (Product product in productsToRemove)
  270.                 {
  271.                     _cart.Remove(product);
  272.                 }
  273.  
  274.                 if (Money < sum)
  275.                 {
  276.                     Console.WriteLine("Клиент ушел, ничего не купив.");
  277.                     _cart.Clear();
  278.  
  279.                     return false;
  280.                 }
  281.             }
  282.  
  283.             return true;
  284.         }
  285.  
  286.         private void PayForProducts(int sum)
  287.         {
  288.             Money -= sum;
  289.             Console.WriteLine($"Клиент отдает {sum} рублей под рассчет и складывает купленные продукты в пакет.");
  290.  
  291.             foreach (var product in _cart)
  292.             {
  293.                 _shoppingBag.Add(product);
  294.             }
  295.  
  296.             _cart.Clear();
  297.         }
  298.  
  299.         private void FillCart(List<Product> availableProducts)
  300.         {
  301.             int minimalProductNumber = 2;
  302.             int maximalProductNumber = 19;
  303.             int productNumber = Utility.GetRandomNumber(maximalProductNumber, minimalProductNumber);
  304.  
  305.             for (int i = 0; i < productNumber; i++)
  306.             {
  307.                 _cart.Add(availableProducts[Utility.GetRandomNumber(availableProducts.Count - 1, 0)]);
  308.             }
  309.         }
  310.     }
  311.  
  312.     class Product
  313.     {
  314.         public Product(string name, int price)  
  315.         {
  316.             Name = name;
  317.             Price = price;
  318.         }
  319.  
  320.         public int Price { get; private set; }
  321.         public string Name { get; private set; }
  322.     }
  323.  
  324.     public static class Utility
  325.     {
  326.         private static Random _random = new Random();
  327.  
  328.         public static int GetRandomNumber(int maximalNumber, int minimalNumber = 0)
  329.         {
  330.             if (minimalNumber > maximalNumber)
  331.             {
  332.                 throw new ArgumentException("Минимальное число должно быть меньше максимального.");
  333.             }
  334.  
  335.             return _random.Next(minimalNumber, maximalNumber + 1);
  336.         }
  337.  
  338.         public static void PressAnyKeyToContinue()
  339.         {
  340.             Console.WriteLine("\nНажмите любую кнопку чтобы продолжить.");
  341.             Console.ReadKey(true);
  342.         }
  343.     }
  344. }
Advertisement
Comments
Add Comment
Please, Sign In to add comment